Jquery Ajax POST Request sending data issue - javascript

I have searched a lot and not been able to find a working solution to why my post request is not sending it's data to the server. I can send the request without data and I get my results from the server, but I just cannot send my data to the server. I have narrowed it down to the "data" attribute and assume I am just doing something wrong. Thank you.
Client
var scriptURL = "default/scripts/serverside/Scripts.aspx";
$.ajax({
type: "POST",
url: baseURL + scriptURL + "/SaveItem",
data: "{}", //works (to return a result)
//data: "{sendData: '" + dataPackage + "'}", //does not work
//data: dataPackage, //does not work
//data: { sendData: dataPackage }, //does not work
//data: { "sendData": dataPackage }, //does not work
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
de("server result:" +result);
}
});
Server
[WebMethod]
public static string SaveItem(string sendData)
{
string result = "received: " + sendData;
return result;
}
Please help, I just cant seem to get it working and know it has got to be a syntax issue...
Similar problems I have found (but no working answers):
https://stackoverflow.com/questions/7258933/jquery-ajax-data-parameter-syntax
https://stackoverflow.com/questions/7262940/webmethod-not-being-called?lq=1

Try this one:
$.ajax({
type: "POST",
url: baseURL + scriptURL + "/SaveItem",
data: $.toJSON({ sendData: dataPackage }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
de("server result:" +result);
}
});
The toJSON will convert your JS object into a proper JSON string. You could also use JSON.stringify

Try this:
var scriptURL = "default/scripts/serverside/Scripts.aspx";
$.ajax({
type: "POST",
url: baseURL + scriptURL + "/SaveItem",
data: {sendData: "string to send" }
dataType: "json",
success: function (result) {
de("server result:" +result);
}
});

Related

How to get the data value during Jquery Ajax calling?

I'm calling Ajax like below
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: path,
dataType: "json",
data: '{ "jsondata":' + jsondata + ',"key":"' + getValue('id') + '"}',
success: function (data) {
callback(data);
},
error: function (error) {
callback(error.responseText);
}
});
I want to get the "Data" value at calling time because after the call the execution doesn't goes to the desired web method and the error is showing like
""Message":"Invalid web service call, missing value for parameter: \u0027obj\u0027..."
I have to track the the Ajax posting value during Ajax call and find out what is the problem with posting data.Is there any tricks to get the data value before Ajax calling?
Any help will be appreciated.
Edit: I'm sending the jsondata value like below
var jsondata = '{ "pagenumber":"' + pagenumber + '","sortColumn":"' + sortColumn + '","sortDirection":"' + sortDirection + '","rowPerPage":"' + rowPerPage + '"}';
Thanks.
I was just checking with below code -
please have a look. please check beforesend content
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/dummy',
dataType: "json",
data: '{dummy:"dummy"}',
success: function (data) {
alert(data);
},
error: function (error) {
alert(error);
},
beforeSend: function(data,data1) {
console.log('before'+data1.data)
},
});
})
});
var path = "test_ajax.php";
var jsondata = "Testing123";
var test = "test";
var data = {jsondata : jsondata,key : test};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: path,
dataType: "json",
data: data,
success: function (data) {
alert("success:"+data);
},
error: function (error) {
alert("failure"+error.responseText);
}
});

Error getting json data, ajax

I'm trying to get a data from server without refreshing the page using ajax, So the problem the data come like a text not like json data
my code:
$.ajax({
type: "GET",
url: "http://localhost:8080/search?key=" + QUERY + "",
success: function (reslt) {
console.log(reslt);
console.log(reslt.length);
}
});
and the data on the server:
im using nodejs and express framework the code:
router.get('/search', function (req, res) {
tab = ['08:00', '09:00', '10:00', '11:00'];
res.end(JSON.stringify(tab));
});
why when i do console.log(reslt[3]); it's give me 8 , should give me 10:00
Use
dataType: 'json'
If your response is JSON, always set the datatype to json. Do it like this
$.ajax({
type: "GET",
dataType: 'json',
url: "http://localhost:8080/search?key=" + QUERY + "",
success: function (reslt) {
console.log(reslt);
console.log(reslt.length);
}
});
You have to use dataType and contentType attribute in your ajax request
$.ajax({
type: "GET",
dataType: 'json',
contentType: "application/json",
url: "http://localhost:8080/search?key=" + QUERY + "",
success: function (reslt) {
console.log(reslt);
console.log(reslt.length);
}
});

Ajax call not accepting Names with apostrophe as a parameter

$(".loadingPnl").removeClass('hdn');
var siteurlA = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl;
var callUrl = siteurlA + "/_layouts/15/SynchronyFinancial.Intranet/CreateMySite.aspx/SaveAvailableFavoriteItem";
var linkName = $('.txtLinkName').val();
linkName = linkName.replace("'","\'");
$.ajax({
type: "POST",
url: callUrl,
data: "{'linkName': '" + linkName + "', 'webSiteUrl':'" + $('.txtWebAddress').val() + "','iconId':'" + $(".ddlIcons").val() + "'}",
contentType: "application/json; charset=utf-8",
processData: false,
dataType: "json",
success: function (response) {
return true;
},
error: function (response) {
return true;
}
});
return true;
}
The problem is you're building JSON yourself as the request parameters. Moreover, you're building invalid JSON (JSON property names are always with double quotes (")).
Instead, pass an object and let jQuery take care of how to send it - if you pass that instead of a string the server can figure it out. If you really want to do it yourself you can also pass an object to JSON.stringify.
var payload = {
linkName: linkName,
webSiteUrl: $('.txtWebAddress').val(),
iconId: $(".ddlIcons").val()
};
$.ajax({
type: "POST",
url: callUrl,
data: JSON.stringify(payload), // or just payload
contentType: "application/json; charset=utf-8",
processData: false, // if you just pass payload, remove this
dataType: "json"
// you had two `return`s here, but they wouldn't work, make sure
// you understand why
// http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call
});
You can send a JSON instead. Or use JSON.stringify if you want String.
{
'linkName' : linkName,
'webSiteUrl' : $('.txtWebAddress').val(),
'iconId' : $(".ddlIcons").val()
}
Don't create JSON string by yourself AND don't use JSON.stringify().
Problem with creating JSON string yourself is to escape string properly for JavaScript (which could be tricky). see Special Characters
Problem with JSON.stringify is that I found it somehow slower than XMLHttpRequest which is strange because I thought it is using JSON.stringify behind curtains.
XMLHttpRequest is handling this for you. If you just pass your object as a data and XMLHttRequest will do the trick.
$.ajax({
type: "POST",
url: callUrl,
data: {'linkName': linkName,
'webSiteUrl': $('.txtWebAddress').val(),
'iconId': $(".ddlIcons").val()
},
contentType: "application/json; charset=utf-8",
processData: false,
dataType: "json",
success: function (response) {
return true;
},
error: function (response) {
return true;
}
});

How to pass parameter through url using jquery ajax without refreshing page?

I am trying to pass parameter using Get method in Asp.Net. But in address bar url did not change.
Please any one help me to pass parameter using ajax call through url.
Some try from my side is as below Consider url as below
var obj = { templateName: templateName, pageIndex: pageIndex };
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "result.aspx/DisplayResult",
// data: "{'templateName':'" + document.getElementById('txtSearch').value + " &pageIndex : '" + pageIndex + "'' }",
data: JSON.stringify(obj),
dataType: "json",
success: OnSuccess,
error: function (result) {
alert(result.value);
}
});
Your AJAX request looks fine, but there's no reason it'd change the URL. If your request is successful, it will be handled by the OnSuccess function. However, I don't see where you've defined the function referenced by onSuccess. Try this:
var obj = { templateName: templateName, pageIndex: pageIndex };
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "result.aspx/DisplayResult",
// data: "{'templateName':'" + document.getElementById('txtSearch').value + " &pageIndex : '" + pageIndex + "'' }",
data: JSON.stringify(obj),
dataType: "json",
success: function (response) {
// You should see the response object in your dev console
console.log(response);
// If you want to manipulate the URL for some reason after a successful callback,
// do that here, or better, call a function referenced elsewhere that does it.
},
error: function (result) {
alert(result.value);
}
});

Parse List of Entities using Json In Javascript + MVC3

I have looked for a solution , but nothing that fits my needs was found on the site, so here goes:
I have a Controller that returns a Json:
return Json(new { Item = searchModule});
searchModule is a list of Profiles:
{ "Item":[{"ProfileID":4854,"NickName":"Johnny","users":null,"FirstName":"John","LastName":"Doe"}]}
In JavaScript we have:
$.ajax({
type: "POST",
url: action/controller,
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.Item)
}
})
That returns an object. How can I obtain: Firstname,LastName and NickName ???
Additional answer: If I write the code like below:
var request = $.ajax({
type: "POST",
url: action/controller,
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
}
}).responseText
var obj = json.Parse(request)
, request is null.
since they're objects structured according to the JSON, you should be able to just access the properties like so: data.Item[0].Firstname. You may or may not need to use jQuery.parseJSON to get to this step - calling that is trivial.

Categories