Updating MYSQL with jQuery / AJAX

I am trying to create a mobile application using PhoneGap and jQuery Mobile. In my application, I have a page where there is a link to a PHP file that updates MYSQL and goes to the next page. But with PhoneGap, I need to have all the PHP files on an external server, so I cannot use the current solution for this application.

This is the PHP that I use to update MYSQL

<?php $var = @$_GET['id'] ; $con = mysql_connect("localhost","username","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("database", $con); mysql_query("UPDATE table SET condition=true WHERE ID= \"$var\" "); header('Location: http://1.2.3.4/test'); mysql_close($con); ?> 

So, how can I run this PHP when the user clicks a button? With jQuery / AJAX, I suppose?

+7
source share
4 answers

Suppose the above PHP code is in the update.php file. Then you can use the following code -

 <head> <script src="jquery.js"></script> <script> function UpdateRecord(id) { jQuery.ajax({ type: "POST", url: "update.php", data: 'id='+id, cache: false, success: function(response) { alert("Record successfully updated"); } }); } </script> </head> <body> <input type="button" id="button_id" value="Update" onClick="UpdateRecord(1);"> </body> 

Just pass a valid identifier in the UpdateRecord function. Put your PHP code in the update.php file. To be on the safer side, in your PHP code replace $var = @$_GET['id'] ; on $var = @$_POST['id'] ; and check if this works for you

+8
source
 <head> <script src="jquery.js"></script> <script> function UpdateRecord(id) { jQuery.ajax({ type: "POST", data: 'id='+id, // <-- put on top url: "update.php", cache: false, success: function(response) { alert("Record successfully updated"); } }); } </script> </head> <body> <input type="button" id="button_id" value="Update" onClick="UpdateRecord(1);"> </body> 

Those codes suggested by Sachyn Kosare work, the only thing is that the line data: 'id='+id should be at the top of the url: "update.php"

And you can use $var = $_POST['id']; for your PHP.

+2
source

let's say that your button has a clickme , you associate an event handler with it as follows. I use the on selector to avoid cases where the code is executed when the button does not exist on the page .. you can very well bind the click handler

 $(document).on("click","#clickme",function(){ $.ajax({ type:"POST", //GET - update query should be POST url: my_endpoint.php, //your php end point data: {jsonKey1:jsonValue1}, success: function(data){ //if success //do necessary things with data } }) }); 

Is this what you are looking for?

+1
source

Do something in your successful function

 success: function(response) { window.location = response; } 

and html should contain

And in php do something like this

 mysql_query('blah blah'); mysql_close($con); echo "http://1.2.3.4/test"; 
0
source

All Articles