views:

1952

answers:

7

Hi All,

How to pass value from Javascript to PHP and get return of PHP back to Javascript function

I am having HTML page which will have Javascript function which should call PHP (php is another file)

for example like

function JavaCallphp() { test = Validate.php }

"test" is variable on JavaScript

Validate.php is the File which contain Validation code and returns the Bool Value.

I want to get true/false in "test" variable

+2  A: 

Use an asynchronous HTTP request in the JavaScript to load the output of the PHP script.

For example, using the Prototype framework's Ajax.Request, say you have an HTML element with id="notice" and you want to update that based on the script's output (a simple "true" or "false" string).

new Ajax.Request('/validate.php', {
  method: 'get',
  onSuccess: function(transport) {
    var notice = $('notice');
    if (transport.responseText == 'true')
      notice.update('Validation successful');
    else
      notice.update('Validation failed');
  }
});
Ben James
I am not using Ajax... do you have any idea how can i make it in pure Javascript
Ankita
Ajax is just a term that describes exactly the sort of functionality that you want. It does not imply any particular framework, so you can do it with pure JavaScript but it will be more work.
Ben James
AJAX is the answer :) and read the wiki article on AJAX ( asynchronous JAVASCRIPT and XML )
Aviatrix
i am getting ajax is undefinedif i try to use it like this<script language="javascript">function aaa(){ new Ajax.Request('/ValidateLogin.php', { method: 'get', onSuccess: function(transport) { var notice = $('notice'); if (transport.responseText == 'true') alert('Validation successful'); else alert('Validation failed'); } });} </script>
Ankita
Obviously, that means you're not using the Prototype framework (see the link in Ben James' answer).
Duroth
+2  A: 

Ajax?

Jiří Pospíšil
A: 

The PHP should be stored on a remote server and called using a scripted HTTP request. Read up on AJAX for details of how this works and how to perform such tasks.

You can't just do it in a browser as JavaScript has no PHP interpreter and neither do most browsers, and so can't just run a PHP file to get output.

workmad3
A: 

If your not using a javascript framework like jquery or prototype then you will have to create a XMLHttpRequest object yourself which the javascript framework would normally wrap up. Something like the following:

function GetHttpObject() 
{
    if (typeof XMLHttpRequest != 'undefined')
        return new XMLHttpRequest();

    try 
    {
        return new ActiveXObject("Msxml2.XMLHTTP");
    } 
    catch (e) 
    {
        try 
        {
            return new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch (e) {}
    }

    return false;
}
Steve Mc
+1  A: 
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  return new XMLHttpRequest();
  }
if (window.ActiveXObject)
  {
  // code for IE6, IE5
  return new ActiveXObject("Microsoft.XMLHTTP");
  }
return null;
}

function CallSomePHP(username, password)
{
    xmlhttp=GetXmlHttpObject();
    if (xmlhttp==null)
    {
    alert ("Browser does not support HTTP Request");
    return;
    }
    var url="myPhp.php";
    url = url+"?username="+username+"&password="+password;
    xmlhttp.onreadystatechange=stateChanged;
    xmlhttp.open("GET",url,true);
    xmlhttp.send(null);
}

function stateChanged()
{
    if (xmlhttp.readyState==4)
    {
     alert(xmlhttp.responseText); // this will alert "true";
    }
}

myphp.php

<?
  // Get the values of username and password
  $username = $_GET['username'];
  $password = $_GET['password'];
  echo"true";
?>
junmats
i am trying to use this on my login page so if i access this then i also need to send two parameter to myPHP.php (Username and Password)How can i send the parameter also with CallSomePHP Method
Ankita
Check back my post. I have added parameters for username and password and the how to get the values you passed in php. Hope this helps
junmats
A: 
Enjoy coding
A: 

You should try JQuery. I send and receive from JS to PHP the following way, assuming this is the form.

<div id="form">
<input type="text" id="email" /><br />
<button id="submit">Submit</button>
</div>
<div id="response">
</div> <!-- load jquery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" > </script>

// put this in script type="text/javascript" tags
$(document).ready(function(){
var emailValue;

  $("#submit").click(function(){
  // when the user clicks the submit button

    // get the value of email and put it in the variable we made above
    emailValue=$("#email").val();

    /* am going to send a post variable called "email" 
    * with the value of "emailValue" to a script called receiver.php
    */
    $.post('receiver.php',{email:emailValue},function(e){
     // "e" is variable that contains the echoed string
     // check if it's true or false
  if(e=="true")
  alert ("valid email");
  else
  alert("invalid email");
    });

  });

});

receiver.php


$email=$_POST['email'];

// checkMail is a fictional function that returns a bool
$valid=checkMail($email);

if($valid)
{
 // email is valid
 echo "true";
}else{
 // email is invalid
 echo "false";
}


Note: if you are not sending data to the php script you should use $.get instead of $.post, it's a little bit faster.

You can also use the javascript variable "e" and load its contents in the "response" division in your form like this

$("#response").html(e);

This would accomplish the same thing as if you used JQuery's "load()" function like Coder mentions below.

SoftwareDev