4

So confused about how to connect frontend and backend?

Suppose I've got an object obj and var jsonText = JSON.stringify(obj);

how can I send this jsonText to backend (locally, non remote server, no database), using php to get this data and then save the content as a single new JSON file?

Thanks a lot!

KAFFEECKO
  • 173
  • 1
  • 2
  • 10
  • [Ajax.](http://api.jquery.com/jquery.ajax/) – Script47 Dec 30 '15 at 23:07
  • @Script47 but how to define the post target address? – KAFFEECKO Dec 30 '15 at 23:10
  • Using the `url` parameter which is available. – Script47 Dec 30 '15 at 23:11
  • Check [this page](http://stackoverflow.com/questions/1678010/php-server-on-local-machine) to see how to run local php application. – Ahamed Dec 30 '15 at 23:13
  • 1
    it would be: `/your-file.php` which is located on `http://localhost/` .. the full path might be something like `http://localhost/your-file.php` and as @Ahamed posted, make sure you have a web server running otherwise what I said is not possible. – Clay Dec 30 '15 at 23:14
  • @Script47 thanks :) If the target file is `example.php`, what would be the content of this `example.php`? – KAFFEECKO Dec 30 '15 at 23:15
  • @KAFFEECKO have you looked at the link I provided? – Script47 Dec 30 '15 at 23:16
  • StackOverflow is not a code writing service... please try some things out and come back when you get stuck. There are many tutorials out there on how to do this basic task. At the very least, here is one example I found that may be useful for you: http://stackoverflow.com/a/24722126/747678 – Clay Dec 30 '15 at 23:16
  • @Clayton ya... i've tried using XMLHttpRequest send the data to php earlier, then suddenly my mind's gone blank... – KAFFEECKO Dec 30 '15 at 23:24

1 Answers1

3

You need to query your data from a database or from somewhere else in PHP. Then, you can echo it with PHP in a JSON format. In a second step, you can use jQuery or plain JavaScript to make an Ajax call to this PHP file and make something with it.

PHP (data.json.php):

<?php
  header('Content-Type: application/json');
  $output = array();
  // query the data from somewhere
  $output['data'] = "1234";
  echo json_encode($output); // json_encode creates the json-specific formatting
?>

JavaScript (jQuery):

$.ajax({
   url: "data.json.php",
   success: function(result){
      console.log(result);
   }
});

The code is untested, but I think you should get the idea.

ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87