0

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?

2
  • 3
    Yes, this is possible. Next... Commented 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? Commented Nov 2, 2010 at 19:00

5 Answers 5

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3

Yes it is possible. Just do $.get with jquery and call the php page. Does that make sense?

Comments

3

If by "not through a POST" you mean "without an AJAX call to a PHP page on my server" then no, it's not possible. If you mean "without a POST" then yes, you can use a GET. :)

Comments

3

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

I'm not saying you're wrong, per se, but from jQuery's AJAX documentation: The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
If you omit, the type parameter, then GET is default. The example above is to illustrate how to change it if needed. However, in most cases, the only reason one would use GET over post is if the script being called requires it.
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.