jquery won't accept json_encode() data - php

I'm using the following piece of code to send data from a form to a php script that will do some calculations using a class:
$.ajax({
type: "POST",
url: "test2.php",
data: values,
success: function(returnedData) {
$("#result").html(returnedData);
},
error: function(){
alert("failure");
$("#result").html('error while submitting');
}
});
My PHP script creates an array which I encode with JSON and then echo
$jsonString = array(
'monthText' => $Month->getMonthText($month),
'gross' => $formatGross,
'net' => $formatNet
);
echo json_encode($jsonString);
So far so good. But I'm not very keen on displaying the raw JSON. I'd like to format the text before it's written to the document. I've tried $.parseJSON() and $.getJSON() but none of them work.
The jQuery docs says it needs a string but isn't json_encode() making my array to a string? Isn't echo making it a string? Why am I getting the error Uncaught SyntaxError: Unexpected token { in my jQuery-file? My theory is that it doesn't have single quotes around it.
I've tried using header('Content-type: application/json') in my PHP script and I've also tried dataType: json in my AJAX POST but nothing is working.
What am I doing wrong?

From the comments it sounds like you are using json_encode wrong. Store each piece of data into an array and then encode the array.
$data = array();
for($i=0;$i<$something;$++) {
$data[] = array(
'monthText' => $Month->getMonthText($month),
'gross' => $formatGross,
'net' => $formatNet
);
}
echo json_encode($data);
Then your Javascript would need to be
$.ajax({
type: "POST",
url: "test2.php",
dataType:"json",
data: values,
success: function(returnedData) {
//returnedData will now be an array Object
for( var i=0; i<returnedData.length; i++ ) {
$("#result").html(returnedData[i].monthText);
}
},
error: function(){
alert("failure");
$("#result").html('error while submitting');
}
});

for parsing, use jQuery.parseJSON(returnedData);

Add dataType in your ajax call like this.
$.ajax({
type: "POST",
dataType:"json",
url: "test2.php",
data: values,
success: function(returnedData) {
$("#result").html(returnedData);
},
error: function(){
alert("failure");
$("#result").html('error while submitting');
}
});

Related

JSON.parse Error after decoding JSON.stringify-ed Array

I want to submit an array of arrays through JSON. So I create an object, apply JSON.stringify() on it and set it to a formData...
var sources = new Array();
$('.source-instance').each(function(){
var auxObject = {};
auxObject["sourceTitle"] = $(this).find(".source-title").val();
sources.push(auxObject);
console.log('sources: ' + JSON.stringify(sources));
});
formData.set('sources', JSON.stringify(sources));
When I check the data
console.log(formData.get('sources'))
I get
[{"sourceTitle":"SomeTitle"},{"sourceTitle":"AnotherTitle"}]
... which I then proceed via AJAX to the server.
On server side in php I loop over the array and let it print:
foreach (json_decode($request['sources'], true) as $sourceInstance) {
print_r($sourceInstance);
}
I get
Array
(
[sourceTitle] => SomeTitle
)
Array
(
[sourceTitle] => AnotherTitle
)
which looks pretty fine. But I also get
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
How come that? And how can I repair this? I don't see, where it is coming from.
EDIT
the ajax looks like this:
$.ajax({
url: '/piece/store',
type: 'POST',
processData: false,
contentType: false,
dataType: 'JSON',
data: formData,
success: function(response){
if (response.status == 'error'){
// show the erors
}
if (response.status == 'success'){ // "redirect" to success page
window.location.replace('/succes');
}
},
error: function(response){
$(".optional.errors").show();
$('ul.errors').empty();
$.each(response.errors, function (index, error) {
$('ul.errors').append('<li>' + error + '</li>');
});
}
});
the php responds:
$response = [
'status' => 'success',
];
return response()->json($response);
That error message happens when jQuery is trying to parse the response from the ajax call.
In your ajax request, you have set: dataType: 'json', which tells jQuery to expect the response to be a json-string. jQuery will then try to parse that json-string into a json-object (using JSON.parse()).
However, since you have print_r($sourceInstance) in your PHP-code, the response won't be a valid json-string and will make JSON.parse() fail.
Any output on the server side (echo, var_dump, print_r etc) will be a part of the response.

How to select the result from data success of ajax?

These are my code:
$("#promo_form").submit(function(stay){
$.ajax ({
type: "post",
url: "<?=base_url()?>promo/code_validate",
data: $("#promo_form").serialize(),
success: function(data){
$("#myModalLabel").html(data);
}
});
stay.preventDefault();
});
And the success data result below:
$result1 = "code is invalid";
$result2 = "promo unavailable";
How can I select these and retrieve it?
This is what I did below but now working.
$("#myModalLabel").html(data->result1);
JavaScript uses dot syntax for accessing object properties, so...
$("#myModalLabel").html(data.result1);
I'll also add that you want to make sure the page at promo/code_validate prints out a JSON response, as that is how data will become an object ($.ajax is intelligent about how to parse the server's response, see the link below). So your code_validate page might look something like this:
{
"result1": "code is invalid",
"result2": "promo unavailable"
}
http://api.jquery.com/jquery.ajax/
Do this
Function controller
function code_validate()
{
echo json_encode(array('result1'=>'Code is invalid',
'result2'=>'Promo not available');
}
Javascript
$("#promo_form").submit(function(stay){
$.ajax ({
type: "post",
url: "<?=base_url()?>promo/code_validate",
data: $("#promo_form").serialize(),
success: function(data){
var mydata = JSON.parse(data);
console.log(mydata.result1);
console.log(mydata.result1);
}
});
stay.preventDefault();
});
You must return it as JSON.
Goodluck meyt
Vincent, add the dataType paramater to your ajax call, setting it to 'json'. Then just parse the response to convert it to an object so that you can access the variables easily, e.g.
in AJAX call:
dataType: "json"
in success function:
var obj = jquery.parseJSON(data);
console.log(obj);//echo the object to the console
console.log(obj.result1);//echo the result1 property only, for example
The simplest way to do what you want is create a php associative array of your values then json encode the array and echo the resulting string like this:
$response = ["result1"=>"code is invalid", "result2"=>"promo unavailable"];
echo json_encode($response);
Then on the client side, access them like this
$("#promo_form").submit(function(stay){
$.ajax ({
type: "post",
url: "<?=base_url()?>promo/code_validate",
data: $("#promo_form").serialize(),
success: function(data){
$("#modal-1").html(data.result1);
$("#modal-2").html(data.result2);
}
});
stay.preventDefault();
});

return json from php and handle

I get this from ajax call
{"id":"381120774951940096","time":"Posted 0 minutes and 51 seconds ago.",....
How can I add each of these into variable, id, time etc? data.id won't work, it says undef.
<script>
$(function() {
$.ajax({
type: "POST",
url: "start.php",
cache: false,
success: function(data) {
console.log(data.name);
console.log(data);
}
})
});
</script>
This is what I return from start.php
$return = array('id' => $info['id_str'] ,'time' => timeDiff(new DateTime($info['created_at'])), 'name' => $info['user']['name'], 'text' => $info['text'], 'image' => $picture, 'url' => "http://twitter.com/{$info['user']['screen_name']}");
print_r(json_encode($return));
EDIT
I had that print_r inside foreach loop and that was the issue. So I added another array and used echo json_decode($array,true) at the end of file.Writing this just in case, might help someone.
Cheers
First, in your PHP, change your line to:
echo json_encode($return, true);
That second parameter ensures that the JSON is interpretable as an associative array. Also, you should use echo instead of print_r when returning JSON; print_r can alter the formatting.
Next, use the following AJAX call:
$.ajax({
type: "POST",
url: "start.php",
dataType: "json", // Add this option.
cache: false,
success: function(data) {
console.log(data.name);
console.log(data);
}
})
The dataType: "json" option ensures that data will be parsed as a JSON object as soon as it's retrieved. So, data.id should be immediately available in your success callback function.
Hope this helps!
Firstly, you should use echo in the server script. print_r is mainly for debugging arrays.
Secondly, you should declare a dataType option for the ajax call:
$.ajax({
dataType: "json", // <-- here
type: "POST",
url: "start.php",
cache: false,
success: function(data) {
console.log(data.name);
console.log(data);
}
});
The way you have it now, I think you are getting a string response as data.
You can verify that with console.log(JSON.stringify(data));
You have to set dataType: 'json' in your ajax. This means that jQuery will parse the result as JSON for you.
Then parse the data,
data = $.parseJSON(data);
Then read var id = data.id;
Also, in your PHP, No need to use print_r(). Just use echo instead print_r().like:
echo json_encode($return);
You'll need to parse the JSON string into an object. You can use JSON.parse to do this.
// Your JSON string
var json_str = "{'id': 'foo', 'time': 'bar'}";
// We need to parse it, converting it into a JS object
var json_obj = JSON.parse(json_str);
// We can now interact with it
console.log(json_obj.id);
console.log(json_obj.time);
Alternatively, you can parse JSON using a built in jQuery function parseJSON().
jQuery also has a built in function for fetching JSON called getJSON(). If memory serves, this is just a shorthand for doing an .ajax() call and specifying a datatype of json. This will handle the above (parsing JSON) for you, and is the recommended solution.

Post value via ajax to php

I trying to post some value via ajax to php then php print send back js console.log, have problem:
build array( I'm doubt below I made is array??)
$('.eachcontainer').each(function(){
var arr = $(this).find('img').map(function(){
return $(this).attr('src');
});
console.log(arr);
// result:
// ["16.png", "17.png", "19.png", "18.png"]
// ["0.png"]
// ["0.png"]
// []
// []
$.ajax({
type: "POST", url: "update.php",
data: arr
}).done(function(msg){
console.log(msg);
});
});
php
print_r($_POST);
js come back console.log
Array
(
[undefined] =>
)
Array
(
)
Array
(
)
Array
(
[undefined] =>
)
Why this does not work? How can i fix it?
Also, I tried to change the syntax in my ajax function data: {arr: arr} but this didn't work either.
Error message:
TypeError: Type error jquery-1.10.1.min.js:6
Found error line in jquery-1.10.1.min.js:6:
t = x.isFunction(t) ? t() : null == t ? "" : t, i[i.length] = encodeURIComponent(e) + "=" + encodeURIComponent(t)
you haven't constructed proper key&value pair using your data, if you want to pass a raw stream of data then set processData: false and capture with php://input
var arr = $(this).find('img').map(function(){
return $(this).attr('src');
});
$.ajax({
type: "POST", url: "update.php",
data: arr,
processData: false,
}).done(function(msg){
console.log(msg);
});
on the php side
$data = file_get_contents("php://input");
You first need to call arr.get() to get the jquery.map result back as a regular javascript array. Then you can pass it to the ajax data paramter as:
data: { "images" : arr.get() }
So the full ajax call would look like this:
$.ajax({
type: "POST", url: "update.php",
data: { "images" : arr.get() }
}).done(function(msg){
console.log(msg);
});
You can then read the array back in php as:
$images = $_POST['images'];

multiple return values from PHP with jQuery AJAX

I'm using this jQuery code:
$.ajax
({
type: "POST",
url: "customerfilter.php",
data: dataString,
cache: false,
success: function(html)
{
$(".custName").html(html);
}
});
How can i do something like this: $(".projDesc").html(html1);
So i can split the returned results into two html elements?
echo "<p>" .$row['cust_name']. "</p>";
thats the PHP i'm using and i want to echo another statement which i can put into another HTML element
Does this make sense?
Use json_encode() to convert an associative array from PHP into JSON and use $.getJSON(), which will return a Javascript array.
Example:
<?php echo json_encode(array("a" => "valueA", "b" => "valueB")); ?>
In Javascript:
$.getJSON("myscript.php", function(data) {
alert("Value for 'a': " + data.a + "\nValue for 'b': " + data.b);
});
Make your response return JSON, you'll need to change your jQuery to this, so the expected dataType is json:
$.ajax
({
type: "POST",
url: "customerfilter.php",
dataType: 'json',
cache: false,
success: function(data)
{
$(".custName").html(data.message1);
$(".custName2").html(data.message2);
}
});
Then you need to encode your response as a JSON Array:
<?php echo json_encode(
array("message1" => "Hi",
"message2" => "Something else")
) ?>
Why don't you return a JSON object. This way you can easily put many different results inside the ajax response.
You can use a separator and join the values like this in your response
echo $value1.'|'.$value2;
Now you can use JavaScript method split("|") as below:
var myarray = response.split("|");
var value_1 = myarray[0];
var value_2 = myarray[1];

Categories