I am trying to run a php function based on a button click using jquery but not through a POST. It is a function that is using array data that was printed on the form. Is this possible?
-
3Yes, this is possible. Next...Stephen– Stephen2010-11-02 19:00:08 +00:00Commented Nov 2, 2010 at 19:00
-
Yes, it's probably possible. Can you show us what you've written so far and explain what you need help with?lonesomeday– lonesomeday2010-11-02 19:00:45 +00:00Commented Nov 2, 2010 at 19:00
5 Answers
You are looking for jQuery's Ajax functions.
You can't "run" a PHP command from within JavaScript, but you can make an asychronous call to another PHP script without changing the page.
Comments
You would have to use either POST or GET to pass HTML data from the page to a php function. You cannot call a PHP function directly from javascript. Does your PHP function only utilize the GET parameter to retrieve data?
You can use the jQuery ajax function for either:
var formData = $('#formName').serialize();
$.ajax({
type: "GET",//change to POST if your PHP script can use it
url: "some.php",//file where your php function will be run.
data: formData,
dataType: 'JSON',
success: function(msg){
alert( "Data Saved: " + msg );//Will show an alert box if the GET was a success
}
});
php:
$data = $_SERVER['GET'];
print(saveData($data));
function saveData($arr){
//Insert data into MySQL table
//display JSON encoded result for AJAX result
if(success)
return json_encode(true);
return json_encode(false);
}
2 Comments
You can not run a PHP function from the jquery script, and thanks God you cannot do that. Just think about how it would be dangerous.
Anyway, just look for AJAX. I think that just write you the code will not be as use-full as provide your going to study it. So go and study AJAX so that you will be able to make an async call to a php script that will elaborate GET/POST variable and call the php function.
Or just look at the post() and the get() functions of jquery.