How to get the data value during Jquery Ajax calling? - javascript

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);
}
});

Related

put JSON response in var and output it

I have a form which sends Zip code + housenumber to an external page and the external page sends me a json response with the address information back.
This all works but how can i grab this json response put it into a variable and output it again on my page.
Here i do a post to a page
function validate() {
var postc = $('#postc').val();
var huisnr = $('#huisnr').val();
$.ajax({
url: 'postcodecheck.php',
type: 'POST',
dataType: 'json',
data: 'postc=' + postc + '&huisnr=' + huisnr,
cache: false
});
and i get this response in the header of postcodecheck.php
{"location":[{"city":"Amsterdam","postcode":"1012NX","straat":"Kalverstraat","nummer":1}]}
How can i grab this reponse and put it into a variable ?
Any help would be highly appriciated.
$.ajax({
url: 'postcodecheck.php',
type: 'POST',
dataType: 'json',
data: 'postc=' + postc + '&huisnr=' + huisnr,
cache: false,
success: function(data) {
$.each(data.location, function(index, value) {
console.log("City " + value.city)
console.log("postcode " + value.postcode)
console.log("straat " + value.straat)
})
}
});
Add success and inside success you can iterate on the data
Demo
you can use request callback to get the retrieved data & put it into a variable
$.ajax({
url: 'postcodecheck.php',
type: 'POST',
dataType: 'json',
data: 'postc=' + postc + '&huisnr=' + huisnr,
cache: false
})
.done(function(data) {
console.log(data);});
The ajax call have another attribute called success you need to use it.
var store = '';
$.ajax({
url: 'postcodecheck.php',
type: 'POST',
dataType: 'json',
data: 'postc=' + postc + '&huisnr=' + huisnr,
cache: false,
success: function(result){
store = result;
}
});
Result
console.log(store); //{"location":[{"city":"Amsterdam","postcode":"1012NX","straat":"Kalverstraat","nummer":1}]}
You need to use the done method and pass data as an argument to the callback function that will then contain the response from the server.
$.ajax({
url: 'postcodecheck.php',
type: 'POST',
dataType: 'json',
data: 'postc=' + postc + '&huisnr=' + huisnr,
cache: false
}).done(function(data) {
var result = data;
alert(result);
});

when use contentType: 'application/json; charset=utf-8', then my data is not passed to api controller

I,m updating a record using PUT in web api, when I use contentType: 'application/json; charset=utf-8', then my data is not passed to api controller but when i comment this line data is transfered. can any one explain this ? below is my Call from mvc view
$(function () {
$("#btnSubmit").click(function () {
var id = $("#hdnProductID").val();
var ProductName = $("#txtProductName").val();
var QuantityPerUnit = $("#txtQuantityPerUnit").val();
var ReorderLevel = $("#txtReorderLevel").val();
var UnitPrice = $("#txtUnitPrice").val();
var UnitsInStock = $("#txtUnitsInStock").val();
var UnitsOnOrder = $("#txtUnitsOnOrder").val();
$.ajax({
url: "http://localhost:2821/api/Products"+ "/" + id,
type: 'PUT',
contentType: 'application/json; charset=utf-8',
data:{ProductName:ProductName,QuantityPerUnit:QuantityPerUnit,ReorderLevel:ReorderLevel,UnitPrice:UnitPrice,UnitsInStock:UnitsInStock,UnitsOnOrder:UnitsOnOrder},
success: function (data) {
alert("success");
},
error: function (msg) {
alert(msg);
}
});
});
});
Below is my controller method
public IHttpActionResult PutProduct(int id, Product product)
{}
If contentType is not specified in the request, it takes default contentType, i.e., "application/x-www-form-urlencoded; charset=UTF-8" and no need to stringfy the post data but if contentType is "application/json; charset=utf-8", need to stringfy post data explicitly. So it should be:
$.ajax({
url: "http://localhost:2821/api/Products"+ "/" + id,
type: 'PUT',
contentType: 'application/json; charset=utf-8',
data:JSON.stringify({ProductName:ProductName,QuantityPerUnit:QuantityPerUnit,ReorderLevel:ReorderLevel,UnitPrice:UnitPrice,UnitsInStock:UnitsInStock,UnitsOnOrder:UnitsOnOrder}),
success: function (data) {
alert("success");
},
error: function (msg) {
alert(msg);
}
});

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);
}
});

Jquery Ajax POST Request sending data issue

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);
}
});

Sending string to wcf service using jquery ajax. why can i only send strings of numbers?

For some reason, I'm only able to pass strings containing numbers to my web service when using jquery ajax. This hasn't been an issue so far because I was always just passing IDs to my wcf service. But I'm trying to do something more complex now but I can't figure it out.
In my interface:
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json)]
DataTableOutput GetDataTableOutput(string json);
My webservice:
public DataTableOutput GetDataTableOutput(string json)
{
DataTableOutput x = new DataTableOutput();
x.iTotalDisplayRecords = 9;
x.iTotalRecords = 50;
x.sColumns = "1";
x.sEcho = "1";
x.aaData = null;
return x;
}
Javascript/Jquery:
var x = "1";
$.ajax({
type: "POST",
async: false,
url: "Services/Service1.svc/GetDataTableOutput",
contentType: "application/json; charset=utf-8",
data: x,
dataType: "json",
success: function (msg) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(XMLHttpRequest.status);
//alert(XMLHttpRequest.responseText);
}
});
The above code WORKS perfectly. But when I change x to "t" or even to "{'test':'test'}" I get a Error 400 Bad Request error in Firebug.
Thanks,
John
EDIT:
Making some progress!
data: JSON.stringify("{'test':'test'}"),
Sends the string to my function!
EDIT2:
var jsonAOData = JSON.stringify(aoData);
$.ajax({
type: "POST",
async: false,
url: sSource,
contentType: "application/json; charset=utf-8",
data: "{'Input':" + jsonAOData + "}",
dataType: "json",
success: function (msg) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(XMLHttpRequest.status);
//alert(XMLHttpRequest.responseText);
}
});
EDIT3: I modified the code block I put in EDIT2 up above.
Swapping the " and ' did the trick!
$.ajax({
type: "POST",
async: false,
url: sSource,
contentType: "application/json; charset=utf-8",
data: '{"Input":' + jsonAOData + '}',
dataType: "json",
success: function (msg) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(XMLHttpRequest.status);
//alert(XMLHttpRequest.responseText);
}
});
However, I have a new problem:
public DataTableOutput GetDataTableOutput(DataTableInputOverview Input)
{
The input here is completely null. The values I passed from jsonAOData didn't get assigned to the DataTableInputOverview Input variable. :(
I modified the code block I put in EDIT2 up above.
Swapping the " and ' did the trick!
$.ajax({
type: "POST",
async: false,
url: sSource,
contentType: "application/json; charset=utf-8",
data: '{"Input":' + jsonAOData + '}',
dataType: "json",
success: function (msg) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(XMLHttpRequest.status);
//alert(XMLHttpRequest.responseText);
}
});
This actually worked but I had to fix the format of the object I was sending to GetDataTableOutputOverview

Categories