Setting processData to false in jQuery breaks my AJAX request - ajax

I've googled for a while now and can only find what processData: false does. I can't find anyone who has experienced this same issue.
I'm passing JSON back to the server and do not want jQuery to automatically convert the data to a query string so I'm setting processData to false. I can see the request firing if I take out processData, but as soon as I put it in I do not see any requests being made (using Firebug & Chrome dev tools).
$.ajax({
url: myUrl,
type: "POST",
data: {foo: "bar"},
processData: false,
contentType: 'application/json'
});
The request I was initially making was a bit more complex than this but I've simplified it to try to narrow down the problem but this simple piece of code does not work either (again, it does work if I comment out processData). Also, I am not seeing any JavaScript errors in the console.
Edit
For future web searchers: As lonesomeday pointed out, jQuery will not throw any errors if you supply either a JS object or an incorrectly formatted JSON string. It will simply not fire the request.

You want to pass the data as JSON. You are passing a Javascript object. JSON is a way of serializing Javascript objects to strings so that they can be passed around without compatibility issues.
You actually want to pass the JSON in a string:
$.ajax({
url: myUrl,
type: "POST",
data: '{"foo": "bar"}',
processData: false,
contentType: 'application/json'
});

Actually, processData by default assumes that data passed is an object and sends it as application/x-www-form-urlencoded.
Summing up everything said above by #lonesomeday and #vsm to send raw JSON (what is different from the form data) you need to:
$.ajax({
url: 'http://here-i.am/send-me/an/angel', // Determining far end
data: JSON.stringify({foo: "bar"}), // Obtaining proper JSON string from data object
processData: false, // Preventing default data parse behavior
contentType: "application/json" // Setting proper `ContentType` for our data
...
});

Figure I'd add my current understanding (as of a few hours..)
ProcessData = true : convert an object's name value pairs into a URL encoding, or an array's objects into name value pairs, or take a string as a literal.
ProcessData = false: take a string as a literal, or call an object's ToString() method.
On top of the ProcessData = true, by setting the 'traditional' flag, it can send it using a recursive encoding that captures complex structures, or a flat name value pair list.
So with respect to the OP, it worked without specifying processData since the default is true. So it converted the name value pairs in the object to a URLEncoded form. When you add the line back in, it calls your object's toString() method. Since you don't have a URL encoded string being returned by a toString() method (you have none), you will get a string such as "[object Object]". Perhaps jQuery cannot send strings that aren't URL encoded, or does not use the inherited toString() method.
The two solutions presented convert the object to a JSON string, and thus there is no processing, and thus processData does nothing. The contentType setting helps the server understand what is being sent.
In addition, one person commented that processing adds the encoded properties to the URL. Not quite: It sends that data via the most appropriate method; GET means appended to the URL, and POST means a urlencoded http body.

Related

Sending JavaScript Array or Object to Django View

I am trying to send via AJAX an array (or object) to my Django View.
In JS File:
var dataArr = [];
dataArr.push({'status':'active'});
...
var json = JSON.stringify(dataArr);
...
$.ajax({
type: "POST",
url: "/filter/",
data: {
'filter_text' : json,
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: filterSuccess,
dataType: 'json',
contentType: 'application/json'
});
I am getting a 403 Forbidden error in Javascript. I tried several things, e.g. omitting the dataType / contentType, sending a Javascript object instead of an array, etc.
You can't pass the array directly to url,
Use jQuery.param(yourObject).
The param() method creates a serialized representation of an array or an object that can be understandable by various frameworks like php, ruby, django etc.
For again converting it to python
from urllib import parse
value = parse.parse_qs(self.request.POST.get('name'))
Note that using prase you can lost some information, so recheck your data after getting it in python.

Web API and Entity framework

I am working with back end written by another developer. I think he used Web API 2.0 and Entity Framework. Specifically I am having a problem with POST. Here is the code:
public CL_CASE Post([FromBody]CL_CASE value)
{......
I am testing it using Chrome's Advanced Rest Client. I am specifying a few parameters and clicking Send. The value I am getting is null. What might be causing that?
var response = $http({
method: 'POST',
withCredentials: true,
dataType: "json",
data: JSON.stringify(payload),
params: '',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Content-Type': 'application/x-www-form-urlencoded'
},
url: url
});
payload is an object with properties that match CL_CASE.
There are a couple things you can check.
First, are the parameters you are passing in the body of the post or on the query string? The attribute [FromBody] on the value argument passed into the Post method is telling the model binder to look in the body of the HTTP request for matching parameters.
It's also important that the parameters you are passing are being specified using the correct Content-Type. Are you using a Content-Type header? If not, the expectation is probably that you are using form encoding. If that's the case, you should be specifying your parameters in the body like this:
paramName1=paramValue&paramName2=paramValue
Be sure the case of the parameter matches the case used for the matching property in the CL_CASE class too. These can be different cases and still be matched if you are using the right ContractResolver.
Another thing to be sure of is that you are in fact choosing to POST instead of GET.
Are there any other attributes on the Post method in your controller? If there are, these could be throwing off the binding.

While posting json to MVC controller method, I get "Length of string exceeds value set on maxJsonLength property."

While trying to post json object using:
$.ajax({
url: baseUrl + 'Controller/SaveBase64Image',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ "imageData" : ' + imageData + '}'
});
I get the following error back from the server:
"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property."
This error was partially answered RIGHT HERE.
My problem is that the serialized json object I am posting to a controller method gets automatically de-serialized in order to convert it to the correct object in the argument of the method.
Is there a way to override the class that handles this automatic de-serialization?
Thanks in advance!
After reading one of Cordova's articles on how to use the camera capture, they said that newer cameras have such high resolution that the base64 string is too large for the clientside javascript to send to server. They recommend another path of which I am working on right now. I will let you know when I have a solution.

proper way to send ajax json to play framework

I've read a couple of posts here regarding how to do this and I can get it working only half-way.
This works (sending json object as text):
function go(itemid)
{
apiRoutes.controllers.Application.addItem(itemid).ajax({
data: '{"reqid":0,"iid":2,"description":"adsf"}',
dataType: 'text',
contentType:'application/json',
success: function(reply) {
alert(reply)
}
});
}
This does not (sending object as json):
function go(itemid)
{
apiRoutes.controllers.Application.addItem(itemid).ajax({
data: {"reqid":0,"iid":2,"description":"adsf"},
dataType: 'text',
contentType:'application/json',
success: function(reply) {
alert(reply)
}
});
}
And what I really want to do is something like this (I've already set up the proper combinators):
function go(itemid)
{
apiRoutes.controllers.Application.addItem(itemid).ajax({
data: #Html(Json.stringify(Json.toJson(item))),
dataType: 'text',
contentType:'application/json',
success: function(reply) {
alert(reply)
}
});
}
My controller looks like this:
def addItem(id: Long) = Action (parse.json) { implicit request =>
Logger.info("add item")
request.body.validate(Item.itemReads).map { item =>
thing.addItem(item)
Ok("Succesfully added item.")
}.recoverTotal{
e => BadRequest("Detected error:"+ JsError.toFlatJson(e))
}
}
In the second case, it never gets to the logging code. Instead it returns a 400 Bad Request immediately (this is likely something triggered in the Action (parse.json) bit I think).
I'd rather send the object as json because when I convert to string and description happens to have an apostrophe in it (') that messes things up. I could probaby escape the apostrophe, but hoping that I'm missing something simple about how to do this with an object rather than a string.
Thanks
As described in the API the dataType param is for setting:
The type of data that you're expecting back from the server.
For sending the json use your second approach (don't send it as a String). Use web browser inspector to validate if correct data were send. AFAIK you shouldn't have problem with Handling the JSON request after receiving valid JSON object
If you are trying to send a non-stringified JSON object in Jquery, $.ajax automatically tries to process it with $.param,
If your data in the ajax call looks like this:
data: {"reqid":0,"iid":2,"description":"adsf"}
This is what $.ajax is doing under the hood before sending:
$.param({"reqid":0,"iid":2,"description":"adsf"})
// "reqid=0&iid=2&description=adsf"
It takes the JSON and serializes it into a form-url-encoded format. Whereas your server is expecting JSON. I would suggest the best way to get around this is to just stringify before sending:
data: JSON.stringify({"reqid":0,"iid":2,"description":"adsf"})
Source: http://api.jquery.com/jQuery.ajax/#sending-data-to-server

GET and POST in ajax

I have a C# web application which uses ajax method to GET and POST data. Is there any difference between GET and POST methods in passing data (in case of contentType,data,dataType)?
$.ajax({
type: 'GET',
url: "url",
contentType: "application/json; charset=utf-8",
data: { value: "data" },
dataType:"json",
success: function (data) {
alert(data);
},
error: function (data) {
alert("In error");
}
});
});
GET encodes the information into the url, the more info you GET the longer your URL becomes.
POST stores data in an array and passes that array to the next page. your Url remains unmodified.
While that may not seem like a huge deal, URLs do have a maximum length and errors will ensue if you exceed it. In addition and call to a specific url may fail due to the modifications GET makes. Apart from that, They are similar enough in function to be interchangeable for most purposes.
In normal form method also GET is used to sent some insensitive small chunk of data to server in querystring, whereas POST is used for sending large and secure data to the server
In case of using ajax GET is commonly used, POST is feasible only when you have to do DB interactions on server or there's some sensitive data involved, read more here http://www.jquery4u.com/ajax/key-differences-post/

Resources