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');
Related
I have an array where I want to loop through the array inside the JSON and show the data in the table based on the nationalities in the array. The problem is that the array data contains backslashes and I can't loop through it. I retrieve the data with an AJAX call from my PHP file.
PHP:
$arr
if (!empty($arr)) {
echo json_encode($arr);
// print_r($arr);
} else{
$errors = 'No data available.';
}
exit;
If I print_r() I see: Array ( [0] => stdClass Object ( [company] => John Comp [pro_countries] => ["BR","ES","FR"])
If I use echo json_encode my echo looks like but I can print company in my Jquery: [{"company":"John Comp","nationality":"[\"BR\",\"ES\",\"FR\"]"}]
But if I use print_r($arr) the slashes disappear but I can't seem to print the company in Jquery: [{"company":"John Comp","nationality":"["BR","ES","FR"]"}]
If I use Print_r() Then my AJAX call in JQuery goes straight to the error response.
JQuery:
$.ajax({
type: 'GET',
url: 'testurl',
dataType: 'json',
processData: false,
cache: false,
success: function (response){
response.nationality.forEach((item)=>{
});
I also tried:
$.ajax({
type: 'GET',
url: 'testurl',
dataType: 'json',
processData: false,
cache: false,
success: function (response){
var data = JSON.parse(response);
data.nationality.forEach((item)=>{
});
What I want after the loop:
nationality is a JSON string, you need to parse it so you can loop over it.
JSON.parse(response.nationality).forEach(item => ...)
I'm not sure why you encoded nationality in the first place. You should just make it an ordinary PHP array, and then it will be encoded as part of $arr.
I already looked up questions about this topic but couldn't figure my problem out.
I have a php file which contains the array:
$data = ['logged' => $_SESSION['loggedin'], 'sessName' => $_SESSION['name']];
echo json_encode($data);
Here's my AJAX code, but I have no idea what should I put in "data". Basically my goal is to use the $data array in my Javascript code. (So i can manipulate DOM with conditions).
<script>
$.ajax({
type: 'POST',
dataType: "json",
url:'sign-in.php',
data:
success: function(data)
{
try {
data = JSON.parse(data);
}catch(e) {}
console.log(data);
}
});
</script>
By specifying dataType: "json" in your $.ajax call, jQuery will automatically parse your JSON data into javascript object / array for you. You can probably remove the JSON.parse form you code.
Also there is an extra data: line, which would be a javascript syntax error.
<script>
$.ajax({
type: 'POST',
dataType: "json",
url:'sign-in.php',
success: function (data) {
console.log(data);
},
});
</script>
One more thing. Your PHP code, expects both 'loggedin' and 'name' to be set in your $_SESSION. If not, your PHP (depends on settings) might generate warning message in between and cause JSON parsing error.
You can use the null coalescing operator (introduced since PHP 7.0) to assign some value if either or both values are not set:
$data = [
'logged' => $_SESSION['loggedin'] ?? FALSE,
'sessName' => $_SESSION['name'] ?? '',
];
echo json_encode($data);
Updated: Add proper handling to potential invalid key issue.
In your example you haven't intiliaze the session with session_start(), also it recomanded to indicate the response content type, and i fix also your ajax request :
PHP :
session_start();
$data = [
'logged' => $_SESSION['loggedin'],
'sessName' => $_SESSION['name'],
];
header("Content-type: application/json");
echo json_encode($data);
exit();
Jquery :
$.ajax({
type: 'GET',
dataType: "json",
url:'sign-in.php',
success: function(data)
{
try {
data = JSON.parse(data);
} catch(e) {}
console.log(e);
}
}
});
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];
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);
?>
So I'm trying to send a JSON as a string.
Then I have a PHP back-end that retrieves this JSON string and parses it using json_decode.
Unfortunately, I can't get to send this JSON as a string.
Here's the jQuery Ajax script I used:
var jsonString = JSON.stringify(checkables);
console.log(jsonString);
$.ajax({
url: $url,
type: 'POST',
data: {ajaxidate: JSON.stringify(jsonString)},
contentType: "application/json; charset=UTF-8",
success: function (data)
{
// just successful callback
},
error: function ()
{
// just error callback
}
});
Variable checkables contains raw form as JSON data:
After applying JSON.stringify(), this is now how it looks:
[{"name":"name","type":"multialphanumslug","value":"AD"},{"name":"server","type":"host","value":"10.1.1.1"},{"name":"port","type":"number","value":"8080"},{"name":"authid","type":"username","value":"barryallen"}]
At the back-end, I have this PHP script:
<?php
var_dump($_POST);
die();
?>
Now I suppose $_POST at back-end should now contain this:
array(
'ajaxidate' => "[{\"name\":\"name\",\"type\":\"multialphanumslug\",\"value\":\"AD\"},{\"name\":\"server\",\"type\":\"host\",\"value\":\"10.1.1.1\"},{\"name\":\"port\",\"type\":\"number\",\"value\":\"8080\"},{\"name\":\"authid\",\"type\":\"username\",\"value\":\"barryallen\"}]"
);
But it didn't receive anything. Here's the captured request:
The response from back-end?
I tried with POSTMan and I received an expected correct output:
Now that was ridiculous.
I'm stuck at this for 2 days trying to figure out what's going on or what did I miss. Any help will be greatly appreciated.
You need to parse the data on the server:
$myArray = json_decode($_POST['ajaxidate']);
var_dump($myArray);
Consider this:
<?php
$a = '[{"a": 1}]';
$b = json_decode($a);
var_dump($a);
var_dump($b);
?>
Output:
string(10) "[{"a": 1}]"
array(1) {
[0]=>
object(stdClass)#1 (1) {
["a"]=>
int(1)
}
}
dataType: 'json', tldr: Use It!
When setting dataType = json you tell jQuery that the response from the server should be interpreted as JSON and it will therefore parse it for you and give the parsed object / array as first argument to the success callback:
$.ajax({
// ...
dataType: 'json',
success: function(myJson) {
console.log(myJson); // this will be a JSON object/array...
}
});
As you mention dataType: json in your ajax call data need to be in json formate but using JSON.stringify convert Json object to json String that with make problem for you need to change
`var jsonString = JSON.stringify(checkables);`
to
var jsonString = checkables;
JSON.stringify()
Solved my own problem. Having #Munna suggested to use $.post() made me figure out to eliminate the unnecessary. From that case, the unnecessary is contentType option from $.ajax().
This is the updated working solution:
$.ajax({
url: $url,
type: 'POST',
data: {ajaxidate: JSON.stringify(jsonString)},
success: function (data)
{
// just successful callback
},
error: function ()
{
// just error callback
}
});
Thanks everyone who helped. Have a good day