php can not parse json data to ajax - javascript

The question is very common in stackoverflow. I have been to too many solution provided in this forum for problem like mine. but it did not help. So i am posting it. Please please be kind enough to answer me.
Problem:
I am trying to send an integer from cakephp controller function to view having ajax call.
I keep getting this error for all the solutions i tried from here and other forums.
"SyntaxError: Unexpected token a in JSON at position 0"
Please tell me what is wrong looking at my code :
I can see clearly i get data in json format in php while i make echo but not in main Ajax call.
Console says :the result is {"data":1}
Controller :
public function addit()
{
$mycount = 1;
$responseJSON = array(
'data' => $mycount
);
//$responseJSON = array('status' =>'true', 'result'=>$arr);
header('content-type:application/json');
$response = json_encode($responseJSON);
echo $response;
}
ajaxcall in view:
$(document).ready(function(){
$('#bn_cart').click(function(event){
//alert('clicked');
var form_data = $(this).serialize();
var id = $('#id').val();
alert("your item id is "+ id);
var csrfToken = <?php echo(json_encode($this->request->getParam('_csrfToken'))) ?>;
//alert("your form data "+csrfToken);
event.preventDefault();
$.ajax({
headers: {
'X-CSRF-Token': csrfToken
},
url:'../addit',
type:'POST',
data: { id : id },
dataType:'json',
success:function(xhr, response){
var respons = response;
console.log("conosle success says "+ (respons.result));
alert("success"+respons.result);
},
error:function(xhr, e,etype,response){
//alert("<br>error<br>"+ error.responseText.message);
alert("response = "+ response +"xhr = "+ xhr + " e = " + e + " etype = "+ etype);
console.log(" response =" + response + "error ="+ e +"xhr = "+ xhr + " etype = "+ etype );
// $("#result").html(error.Message);
// alert('error ='+(error.Message));
}
});
});
});
Network>Header:
Request URL: http://localhost/shoppingCart/products/addit
Request Method: POST
Status Code: 200 OK
Remote Address: [::1]:80
Referrer Policy: no-referrer-when-downgrade
Cache-Control: no-store, no-cache, must-revalidate
Connection: Keep-Alive
Content-Length: 583
Content-Type: text/html; charset=UTF-8
Date: Tue, 23 Oct 2018 14:10:08 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive: timeout=5, max=99
Pragma: no-cache
Server: Apache/2.4.29 (Win32) OpenSSL/1.0.2n PHP/7.1.15
X-DEBUGKIT-ID: 182187f0-546d-48d4-9e5a-6746a40dba64
X-Powered-By: PHP/7.1.15
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 4
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Cookie: csrfToken=0a8a1f6e98fe8274e80f9bdcb3ba5df66a5af4296126302d3e79bf44e856ed720438947bb93f041f772ac1e39d083aa2d88c5159697c9843a8b04eace893260b; CAKEPHP=mhphclr8cuvacrlotbit45dd3l; csrftoken=t0p47S5P7NBcwGGQ9sfuNGLi5JJDkll8ifuCWhG3W6MRSIewe9GtRNjanPUqms54
Host: localhost
Origin: http://localhost
Referer: http://localhost/shoppingCart/products/view/2
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
X-CSRF-Token: 0a8a1f6e98fe8274e80f9bdcb3ba5df66a5af4296126302d3e79bf44e856ed720438947bb93f041f772ac1e39d083aa2d88c5159697c9843a8b04eace893260b
X-Requested-With: XMLHttpRequest
Network>>Response :
{"data":1}

You need to return your response encoded in json. You are trying to echo a non json-encoded response which will not work.
public function addit()
{
$mycount = 1;
$responseJSON = array(
'data' => $mycount
);
//$responseJSON = array('status' =>'true', 'result'=>$arr);
header('content-type:application/json');
return json_encode($responseJSON);
}
Ajax call :
success:function(data, status, jqxhr)
var respons = data;
console.log("conosle success says "+ (respons.result));
alert("success"+respons.result);
},

Related

jQuery Ajax Form Data settings convert to pure javascript

Found the answer thanks from Patrick Evans:
window.onload = function()
{
var data = new FormData();
data.append("gcd", "gcd");
data.append("name", "name");
ajax({
type: "POST",
url: url,
data: data,
success: function(resopnse)
{
console.log(resopnse);
},
dataType: "json"
});
}
var http_request = new XMLHttpRequest();
function ajax(options) {
http_request.open(options.type || 'GET', options.url, true);
http_request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
http_request.send(options.data || null);
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var type = options.dataType || '';
switch (type.toLowerCase()) {
default:
options.success(http_request.responseText);
break;
case 'json':
options.success(JSON.parse(http_request.responseText));
break;
}
}
}
}
}
Here is my Ajax test javascript using jQuery and Pure Javascript Ajax:
window.onload = function()
{
var url = "GRNM";
var data = {
gcd: "gcd",
name: "name"
};
$.ajax({
type: "POST",
url: url,
data: data,
success: function(resopnse)
{
console.log(resopnse);
},
dataType: "json"
});
ajax({
type: "POST",
url: url,
data: data,
success: function(resopnse)
{
console.log(resopnse);
},
dataType: "json"
});
}
Pure Javascript Ajax:
var http_request = new XMLHttpRequest();
function ajax(options) {
http_request.open(options.type || 'GET', options.url, true);
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
http_request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
http_request.send(JSON.stringify(options.data) || null);
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var type = options.dataType || '';
switch (type.toLowerCase()) {
default:
options.success(http_request.responseText);
break;
case 'json':
options.success(JSON.parse(http_request.responseText));
break;
}
}
}
}
}
And this is the result:
jQuery: I could get the value data successfully
General:
Request URL: http://gaspc-011:8888/GRNM
Request Method: POST
Status Code: 200
Remote Address: 192.168.1.120:8888
Referrer Policy: strict-origin-when-cross-origin
Response Headers:
Connection: keep-alive
Content-Length: 43
Content-Type: application/json
Date: Fri, 27 Aug 2021 06:20:37 GMT
Keep-Alive: timeout=60
Request Headers:
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 17
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host: gaspc-011:8888
Origin: http://gaspc-011:8888
Referer: http://gaspc-011:8888/index01
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36
X-Requested-With: XMLHttpRequest
Form Data:
gcd: gcd
name: name
Pure Javascript: I couldn't get the data
General:
Request URL: http://gaspc-011:8888/GRNM
Request Method: POST
Status Code: 400
Remote Address: 192.168.1.120:8888
Referrer Policy: strict-origin-when-cross-origin
Response Headers:
Connection: close
Content-Language: en-US
Content-Type: text/html;charset=Shift_JIS
Date: Fri, 27 Aug 2021 06:20:37 GMT
Transfer-Encoding: chunked
Request Headers:
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 27
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host: gaspc-011:8888
Origin: http://gaspc-011:8888
Referer: http://gaspc-011:8888/index01
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36
X-Requested-With: XMLHttpRequest
Form Data:
{"gcd":"gcd","name":"name"}:
My Spring Boot Controller couldn't find the gcd and name parameter that came from pure javascript because the Form Data format is different. I've also tried to use FormData() but couldn't make it work.
My Form Data becomes like this:
Form Data:
------WebKitFormBoundaryLgD8tjkxnVk4hfiE
Content-Disposition: form-data; name: "gcd"
gcd
------WebKitFormBoundaryLgD8tjkxnVk4hfiE
Content-Disposition: form-data; name="name"
name
------WebKitFormBoundaryLgD8tjkxnVk4hfiE--
I've also tried changing http_request.send(JSON.stringify(options.data) || null); to http_request.send(options.data || null); but didn't worked.
How can I achieve the same result as jQuery? How can I pass my var data object to controller using Ajax POST same as jQuery?
You need to supply the correct content-type with the correct content.
If you want to send JSON text you have to use application/json content-type
http_request.setRequestHeader('Content-Type', 'application/json');
http_request.send(JSON.stringify(options.data));
If you want to use the FormData object you need the multipart/form-data content-type
let fd = new FormData();
for(let key in options.data){
fd.append(key,options.data[key]);
}
//don't need to explicitly set content-type when sending FormData
//it will automatically do that
//http_request.setRequestHeader('Content-Type', 'multipart/form-data');
http_request.send(fd);
If you just want to use your object you will need to convert it to one of the previously mentioned methods or create a param string from it and use application/x-www-form-urlencoded content-type
//builds a param=value&param2=value2 type of string from your options.data object
let paramStrings = [];
for(let key in options.data){
paramStrings.push(`${key}=${options.data[key]}`);
}
let data = paramStrings.join('&');
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
http_request.send(data);

Sending JSON from Javascript to PHP Server

I want to send JSON from javascript to PHP server vice versa, but i got exception SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data while get data from server.
I have tried to validate JSON output on JSONLint and my JSON is valid.
Here are JSON I would expected from server :
{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5
}
and JSON which I sent to server :
{"counter":"123"}
Here are my code :
$.ajax({
type: 'POST',
url: 'http://localhost:8080/debug/json.php',
data: {json: JSON.stringify(obj)},
dataType: 'json'
})
.done( function( data ) {
console.log('done');
console.log(data);
})
.fail( function( data ) {
console.log('fail');
console.log(data);
});
when obj is
var obj = {"counter":counter};
and on server-side (php)
<?php
header('Content-type: application/json');
$json = file_get_contents('php://input');
$json_decode = json_decode($json, true);
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Request header
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:55.0) Gecko/20100101 Firefox/55.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 36
Origin: null
Connection: keep-alive
Response Header
Date: Thu, 22 Jun 2017 04:11:53 GMT
Server: Apache/2.4.3 (Win32) OpenSSL/1.0.1c PHP/5.4.7
X-Powered-By: PHP/5.4.7
Content-Length: 31
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: application/json
I think problem comes from my PHP Script, but when i tried to access directly from URL its work like a charm. I got status code 200 but the response error. What I missed? thank you.

Jquery File Upload - Not sending headers in IE9

I'm using jQuery Fileupload to upload files. Its not sending headers that I set to the server. Why is the Authorization header missing only in IE but passed in chrome?
Here is the code:
upload_photo: function(){
var url = '/api/v1/upload';
$('#photoupload').fileupload({
url: url,
dataType: 'json',
paramName: 'uploadFile',
beforeSend: function ( xhr ) {
setHeader(xhr);
$("#check_progress").html('true');
},
done: function (e, responseJSON) {
var id = responseJSON.result.id;
url = responseJSON.result.url;
var photo_ids = $("#photo_ids");
var val = photo_ids.val();
photo_ids.val(val + id.toString() + ",");
$(".photothumb-wapper").append('<div class=\"photothumb\" id="post_photo_'+id+'"><div><img src=\"'+url+'\" /></div><img class=\"thumb-delete photo_delete\" id=\"'+id+'\" title=\"Remove\" src=\"/assets/delete-red.png\"></div>');
$("#check_progress").html("");
},
start: function (e, data) {
$(".photothumb-wapper").append('<div class="photothumb photoprogress" style="border:none"><img src="/assets/ajax-loader.gif" /></div>');
},
always: function (e, data) {
$(".photoprogress").remove();
}
});
}
var setHeader = function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer fdf49c4f1cfgc176eb952f18eeefaec3e7');
};
Headers passed in IE:
Request : POST /api/v1/upload HTTP/1.1
Accept : text/html, application/xhtml+xml, \*/\*
Referer : url
Accept-Language : en-US
User-Agent :Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
Content-Type :multipart/form-data; boundary=---------------------------7de2dfe037204f6
Accept-Encoding :gzip, deflate
Host :url
Content-Length :776595
DNT :1
Connection :Keep-Alive
Cache-Control :no-cache
Cookie :sitecookies
Headers passed in Chrome:
ResponseHeaders
date : Tue, 04 Mar 2014 07:32:20 GMT
Connection: Keep-Alive
content-length:225
content-type:application/json; charset=utf-8
cache-control:no-cache
RequestHeaders
Accept: application/json, text/javascript, \*/\*; q=0.01
Authorization: Bearer fdf49c4f1cfgc176eb952f18eeefaec3e7
X-Requested-With: XMLHttpRequest
Why is the Authorization header missing in IE?
This answers my question,
Only browsers with support for XHR file upload support setting custom headers.
As a workaround in old browsers like our dear IE, you could set a cookie with the authentication token when the user authenticate and then get it in the server and verify it the same way you verify the header one. I know that it is not the most elegant solution but it works.

jquery ajax long pending status type put and json only on android

The same code is working fine on every desktop browser (Safari, Chrome, Firefox, IE) or iPad 4 in 1-2 seconds. But fails with long pending (2-4 minutes) when testing on Android tablet (4.2.2) browser / Google Chrome 31 or iPad 2 UMTS.
jquery version = 1.10.2
var datasend;
$.putJSON = function(url, data, callback) {
return $.ajax({
url : url + "?_=" + jQuery.now(),
beforeSend: function(par1, par2, par3){
console.log('beforeSend: ',par1, par2, par3);
},
error: function (par1, par2, par3){
console.log('error: ',par1, par2, par3);
},
success : callback || function() {
},
data : JSON.stringify(data),
timeout: 15000,
dataType : 'json',
type : 'PUT',
cache: false,
contentType : 'application/json; charset=utf-8'
});
};
$('#postklick').on('click', function() {
$.putJSON('/rest/idea', datasend, function(data, statusText, xhr) {
var response = $.parseJSON(xhr.responseText);
console.log(response.exception);
}).fail(function(xhr, status, statusError) {
console.log(statusError);
});
return false;
});
datasend = {
"name": "idee",
"description": "adasdasdasa",
"base64Image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAeoAAAGkCAYAAAD+P2YmAA..."
};
Response Header:
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Server: Microsoft-IIS/7.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: accept, origin, content-type
Access-Control-Max-Age: 1728000
access-control-allow-credentials: true
X-REST-Response-State: ok
X-Powered-By: ASP.NET
Date: Fri, 24 Jan 2014 14:55:18 GMT
Content-Length: 811
Request Header:
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Content-Type: application/json; charset=utf-8
X-Requested-With: XMLHttpRequest
Content-Length: 326765
Connection: keep-alive
In chrome//net-internals/#events I see:
...
[st = 10] HTTP_STREAM_PARSER_READ_HEADERS --> net_error = -101 (ERR_CONNECTION_RESET)
[st = 128859] HTTP_TRANSACTION_RESTART_AFTER_ERROR --> net_error = -101 (ERR_CONNECTION_RESET)
...
Any ideas?

Got XHR.status 0 while doing http get request through jquery code while HTTP response is 200 ok

I am trying to send get request to REST based API(JAX-RS/Jersey based API) through jquery. Request reaches successfully to API as I have seen in logs and on firebug i saw 200 ok response
below is my jquery based client
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'GET',
url: 'http://mtnlp.com:8080/restdemo/resources/employee/1',
dataType: "json",
success: function(data){
alert("success");
},
error: function(xhr){
alert("error"+xhr.status);
}
});
});
});
But xhr.status is 0.
MY resource is
#GET
#Produces(MediaType.APPLICATION_JSON)
public String getJson( #PathParam("empno") int empno) {
JSONObject jObject = new JSONObject();
System.out.println("someone calls me");
switch(empno) {
case 1 :
jObject.put("name", "George Koch");
jObject.put("age", "58");
break;
case 2:
jObject.put("name", "Peter");
jObject.put("age", "50");
break;
default:
jObject.put("name", "Unknown");
jObject.put("age", "-1");
} // end of switch
return jObject.toString();
}
When i use my jersey based client it works fine. but with jquery based client I am facing above issue.
Please find below the request and response headers for HTTP get request
Response Headers
Content-Type: application/json
Date: Tue, 04 Jun 2013 06:38:12 GMT
Server: Apache-Coyote/1.1
Transfer-Encoding: chunked
Request Headers
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate Accept-Language en-US,en;q=0.5
Host: localhost:8080
Origin: null
User-Agent: Mozilla/5.0 (Windows NT5.1; rv:19.0) Gecko/20100101 Firefox/19.0

Categories

Resources