Posting multiple values to PHP from Ajax request - javascript

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

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

Related

AJAX different data records in Response Javascript

I am working on a site using HTML/CSS/JS and AJAX for connecting to the server. (new to web development)
I currently have this to get data and put it in an array.
var addresses = [];
$.ajax({
type: "GET",
url: 'GetAddresses.php',
data: {"type":"check"},
success: function(response){
alert(response);
addresses.push(response) // add values from php to array
}
});
But what if php echoed an address, a name, and a city for example. How could I access those different values?
Thank you for your help.
Typically you would write PHP that outputs structured data, e.g. JSON, and then parse that on the client.
<?php
header("Content-Type: application/json");
$data = [ "address" => "foo", "name" => "bar", "city" => "baz" ];
echo json_encode($data);
?>
and then on the client:
$.ajax({
type: "GET",
url: 'GetAddresses.php',
data: {"type":"check"},
success: function(response){
alert(response);
console.log(response.address);
console.log(response.name);
console.log(response.city);
}
});
Unrelated to the focus of your question, pushing data into an array in the wider scope from an Ajax callback is likely to cause you problems.

ajax method post send to mysql query

I pass the variable javascript method by ajax post method to the php file in this way:
$(".btn_ranking").click(function (e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: 'php/file.php',
type: 'post',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
name: name,
time: time
},
success: function(response){
console.log(response);
}
});
});
Request Payload in my Browser returns: name=Adrian&time=00%3A01%3A59. What should I write in the file file.php to send variables using sql query to my mysql database?
You can make good use of php explode() method here:
$string = name=Adrian&time=00%3A01%3A59
$parameters = explode("&", name=Adrian&time=00%3A01%3A59)
This will give you an array $parameters:
($parameters[0] == name=Adrian,
$parameters[1] == time=00%3A01%3A59)
Now you can get the name and time from $parameters:
$name = explode("=", $parameters[0])[1];
$time = explode("=", $parameters[1])[1];

send post data from js to php using ajax without type cast

I have object in javascript and I need send this object to php using ajax.
I can "just send" this object, but my problem is that I need send object value types exactly as they are and not everything as string: meaning NULL as NULL, boolean values as boolean and so on...
Trying this:
var js_object= <?php echo json_encode( array("a"=>NULL, "b"=>TRUE, "C"=>1.1) ); ?>;
$.ajax({
type: "POST",
url: "some.php",
dataType: "json",
data: JSON.stringify(js_object),
contentType: "application/json; charset=UTF-8",
success: function(msg){
}
});
but this does not sends data to server at all. and not gives any error also. where I am wrong ?
There is nothing wrong with your code.
I've just add a snippet with post query to httpbin.org:
$.ajax({
type: 'POST',
url: '//httpbin.org/post',
data: JSON.stringify({name: 'test', 'null': null, 'true': true}),
success: onSuccess,
error: onError,
dataType: 'json',
contentType: 'application/json; charset=UTF-8'
});
function onSuccess(data){
// data is parsed json response
console.log('Request copy:', data.json);
console.log('Full response', data);
}
function onError(xhr) {
console.log(xhr.status, xhr.responseText);
}
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
Server side sample script:
<?php
$json = file_get_contents('php://input');
$data = json_decode($json, true);
header('Content-type: application/json');
echo json_encode($data);

HTTPPost to JSON in PHP

I am doing an HTTP Post request in Javascript in order to update a JSON file.
function updateJson(dataNew){
var stringData = JSON.stringify(dataNew);
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'update.php',
data: {stringData},
success : function(d){
alert('done');}
})
}
Then in PHP:
<?php
$a = json_encode(file_get_contents("php://input"));
file_put_contents('newData.json', $a);
?>
I want JSON data in the JSON file however, the json file only includes a single string which is similar to the request payload of the http post. What am I doing wrong?
I would suggest to pass a key/value pair in the data object, and leave the contentType attribute as default (remove it), like:
$.ajax({
...
data: {myjson: stringData},
...
);
Then in PHP you should read the posted data and get that myjson element, without encoding it again, as it is already JSON:
<?php
$a = $_POST['myjson'];
file_put_contents('newData.json', $a);
?>

JSON decode is not working with PHP

I have a WAMP server with PHP 5.4.3 version. I encoded the data in JSON by php file below is the code (submit.php).
$username = 'User';
$comment = 'Test comment';
$date = date("Y-m-d G:i:s");
$image = '/img/sephiroth.png';
$return = array(
'username'=> $username,
'comment' => $comment,
'date' => $date,
'image' => $image );
echo json_encode($return);
Now i have a javascript file(script.js).
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
cache: false,
success: function(result){
alert(result); //It is showing all the JSON data.
$value = result;
$data = json_decode($value,true);
alert($data);
}
});
I want to decode all the JSON data separately. e.g Username, comment, date, image. So, i can show them on webpage, at the moment all data is coming together. I tried multiple times with multiple options (php array or result.username or result['username'] but no luck.
Now i am getting below error.
ReferenceError: json_decode is not defined
$data = json_decode($value,true);
you cannot use json_decode in JS json_decode is PHP function
use jQuery.parseJSON(json_data) to parse your json data;
jQuery.parseJSON( result );
Change
$value = result;
$data = json_decode($value,true);
To :
jQuery.parseJSON( result );
http://api.jquery.com/jQuery.parseJSON/
Try the following:
success: function(result){
var res = $.parseJSON(result);
var data = [res.username, res.comment, res.date, res.image]; // Array of the received response
}
This way you can get required output
try like below:
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
cache: false,
success: function(result){
alert(result); //It is showing all the JSON data.
jQuery.parseJSON( result );
}
});
Use the dataType option of ajax and set its value to json.
Then you can access the response as result['username']
My example:
Server-side returns {"username":"xxxxx","data":"xxxxxxxxxxxx and more"}
You can just deal with json like a javascript array, do not need to decode it.
the data below itself is the array of result.
$.ajax({
type: "POST",
url: "submit.php",
cache: false,
success: function(data){
var username = data['username'];
var data = data['data'];
//and so on
}
});
And make sure php sent the header Content-Type:application/json
header('Content-Type: application/json');

Categories