Reputation: 353
I have an Ajax request to save data from JavaScript and write it to a file using a separate ("saveData.php") PHP file. I want to know if I can "POST" multiple JavaScript variables / strings within the same Ajax request.
For instance, I currently have this:
function saveData(){ //sends an AJAX request to saveData.php
$.ajax({
type: "POST",
url: "saveData.php",
dataType: "text/plain",
ContentType: "charset=utf-8",
data: {"data": dataString},
})
}
And this works great via my PHP file, which as this code:
$data = $_POST["data"];
$theFile = fopen("Data/" . FileNameHere . ".txt", "a+");
// Save data into a file based on their username
fwrite($theFile, $data);
fclose($theFile);
But I want to save the file based on their userID, which is a JavaScript variable.
Can I do something like this:
function saveData(){ //sends an AJAX request to saveData.php
$.ajax({
type: "POST",
url: "saveData.php",
dataType: "text/plain",
ContentType: "charset=utf-8",
data: {"data": dataString},
data1: {"data1": userID}, <-----new line with JS variable 'userID'
})
}
And PHP file like this:
// Prepare line of data to save.
$data = $_POST["data"];
$userID = $_POST["data1"]; <--------New code to POST "data1" from Ajax
$theFile = fopen("Data/" . $userID . ".txt", "a+");
// Save data into a file based on their username
fwrite($theFile, $data);
fclose($theFile);
Upvotes: 0
Views: 3797
Reputation: 1058
Yes, you can, you are passing a JSON Object so it can have as many properties as you like.
Read More about, how to send multiple data in server side via ajax. Try this
function saveData(){ //sends an AJAX request to saveData.php
$.ajax({
type: "POST",
url: "saveData.php",
dataType: "text/plain",
ContentType: "charset=utf-8",
data: {
"data": dataString,
"data2":val2,
"data3":val3,
"data4":val4
},
})
}
And PHP file like this:
$data = $_POST["data"];
$userID = $_POST["data2"];
$theFile = fopen("Data/" . $userID . ".txt", "a+");
// Save data into a file based on their username
fwrite($theFile, $data);
fclose($theFile);
Upvotes: 6