JSON response from Python json.dumps - javascript

I am trying to send a Django HttpResponse encoded as JSON to Javascript.
Python:
response_data = {}
response_data['status'] = 'incomplete'
return HttpResponse(json.dumps(response_data), content_type="application/json")
Jquery:
function auth_request(){
$.ajax({
url: AUTH_ENDPOINT + "myid0001",
context: document.body,
success: function(response){
console.log(response);
console.log(response.status);
if(response.status == "incomplete"){
//do something here
}
}
}
});
}
The console prints {"status": "incomplete"} for the first console log and undefined for the console.log function accessing the status element.
I tried using JSON.parse(response) but I get the error
Uncaught SyntaxError: Unexpected token a in the jquery.js file which I believe is indicating that the object is already a JSON object. However, if I check the type of the object, it displays string. How can I access the elements of the response JSON object?

You need to parse the Json back into a JS object when it's received. Otherwise, it's just text.
jQuery will do that for you if you specify dataType: "json" in the Ajax call.

I found the solution. It turns out that my Django setup was returning some additional string items so when I tried to set dataType: "json" (as #Daniel Roseman suggested) or in the jQuery function or use JSON.parse(response) I received an error. I was able to remove the extra string and it worked properly.

Related

Uncaught TypeError: Illegal invocation when trying to send a JSON object of data included files

I'm trying to send a POST request to the server. The request body is a JSON object contains some objects, texts, files and arrays.
But jQuery returns an error of "Uncaught TypeError: Illegal invocation".
I googled about this situation and I applied some solutions like sending the object inside an array (link) but it didn't work for me.
Here's my JSON data that I want to send:
The JS code is:
$.ajax({
url: 'send.php',
data: {
'bbody': lastBody
},
type: 'POST',
success: function(res) {
if (res == 'success') {
alert('success');
}
}
});
lastBody is the JSON object.
The object data has to be a string.
data: JSON.stringify({key: “value”, key2:”value3”})

Passing a string from Python to Javascript

I'm trying to pass a string from Python to Javascript via ajax POST request but i'm finding serious difficulties.
I've tried both with and without using JSON.
Here's the code
JAVASCRIPT
$.ajax({
url: url, #url of the python server and file
type: "POST",
data: {'data1': "hey"},
success: function (response) {
console.log(" response ----> "+JSON.parse(response));
console.log(" response no JSON ---> " +response);
},
error: function (xhr, errmsg, err) {
console.log("errmsg");
}
});
Python
import json
print "Access-Control-Allow-Origin: *";
if form.getvalue("data1") == "hey":
out = {'key': 'value', 'key2': 4}
print json.dumps(out)
Result is a empty JSON. when i do something like JSON.parse in javascript I get a unexpected end of input error, and when i try to get the length of the response data the size I get is 0.
I suppose that there should be some problems with the client server communication (I use a CGIHTTPServer) or maybe something wrong with the datatype that python or javascript expects.
I also tried without JSON, with something like
Python
print "heyyyyy"
Javascript
alert(response) //case of success
but I also got an empty string.
Could you please give me some advices for handling this problem ?
Thanks a lot!
You may want to compare the two snippets of code CGIHTTPRequestHandler run php or python script in python and http://uthcode.blogspot.com/2009/03/simple-cgihttpserver-and-client-in.html.
There isn't enough code to tell where your request handling code is but if it's in a class inheriting from CGIHTTPRequestHandler then you need to use self.wfile.write(json.dumps(out)), etc.
I managed to solve the problem using the method HTTPResponse from the Django Framework.
Now it's something very similar to this
PYTHON (answering the client with a JSON)
from django.http import HttpResponse
...
data = {}
data['key1'] = 'value1'
data['key2'] = 'value2'
.....
response = HttpResponse(json.dumps(data), content_type = "application/json")
print response;
JAVASCRIPT (Retireving and reading JSON)
success(response)
alert(JSON.stringify(response));
Or if I just want to send a String or an integer without JSON
PYTHON (no JSON)
response = HttpResponse("ayyyyy", content_type="text/plain")
print response
JAVASCRIPT (Retrieving String or value)
success: function (response) {
alert(response);
This works very good, and it's very readable and simple in my opinion!
Instead of print json.dumps(out) you should use return json.dumps(out)
The print will only display it in python's console, just as console in javascript.

Why does an empty 200 create a fail in jQuery?

I've created a simple ajax request to post some json to my api. I've done this a couple times before in other pages, but suddenly I can't get this new call to work properly.
var request = $.ajax({
type: "POST",
url: "/my-api-call",
dataType: "json",
data: JSON.stringify({"pid": 5, "comment": $('#comment').val()})
});
request.done(function(data){
console.log('weve got a succesful response!!');
})
request.fail(function(error){
console.log('weve got an error!!!');
console.log(error);
});
The call simply returns an empty 200 response, which I verify in the browser. But somehow the browser console constantly says weve got an error!!!. As you can see I also log the error, but I that is an object so full of information, that I have no idea what could be important in it. In that error object it also says the response is a plain 200 btw.
Seeing that this code is fairly simple, I can't really figure out what I'm doing wrong.
Does anybody know what I'm doing wrong here? All tips are welcome!
It's because you've set your dataType to json. So jquery is trying to parse your data (which is empty) to json. An empty result is not valid json.
"json": Evaluates the response as JSON and returns a JavaScript
object. The JSON data is parsed in a strict manner; any malformed JSON
is rejected and a parse error is thrown. As of jQuery 1.9, an empty
response is also rejected; the server should return a response of null
or {} instead. (See json.org for more information on proper JSON
formatting.)
From the docs
so you should return {} or null

JQuery gives JSON syntax error when using PHP's json_encode

I have an application that uses JQuery $.ajax to send JSON encoded data to server where I process it and then send back the results also JSON encoded. The problem is that JQuery gives a parse error when I want to process the response. (As if PHP's json_encode function outputs an invalid JSON format).
Here comes the code:
The Javascript code:
$.ajax({
type: 'POST',
url: URL+'pages/processListUIAjaxRequest',
data:{filters: filters, rebuild_params: $('#rebuild_params\\['+unique+'\\]').val()},
dataType: 'json',
success: function(response){
alert(response);
},
error: function(request, status, error){
alert('Unable to update table contents');
console.log(request);
console.log(status);
console.log(error);
}
});
This is a piece of the PHP code which outputs the response:
$response->addResult($uFilters);
header('Content-Type: application/json');
$response->toJSON(true);
The $uFilters is a simple array, and the toJSON method of the $response object is here:
public function toJSON($output = false){
$out = array();
if($this->hasErrors()){
$out['has_error'] = true;
$out['errors'] = $this->getErrors();
} else $out['has_error'] = false;
$out['result'] = $this->_result;
if($output){
echo json_encode($out);
}else{
return json_encode($out);
}
}// toJSON
Every time I run the code i get the 'Unable to update table contents', and on JavaScript console I have:
'SyntaxError: JSON.parse: unexpected character'
despite I defined dataType: as 'json' and the output is json_encode'd by PHP. On the JavaScript console I can see that the response text is:
"{"has_error":false,"result":{"page_id":"xxx"}}"
Tried copy this and validate with online JSON validator tools, the interesting thing is it was valid a few times and it was invalid a few times (without any consistency) Im a bit confused.
Tried to use other headers like:
header('Content-Type: text/json');
header('Content-Type:javascript/json');
header('Content-Type: application/json');
or with no header, but nothing.
If I edit the JQuery ajax request's dataType to 'text' (despite the output is JSON formatted and and even the header says it is a JSON content), then the success handler runs and I got the response correctly. In this case the same problem comes when I try to $.parseJSON(response).
What went wrong? Is my JSON string really invalid?
Debug your response to see what characters are there that is making it not valid. Set the dataType to text and escape the text that is returned.
dataType: 'text',
success: function(response){
console.log(escape(response));
},
You will see the characters that are returned, there is probably some weird return character that is cauing the problem.

Ajax request returns 200 OK, but an error event is fired instead of success

I have implemented an Ajax request on my website, and I am calling the endpoint from a webpage. It always returns 200 OK, but jQuery executes the error event.
I tried a lot of things, but I could not figure out the problem. I am adding my code below:
jQuery Code
var row = "1";
var json = "{'TwitterId':'" + row + "'}";
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert("hello");
alert(result.d);
}
function AjaxFailed(result) {
alert("hello1");
alert(result.status + ' ' + result.statusText);
}
C# code for JqueryOpeartion.aspx
protected void Page_Load(object sender, EventArgs e) {
test();
}
private void test() {
Response.Write("<script language='javascript'>alert('Record Deleted');</script>");
}
I need the ("Record deleted") string after successful deletion. I am able to delete the content, but I am not getting this message. Is this correct or am I doing anything wrong? What is the correct way to solve this issue?
jQuery.ajax attempts to convert the response body depending on the specified dataType parameter or the Content-Type header sent by the server. If the conversion fails (e.g. if the JSON/XML is invalid), the error callback is fired.
Your AJAX code contains:
dataType: "json"
In this case jQuery:
Evaluates the response as JSON and returns a JavaScript object. […]
The JSON data is parsed in a strict manner; any malformed JSON is
rejected and a parse error is thrown. […] an empty response is also
rejected; the server should return a response of null or {} instead.
Your server-side code returns HTML snippet with 200 OK status. jQuery was expecting valid JSON and therefore fires the error callback complaining about parseerror.
The solution is to remove the dataType parameter from your jQuery code and make the server-side code return:
Content-Type: application/javascript
alert("Record Deleted");
But I would rather suggest returning a JSON response and display the message inside the success callback:
Content-Type: application/json
{"message": "Record deleted"}
You simply have to remove the dataType: "json" in your AJAX call
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json', //**** REMOVE THIS LINE ****//
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
I've had some good luck with using multiple, space-separated dataTypes (jQuery 1.5+). As in:
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'text json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
This is just for the record since I bumped into this post when looking for a solution to my problem which was similar to the OP's.
In my case my jQuery Ajax request was prevented from succeeding due to same-origin policy in Chrome. All was resolved when I modified my server (Node.js) to do:
response.writeHead(200,
{
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:8080"
});
It literally cost me an hour of banging my head against the wall. I am feeling stupid...
I reckon your aspx page doesn't return a JSON object.
Your page should do something like this (page_load)
var jSon = new JavaScriptSerializer();
var OutPut = jSon.Serialize(<your object>);
Response.Write(OutPut);
Also, try to change your AjaxFailed:
function AjaxFailed (XMLHttpRequest, textStatus) {
}
textStatus should give you the type of error you're getting.
I have faced this issue with an updated jQuery library. If the service method is not returning anything it means that the return type is void.
Then in your Ajax call please mention dataType='text'.
It will resolve the problem.
You just have to remove dataType: 'json' from your header if your implemented Web service method is void.
In this case, the Ajax call don't expect to have a JSON return datatype.
See this. It's also a similar problem. Working I tried.
Dont remove dataType: 'JSON',
Note: Your response data should be in json format
Use the following code to ensure the response is in JSON format (PHP version)...
header('Content-Type: application/json');
echo json_encode($return_vars);
exit;
I had the same issue. My problem was my controller was returning a status code instead of JSON. Make sure that your controller returns something like:
public JsonResult ActionName(){
// Your code
return Json(new { });
}
Another thing that messed things up for me was using localhost instead of 127.0.0.1 or vice versa. Apparently, JavaScript can't handle requests from one to the other.
If you always return JSON from the server (no empty responses), dataType: 'json' should work and contentType is not needed. However make sure the JSON output...
is valid (JSONLint)
is serialized (JSONMinify)
jQuery AJAX will throw a 'parseerror' on valid but unserialized JSON!
I had the same problem. It was because my JSON response contains some special characters and the server file was not encoded with UTF-8, so the Ajax call considered that this was not a valid JSON response.
Your script demands a return in JSON data type.
Try this:
private string test() {
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize("hello world");
}

Categories

Resources