Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect frontend (js) and backend (php) in a local application?

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!

like image 493
KAFFEECKO Avatar asked Oct 14 '25 16:10

KAFFEECKO


1 Answers

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.

like image 192
ssc-hrep3 Avatar answered Oct 17 '25 05:10

ssc-hrep3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!