user2180748
user2180748

Reputation: 21

Using an ajaxRequest.open to send a variable to php

I have a script which uses ajaxRequest.open to call a php script. I'm wondering how I could send a variable to the php file. More specifically, I've got a form text field I'd like to be able to send to the php file.

The ajaxRequest is working fine, I just need to know how I'd send a variable and how php could read it.

Here is the (very abbreviated) script which is calling my php file...

}
  ajaxRequest.open("GET", "../../ajaxphp.php", true);
  ajaxRequest.send(null); 
}

Upvotes: 0

Views: 1601

Answers (3)

Ihor Patychenko
Ihor Patychenko

Reputation: 196

First you need to obtain the value of variable witch you are going to send to *.php You can do it by this ways:

var value = document.getElementById("someID").value;

or jQuery way:

var value = $("#someID").val();

Then, you need to put the variable to your ajax request:

ajaxRequest.open("GET", "../../ajaxphp.php?variable="+value, true);
//The last argument in this line (witch is set a "true") want to say, that is a  asynchronous request 
ajaxRequest.send(null);
//null want to say, that you not sending any parameter, really is automatically sent in the first line of code

Then, when you pick up the value of the variable in the code *. php, can do the next:

<?php
$myVariable = $_GET["variable"];
echo $myVariable;
?>

Or like this:

<?
$myVariable = $_REQUEST["variable"];
echo $$myVariable;
?>

Upvotes: 1

Aley
Aley

Reputation: 8640

You can send data by simply appending parameters to the URL like

ajaxRequest.open("GET", "../../ajaxphp.php?foo=bar", true);

To get a value from an input field using javascript, you may do the following

var foo = document.getElementById('foo').value;

To get the value from the URL using PHP

$foo = $_GET['foo'];

Full example

<input id="foo" name="foo" value="bar">

<script>

    var foo = document.getElementById('foo').value;
    ajaxRequest.open("GET", "../../ajaxphp.php?foo="+foo, true);
    ajaxRequest.send(null);

</script>

PHP file

<?php

    $foo = $_GET['foo'];
    echo $foo;

?>

Upvotes: 0

Mark Parnell
Mark Parnell

Reputation: 9200

Append it as a querystring to the request:

ajaxRequest.open("GET", "../../ajaxphp.php?myvar=thevalue", true);

And then in your PHP

$myvar = $_GET['myvar'];

Upvotes: 1

Related Questions