0

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);   
2

1 Answer 1

6

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);
Sign up to request clarification or add additional context in comments.

5 Comments

I am glad to help you.
Hope you didn't object to my adding a bit to your answer
@RiggsFolly No, I didn't. If you want to add more information feel free to add.
@Phoenix404 I need a help. I wonder if I can ask for help from you?
yup sure... go ahead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.