I am trying to increment a number and update the database and then display the number without refreshing the page. I am just wondering, is there a way to read/update MySQL using JavaScript?
I tried searching around, and it seems you have to call another program that changes the values for you. Right now I have
<?php
require ("connect.php");
echo "connected!<br>";
$extract = mysql_query("SELECT * FROM articles")or die ("Not working");
//$numrows = mysql_num_row($extract);
while ($row = mysql_fetch_assoc($extract)) {
$id = $row['id'];
$article = $row['article'];
$thumbsup= $row['thumbs_up'];
$thumbsdown = $row['thumbs_down'];
$date = $row['date_time'];
$username = $row['username'];
mysql_query("UPDATE articles SET thumbsup = 1");
}
?>
So I am wondering, once this page updates the database, how do you get the updated value into the JavaScript function? Right now I am just reading it from a file
xmlhttp.open("GET", "http://localhost/ajax/folder5/includes/a.txt", true);
Thanks a lot for your help!
Since you already have a server-side script that fetches data all you need to do is return it as a response to your
XMLHttpRequestand handle it by using acallbackfunction. Assuming you want to return$id, $article, $thumbsup..etc you can put it in an array and encode it, as suggested you can usejson_encode(). In your PHP script you can do something like:And in your Javascript you may need to add a response handler, like:
Of couse you need to change the way you request data instead of using GET to text file, in this case you may want to request directly to the PHP script and return the result:
Essentially, that’s all you need.
For more brief example you can refer here.
Also check jQuery’s ajax functions as it may help you a lot.
**EDIT**
Added additional info.
Since we’re returning a result which is JSON (by using json_encode), you need to add a header for the content type, add this at the top most part of your script just below the
<?phppart:And based on the example above assuming we have this as the response:
Once you receive this in your
callbackfunction this will be translated to something like (with sample values):which is given to the result variable:
To be sure we get the response evaluated we will use
eval()to the result string so you can get values off of it by accessing properties. Take this for example:Once that’s done you can access properties from the result variable like
result.ThumbsUpwhich gives you30based on the example. You can then assign that value wherever you need it to be like:document.getElementById('c').innerHTML = result.ThumbsUp;I hope this gives you a clearer idea.A note to using
eval(), read this.