0

I am using basic PHP & AJAX and I want to post data that i have selected from mysql database to a link online and fetch the response sent back to be used in update other information. I am using AJAX to post the data, but i cannot fetch the data sent back to use to update information.

Is it possible to just use PHP directly? how can it be done? What is the best way ?

Code:

$sql = $conn->query("SELECT * FROM hospitals");

if($sql){

    // $json_array = array();

    while($row = $sql->fetch_assoc()){

$output = '{"h_code": "' . $row['h_code'] . '", "h_name": "' . $row['h_name'] . '"}';

?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
    $.ajax({
            url: 'http://example.com/api/link',
            method: 'POST',
            data: <?php echo $output; ?>,
            success: function(data){
                console.log(data);
            }
        });
</script>
<?php
    $update = $conn->query("UPDATE hospital SET h_online_id=  ");
}
}

the response from AJAX call 'data' returns value from online database which i want to update a column from in the local database.

Emil Kitua
  • 59
  • 8
  • 1
    please don't construct a json-string like this. Build an array, then json_encode that. You are missing a `'` at the end there. – Jeff Sep 13 '18 at 09:22
  • 1
    I would also recommend that you read [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming). PHP is server side and Javascript is client side. – M. Eriksson Sep 13 '18 at 09:22
  • thank you @Jeff i edited the code – Emil Kitua Sep 13 '18 at 09:29

1 Answers1

2

You have to be careful here... PHP is server side and JavaScript Client (You would write that Javascript Code to the page X times!) Why don't you use CURL for this?

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://example.com/api/link");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
            "postvar1=value1&postvar2=value2&postvar3=value3"); // modify $output

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec($ch);

curl_close ($ch);

// Further processing ...
if ($server_output == "OK") { ... } else { ... }
Dieter Kräutl
  • 657
  • 4
  • 8