i have a problem when parsing json from php to javascript
this is my example code :
//function
MethodAjax = function (wsFile, param) {
return $.ajax({
type: "POST",
dataType: "json",
url: '../proses/' + wsFile + ".proses.php",
data: 'param='+param,
error: function (msg) {
return;
},
});
};
//call function
$(document).ready(function() {
$('#getproduk').click(function(){
var param = {
ProdukId : '1',
ProdukName : 'test'
};
CallMethodWithAjax('try', JSON.stringify(param)).done(function(data){
$data = JSON && JSON.parse(data) || $.parseJSON(data);
});
});
//Simple Php code
<?php
$data = $_POST['param'];
$data = (json_decode($data));
$data1['name'] = $data->ProdukName;
$data1['id'] = $data->ProdukId;
$data1['test'] = 'test';
echo json_encode($data1);
?>
//post, response and error at console
response : {"name":"test","id":"1","test":"test"}
post : param {"ProdukId":"1","ProdukName":"test"}
error : SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
how to solve this probled, i have try the solution that i found at SO and google, but still cannot solve this problem
please someone help
thanks
jQuery's $.ajax() function will yield a JavaScript object if the response is JSON so I believe the error you're seeing is a result of trying to parse a JavaScript object and not a string as you're expecting. In the callback you're providing to the done function, inspect data and you'll find that it's an object and there is no need to JSON.parse the result.
Related
<?
function phpfunction(){
//insert data to database //some codes work inside this.
$return_arr[] = array($arrResult, // include only one value
$response_array['status'] );//success or not success value
return $return_arr;
}
?>
This $return_arr[] value return to the javascript ajax file >>
$.ajax({
url: 'PHPMethodCalls_AL.php',
type: 'post',
data: {... post many values to php function.. },
success: function(data) {
alert(data);
//data is successfully come as this format >> [[["Testing123"],"success"]]
var results = JSON.parse(data);
alert(results);
// this alert got >> Testing123,success
},
//this one is post value to function
$newCIarrayList = array();
$newCIarrayList = phpfunction(..data include );
echo json_encode($newCIarrayList);
What should I do to get each value as "Testing123" and "success" value separately? I tried with split(",") function but it didn't work.
You can seperate in php function before response to ajax like below .Then you can get easy
<?
function phpfunction(){
//insert data to database //some codes work inside this.
$return_arr = array("data" =>$arrResult, // include only one value
"status" =>$response_array['status'] );//success or not success value
return $return_arr;
}
?>
var results = JSON.parse(data);
alert(results.data || results.status);
What you get back in success: function(data) is a stringified json of a nested array: [[["Testing123"],"success"]].
To get your status and payload out of this structure, you can use the following snippet.
var data = '[[["Testing123"],"success"]]';
var parsedData = JSON.parse(data);
console.log(parsedData); // quite nested
var status = parsedData[0][1];
console.log(status);
var payload = parsedData[0][0][0];
console.log(payload);
Or using ES6 destructuring:
var data = '[[["Testing123"],"success"]]';
var parsedData = JSON.parse(data);
[[[payload], status]] = parsedData;
console.log(status);
console.log(payload);
I would however suggest that you revise your php-side code, and make it so that it forms a simpler structure, ideally:
{"status": "success", "payload": "Testing123"}
I am trying to get customer details in a Laravel POS application. I am sending customer cell number via AJAX to serch and returning details from controller. When ever I am trying to apply JSON.parse on returned data from server I am getting:
Uncaught SyntaxError: Unexpected token s in JSON at position 0
I cant find errors in my code. I have searched product in exact same way from the server which works fine. Below is my code sample:
My Ajax Function
function customersearch(){
var token=$('input[name=_token]').val();
var baseUrl=document.getElementById("baseUrl").value;
var url=baseUrl+"/sales/searchcustomer";
var id=document.getElementById("customercell").value;
console.log(id);
$.ajax({
type: "GET",
headers: {'X-CSRF-TOKEN': token},
url:url,
data: {id:id},
datatype:'json',
success: function(data) {
var returndata =JSON.parse(data);
console.log(returndata);
var id=returndata[0].id;
if(id == "undefined") {
alert("No Customer found");
}
else {
document.getElementById("cname").value = returndata[0].fname;
document.getElementById("cid").value = returndata[0].id;
}
}
});
}
My Controller Function:
public function searchcustomer(Request $request){
$searchingkey = $request->input( 'id' );
//var_dump($searchingkey);
$customer = DB::table('customers')
->where('cellno', $searchingkey)
->get(['id','fname']);
var_dump($customer);
if (count($customer) == 0) {
$data = "No data returned"; // empty result
}
else {
$data = $customer;
}
return json_encode($data);
}
Response of var_dump($customer) in Network XHR
array(1) {
[0]=>
object(stdClass)#221 (2) {["id"]=>string(1) "1"
["fname"]=>string(5) "Ahnaf"}}
[{"id":"1","fname":"Ahnaf"}]
IF I dont apply JSON.parse on the returned data in ajax Function and just print the data variable like:
var returndata =data;
console.log(returndata);
this gives output in the consol like:
array(1) {
[0]=>
object(stdClass)#221 (2) {
["id"]=>string(1) "1"
["fname"]=>string(5) "Ahnaf"
}
}
[{"id":"1","fname":"Ahnaf"}]
The jquery docs for the ajax function say that the dataType parameter is spelled with a capital T.
You have this:
datatype:'json'
Try changing it to this:
dataType:'json'
and see if that helps.
You can try first() instead of get().
That should solve this.
You should use echo rather than return for ajax response
My Controller Function:
echo json_encode($data);
Also dataType must be
dataType: "json" // but remove this line because your already have JSON.parse(data);
I will start by saying that I am learning how to program in jquery/javascript, and am running into an issue using JSON.parse(). I understand the format, and why people use it... but have not been able to get it to work in any of my code projects.
I have read in books/online on here in how to use it, but I think I read too much on it. I am now confused and second guessing what I know about it.
With that said, my jquery/javascript class I am taking is asking me to use it for an assignment, through AJAX using MAMP/localhost as the server.
The two codes below are for the section that I need to fill in the //TODO information. One is javascript (client-side), the other is php (server-side). I think that I've set the other //TODO information correctly, but I keep getting a token error for the JSON part.
I looked on here for a solution, but again, I think I've confused myself badly and need help. Appreciate any feedback, insight, or information.
-Javascript-
var calculateMpg = function () {
// These lines are commented out since the server will perform these checks
// if (!checkNumber("miles") || !checkNumber("gallons")) {
// return;
// }
var miles = $("#miles").val();
var gallons = $("#gallons").val();
console.log("ajax request issued.");
var result;
$.ajax({
url: "service.php?action=calculateMPG&miles="+miles+"&gallons="+gallons,
cache: false,
dataType: "text",
success: function(msg) {
console.log("ajax response received.");
// TODO: parse the JSON string returned from the server (see JSON.parse())
JSON.parse("result");
if (result.status === 'success') {
// TODO: get the mpg value returned from the server and display it to the user.
$("#mpg").val($_GET("result"));
console.log("JSON Working!");
}
else {
// TODO: get the name of the variable with the error. Hint: look at the 'fail' result from service.php
$_GET[fail(id)];
// TODO: report the error to the user using invalidNumber() function.
alert("{status: 'failure', variable: <variable name>}");
}
}
});
};
$(document).ready( function () {
$("#miles").blur(function () {
checkNumber("miles");
});
$("#gallons").blur(function() {
checkNumber("gallons");
});
$("#calculate").click(calculateMpg);
$("#miles").focus();
});
-PHP-
<?php
if ($_GET) {
if ($_GET['action'] == 'calculateMPG') {
$miles = htmlspecialchars($_GET['miles']);
$gallons = htmlspecialchars($_GET['gallons']);
// validate miles
if (strlen($miles) == 0) {
fail("miles");
}
$miles_chars = str_split($miles);
for ($i=0; $i< count($miles_chars); $i++) {
if ($miles_chars[$i] < "0" || $miles_chars[$i] > "9") {
//error_log("miles_chars check failed at: " + $i);
fail("miles");
}
}
// validate gallons
if (strlen($gallons) == 0) {
fail("gallons");
}
$gallons_chars = str_split($gallons);
for ($i=0; $i< count($gallons_chars); $i++) {
if ($gallons_chars[$i] < "0" || $gallons_chars[$i] > "9") {
fail("gallons");
}
}
// validate $miles and $gallons calling $fail along the way
$result = $miles/$gallons;
if ($result) {
success($result);
} else {
fail("mpg");
}
exit ;
}
}
function fail($variable) {
die(json_encode(array('status' => 'fail', 'variable' => $variable)));
}
function success($message) {
die(json_encode(array('status' => 'success', 'message' => $message)));
}
Edited Additional 1
I have made changes to the JSON information in regard to 'var result' (thanks to several of the responses here). I'm starting to understand JSON a bit better.
Another question I have (now) is how to isolate a part of the JSON message from the whole being transmitted?
A piece of the 'JSON.parse(msg)' returned DOES include the answer to the equation miles/gallons, but I don't know how to... extract it from the JSON.
The solution to the equation miles/gallons appears in the 'msg' output.
Thanks.
Edited Additional 2
This question has been solved! While perusing around stackoverflow for a solution to the question in my previous edited section, I found my answer here: JSON response parsing in Javascript to get key/value pair.
The answer is this: under the //TODO section asking for the mpg value, I put the following code - $("#mpg").val(result.message); - which says that in the JSON section of the variable result, take the part of the JSON marked 'message', the value being the equation solution.
Thank you to all who responded with their solutions to my problem. I appreciate the fast responses, the great suggestions, and the information in understanding JSON.
-ECP03
JSON.parse() requires that you send it a valid JSON string.
"result" is not a valid JSON string. In your success function you have defined a parameter msg - what does this contain? Try console.log(msg) at the beginning of your success function and look at the console output.
You have two options:
Option 1: -- Parse the string returned.
Change JSON.parse("result"); to:
var result = JSON.parse( msg );
Option 2: -- Request JSON instead of plain text - no need to parse
Use $.getJSON() which is shorthand for:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Instead of parsing the JSON yourself, jQuery already provides you with a convenient function that will parse JSON:
var path = "service.php?action=calculateMPG&miles="+miles+"&gallons="+gallons;
$.getJSON(path, function (data) {
if (data.status == 'success') {
console.log('Success! Message:', data.message);
} else {
console.log('Failed :( Variable:', data.variable);
}
});
For your original code, what you would need to do is call JSON.parse(msg) in your success callback, which would return a JavaScript object with the values you sent from your PHP script. By specifying dataType: 'json' in the $.ajax call, jQuery does this for you. The $.getJSON method does this and some other things for you.
You need to use the result returned by the success function:
var result = JSON.parse(msg);
Then, you could do stuff like result.status.
When you put JSON.parse("result") you're saying "parse the string 'result'," which doesn't make any sense. However, if you say JSON.parse(msg) you're saying "Parse the variable that was returned from the ajax action," which makes sense.
JSON.parse() is used to convert your json data to object, then you can manipulate it easly.JSON.parse(msg); instead of JSON.parse("result").
For example:
var json = '{"value1": "img", "value2":"img2"}'
var obj = JSON.parse(json);
for ( k in obj ) {
console.log(obj[k])
}
This is totally wrong: JSON.parse("result");. .parse() expects a JSON string, e.g. the string that came back from you ajax request. You're not providing that string. you're providing the word result, which is NOT valid JSON.
JSON is essentially the right-hand side of an assignment expression.e.g.
var foo = 'bar';
^^^^^---this is json
var baz = 42;
^^---also json
var qux = ['a', 'b', 'c'];
^^^^^^^^^^^^^^^---even more json
var x = 1+2;
^^^---**NOT** json... it's an expression.
What you're doing is basically:
var x = parse;
^^^^^^---unknown/undefined variable: not JSON, it's an expression
I'm validating my html form with Jquery/Ajax Call. It's process by Php. In php page its return all success result or error result after processing To Jquery Success method.
SO I want to receive another parameters in jquery success method (). Is there any way to received it ?
for example : in this following line code If $numSearch is == 0
elseif($numSearch === 0){
echo "<font color='red'>No Matches.</font>";
}
then I want to received another parameters in jquery success method so that I can load getDetails2(SearchValue); function. Now it's load when the value is integer. But it's should be check if value is Integer and result is showing something.
Php code :
require_once("corefile.php");
$search = (int) $_POST['data'];
$cdid = inputvalid($_POST['cdid']);
if($cdid == "ID"){
// if serach value is empty
if(empty($search)){
echo "<font color='red'>Search keyword required.</font>";
}
// if serach value is not empty
elseif(!empty($search)){
// start myqli_query to search
//$numserach
}
elseif($numSearch === 0){
echo "<font color='red'>No Matches.</font>";
}
}
Jquery Code:
$(document).ready(function() {
$("#cdid").click(function() {
var SearchValue = $('#txt_name').val();
var cdid = $('#cdid').val();
$("#loading-image").show();
$.ajax({ //create an ajax request to load_page.php
type: "POST",
url: "doSearch.php",
data : {
'data' : SearchValue,
'cdid' : cdid
},
dataType: "html", //expect html to be returned
success: function(response){
if(Math.floor(SearchValue) == SearchValue && $.isNumeric(SearchValue)){
getDetails2(SearchValue);
}
$("#showSearchResult").html(response);
$('#visiableaftersearch').hide();
document.getElementById('txt_name').value='';
document.getElementById('txt_given_name').value='';
$("#loading-image").hide();
}
});
});
});
It is possible, if you use JSON, so you can add more value as key value pair, in JSONObject such as:
{"key1":"value1","key2":"value2"}
Then using JSON.parse, parse the data from success method. Then loop it, to get the key & value separately.
success: function(response){
var json=JSON.parse(response);
jQuery.each(json, function(i, val) {
console.log("key : "+i+" value: "+val);
});
}
Yes it can be done, Use dataType: "json" in Ajax call(instead of HTML response), and send some flags for error & Success , based on that flags parse your Json response.
For eg,
The php file you are making an ajax request , should encode returning data in Json format, like(with the necessary flags)
//example
echo json_encode(array($con_info));
i've got a simple ajax call:
function message(){
$.ajax({
type: "GET",
url: "/file/timestamp="+ timestamp,
async: true,
cache: false,
success: function(data){
var json = eval('('+data+')');
console.log(json);
}
});
}
and i get an error Uncaught SyntaxError: Unexpected token < at this line: var json = eval('('+data+')');
any ideas?
thanks.
edit:
some more details from the error:
$.ajax.successajax.js:9
f.Callbacks.njquery.js:2
f.Callbacks.o.fireWithjquery.js:2
wjquery.js:4
f.support.ajax.f.ajaxTransport.send.d
here is some php if is helping
public function fileAction()
{
$this->getHelper('viewRenderer')->setNoRender();
$filename = '/test/text.txt';
$front = Zend_Controller_Front::getInstance();
$data = $front->getRequest()->getParams();
$lastModif = !empty($data['timestamp']) ? $data['timestamp'] : 0;
$currentModif = filemtime($filename);
while($currentModif <= $lastModif){
usleep(10000);
clearstatcache();
$currentModif = filemtime($filename);
}
$response = array();
$response['msg'] = file_get_contents($filename);
$response['timestamp'] = $currentModif;
echo json_encode($response);
}
if i run this action i get json: {"msg":"message","timestamp":1331599879} but for some reason the response is not this but some html
It depends on what's inside data. You're running eval, so whatever's in data is being run. Please post the data here,.
What are you expecting to be returned in as data? Running eval will try to execute (data) which doesn't seem like it will be proper javascript. If you just want to store a string you can do:
var json = "(" + data + ")";
jholloman almost had it...
var json = eval("(" + data.responseText + ")");