how to call a php script from javascript?

how to call a php script from javascript?

I have always wondered how to call a php script and send GET data from javascript code. It was very important for me as in many projects i have worked i never wanted to header redirect to original php page after delete, edit operations which is really a mess.

jQuery has revolutionized the way we look at javascript and it has certainly bridged the javascript(client side) and php (server side).

so how do you call a php script from javascript?

i am going to show how with just one line of javascript code, you can send GET data to php script and get the output from php script show in javascript inside span or div.

A simple example would be a form registration checking for user availability.

demo.PNG

Logic is simple.you call a php script upon clicking check availability and javascript onClick event fires and the php script returns the data with “available” or “not available”. i have used jquery here.

Take a look at onclick event.

<td><input name="user_name" type="text" id="user_name" class="required"> 
              <input name="btnAvailable" type="submit" id="btnAvailable" 
			  onclick='$.get("checkuser.php",{ cmd: "check", user: $("#user_name").val() } ,function(data){ $("#checkid").html(data); });'
			  value="Check Availability"> <span style="color:red; font: bold 12px verdana; " id="checkid" ></span> 
            </td>

This single line of code sends GET data to check.php?cmd=check&user=demo. Isnt that wonderful? Havnt we bridged php and javascript.

Here is some explanation.

checkuser.php -> name of php script to call
cmd,user -> GET parameters
$("#user_name").val() -> Gets text box value with id user_name;
$("#checkid").html(data); -> Shows the output of php script within a span

Hope this helps!

Similar Posts:

Tags:

Balakrishnan Prabhu

Mr. Balakrishnan Prabhu is the founder of Corpocrat magazine. He is also the founder of Best Citizenships (BC), assisting wealthy individuals with with global citizenship and residency programs in Europe. His other interests are Linux, Machine learning, Wordpress, etc. You can contact him here

  • http://nine95.com Michael Pedzotti

    I have been looking for this everywhere! Thanks. Now to try it out on a plugin I am playing with. I wanted to be able to update the value of an input text box after the contents were validated but couldn’t work out how to call the php function. Placing it in a separate file now seems obvious since reading your code but I just didn’t see it before. Thanks again. Michael.

  • http://www.aqibmushtaq.co.uk Aqib

    Been looking for a tutorial like this for some time now, and this is a great example of how to use AJAX. Thanks