$(document).ready doesn't work however page is loaded - ajax

As you can understand my title, browser doesn't call the GetReleatedProducts method. I put breakpoint $(document).ready(function () line but it doesn't enter into ajax call.
I checked that I have jquery reference. Do you have any idea?
$(document).ready(function () {
$.ajax({
type: "POST",
url: "http://localhost:2782/AjaxCallPage.aspx/GetReleatedProducts",
data: "{productId:" + productId + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {...}

You've told the server you're sending it JSON:
contentType: "application/json; charset=utf-8",
...but what you're sending it:
data: "{productId:" + productId + "}",
...is not valid JSON. To be valid JSON, the key productId must be in double quotes:
data: '{"productId":' + productId + '}',
// ^ ^
(Here I'm assuming productId is a number. If it's a string, it will also need to be in double quotes.)
So I suspect the server side is rejecting the call because the JSON is invalid.
It's also a bit unusual to send JSON to the server, although it's perfectly valid if that server is coded to expect it and if you send it correctly. It's more typical to send data to the server using the default application/x-www-form-urlencoded.
So unless you've coded your server side to expect to receive JSON, remove the contentType option from your $.ajax call and change data to:
data: {productId: productId}
...which tells jQuery to do the encoding for you.

Related

forge.request.ajax returns: "Invalid parameter not satisfying: url"

We have an ios application built with trigger.io. this application is using forge.request.ajax to send data to our servers. one of our requests occasionally throws an error and returns this:
{"message":"Invalid parameter not satisfying: url","type":"UNEXPECTED_FAILURE"}
since the input parameters are sent in json format I suspected that some characters inputted by users, could break the structure and cause this error. my code looks like this:
forge.request.ajax({
url: "someurl.php",
dataType: "json",
data:"some=data&and=some&more=data&which=is inputted by user",
success: function (data) {
},
error: function (error) {
forge.request.ajax({
url: "errorlog.php",
dataType: "json",
data:"data=" + encodeURIComponent(JSON.stringify(error)),
success: function (data) {
},
error: function (error) {
}
});
}
});
this code gives the above error half the time. and work on the other half. are there any limitations for input parameters in ajax request? since i can't edit objective-c code, i need a solution - preferably a filter- which ensures this function to work with whatever input is entered.
Using encodeURIComponent may help:
var data = "some=data&and=some&more=data&which=is inputted by user";
forge.request.ajax({
url: "someurl.php",
dataType: "json",
data: encodeURIComponent(data)
...
Passing request data as URL Parameters has more than it's share of gotchas though so it may also be worth taking a look at this StackOverflow question: When are you supposed to use escape instead of encodeURI / encodeURIComponent?

Why is ajax parsing json to the form "a=b&c=d"?

$.ajax({
url: '/metadata/hg_billing_cycle',
data: {"a":"b", "c":"d"},
datatype: "json",
contentType: "application/json",
type: 'POST',
error: handleError,
});
I'm using ruby on the server:
post "/" do
puts "ummm: #{request.body.read}"
end
I get the following output:
ummm: a=b&c=d instead of ummm : {"a":"b", "c":"d"}. Why is it doing this?
You are passing an object as the data parameter, from the $.ajax docs
data
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
So your object is converted to a query string.
If you want to send json, then you'll have to well send json.
Convert your object to json (with JSON.stringify) and pass that as the data parameter.
$.ajax({
url: '/metadata/hg_billing_cycle',
data: JSON.stringify({"a":"b", "c":"d"}),
datatype: "json",
contentType: "application/json",
type: 'POST',
error: handleError,
});

wcf service json 400 Bad Request

I get a 400 Bad Request error when I try to call WCF service from client side using ajax. Following is my code,
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
string[] GetUser(string Id);
$.ajax({
type: "POST", //GET or POST or PUT or DELETE verb
url: "http://localhost:58055/Service1.svc/GetUser",
crossDomain: true,
data: '{"Id": "3"}',
contentType: "application/json; charset=utf-8",
dataType: "json", //Expected data format from server
processdata: true, //True or False
success: function (msg) {//On Successfull service call
alert(msg.GetUserResult[0]);
console.log("success " + msg);
},
error: function (msg) {//On Successfull service call
console.log(msg);
}
});
Any insights would be really helpfull...
The first thing you should try is hit the URL using fiddler(so that you could post your data too) and see if you get the same error.
Are you making a cross domain request. From the example it looks like you are not. Could you remove
crossDomain: true,
line and try the jquery again.
There are other options also which unnecessay like processdata. Suggest you to use the following code and see if it works or not.
$.ajax({
type: "POST",
// the url to the service -
url: "url",
// the format that the data should be in when
// it is returned
contentType: "json",
data: '{"Id": "3"}',
// the function that executes when the server
// responds to this ajax request successfully
success: function(data) {
// put the JSON response in the employees table
}
According to the ajax api documentation the default content type is 'application/x-www-form-urlencoded'. When sending JSON, the content type should be 'application/json; charset=utf-8' except that WCF does not like that. I got the same error messages and when I removed the content type I stopped getting this error. By the way, I noticed that you set crossDomain to true, this other question is relevant to that option.

JSON Submission to ASMX web service fails when a double quote is present in parameter

I am using JQuery Ajax method and Ajax to talk to a ASP.NET web service.
I have such a setup in my javascript app.
var parameters='Token="'+psToken+'"&ID="'+psDID+'";
$.ajax({
type: "GET",
url: webMethod,
data: parameters,
dataType: "jsonp",
success: function(msg) {
XXXXX.XX(msg.X);
},
As per the IIS log, I can see that all Encoding is happening right and all instances of double quotes get a %22.
The problem is that when for example psToken contains a double quote i.e " , then the web service crashes and I get a 500 error. It doesnt even get to the point of hitting the web methods, hence I cant debug and figure out the error.
What could I be doing wrong.
If the using of jsonp data type is not critical for you, use json dataType with following code:
var parameters = {
'Token': psToken,
'ID': psDID
};
$.ajax({
type: "GET",
url: webMethod,
data: JSON.stringify(parameters),
dataType: "json",
success: function(msg) {
XXXXX.XX(msg.X);
},

jQuery send string as POST parameters

I want to send a string as an ajax Post parameter.
The following code:
$.ajax({
type: "POST",
url: "http://nakolesah.ru/",
data: 'foo=bar&ca$libri=no$libri',
success: function(msg){
alert('wow'+msg);
}
});
Is not working. Why?
Try like this:
$.ajax({
type: 'POST',
// make sure you respect the same origin policy with this url:
// http://en.wikipedia.org/wiki/Same_origin_policy
url: 'http://nakolesah.ru/',
data: {
'foo': 'bar',
'ca$libri': 'no$libri' // <-- the $ sign in the parameter name seems unusual, I would avoid it
},
success: function(msg){
alert('wow' + msg);
}
});
$.ajax({
type: 'POST',
url:'http://nakolesah.ru/',
data:'foo='+ bar+'&calibri='+ nolibri,
success: function(msg){
alert('wow' + msg);
}
});
I see that they did not understand your question.
Answer is: add "traditional" parameter to your ajax call like this:
$.ajax({
traditional: true,
type: "POST",
url: url,
data: custom,
success: ok,
dataType: "json"
});
And it will work with parameters PASSED AS A STRING.
For a similar application I had to wrap my data object with JSON.stringify() like this:
data: JSON.stringify({
'foo': 'bar',
'ca$libri': 'no$libri'
}),
The API was working with a REST client but couldn't get it to function with jquery ajax in the browser. stringify was the solution.
Not sure whether this is still actual.. just for future readers.
If what you really want is to pass your parameters as part of the URL, you should probably use jQuery.param().
Not a direct answer to your question.. But following is the only syntax that used to work for me -
data: '{"winNumber": "' + win + '"}',
And the parameter-name match with the argument of the server method
I was facing the problem in passing string value to string parameters in Ajax. After so much googling, i have come up with a custom solution as below.
var bar = 'xyz';
var calibri = 'no$libri';
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "http://nakolesah.ru/",
data: '{ foo: \'' + bar + '\', zoo: \'' + calibri + '\'}',
success: function(msg){
alert('wow'+msg);
},
});
Here, bar and calibri are two string variables and you can pass whatever string value to respective string parameters in web method.
I have also faced this exact problem. But I have got a solution and it worked perfectly. I have needed to pass the parameters which are already produced by javascript function. So below code is working for me. I used ColdFusion for the backend. I just directly used the parameters as a variable.
$.ajax({
url: "https://myexampleurl.com/myactionfile.cfm",
type: "POST",
data : {paramert1: variable1,parameter2: variable2},
success: function(data){
console.log(data);
} )};
Instead of this, encode the POST request as a string and pass to the data parameter,
var requestData = "Param1=" + encodeURIComponent(jsParam1) + "&Param2="+ encodeURIComponent(jsParam2);
var request = $.ajax({
url: page + "?" + getVars,
method: "POST",
data: requestData,
dataType: "html",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
});

Resources