'How to send multiple variables with XMLHttpRequest?

I try to send two variables with Ajax request to my ajax.php:

var xhReq               = new XMLHttpRequest();

xhReq.open              ( "GET", "ajax.php", false );
xhReq.setRequestHeader  ("Content-type", "application/x-www-form-urlencoded");
xhReq.send              ("cmd=ping&url=www.google.com");

How can I achieve this?



Solution 1:[1]

You are mixing some values.

A GET request:

xhReq.open( "GET", "ajax.php?cmd=ping&url=www.google.com", true );
xhReq.send();

A POST request:

xhReq.open( "POST", "ajax.php", true );
xhReq.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
xhReq.send( "cmd=ping&url=www.google.com" );

Solution 2:[2]

`//main page: javascript function

function ajaxSave(whatToSave,fileToSaveIn){

... etc.

xmlhttp.open("POST","secondaryPage.php",true);

xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

xmlhttp.send("whatToSave=" + whatToSave + "&" + "fileToSaveIn=" + fileToSaveIn + ""); }

//secondary page: PHP code

$myFile = $_POST["fileToSaveIn"];

$fh = fopen($myFile, 'w') or die("can't open file");

$stringData = $_POST["whatToSave"];

fwrite($fh, $stringData);

fclose($fh);`

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 clarke