0

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); 
}
  • Is this what you're looking for? http://stackoverflow.com/questions/9713058/send-post-data-using-xmlhttprequest – PJ Brunet Dec 27 '16 at 16:25

3 Answers3

1

Append it as a querystring to the request:

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

And then in your PHP

$myvar = $_GET['myvar'];
Mark Parnell
  • 9,115
  • 9
  • 28
  • 36
1

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;
?>
Ihor Patychenko
  • 196
  • 5
  • 19
0

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;

?>
Aley
  • 7,770
  • 6
  • 40
  • 53