Best Citizenships

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!