Where am I going wrong? I need to make a service call on a button click on whose 'OnClientClick' property, I've called xyz() for Ajax. But is is not working.
This is my JS:
function xyz() {
$.ajax({
type: 'POST',
url: 'http://localhost:9210/xyzmodule/xyzmethod',
data: "{ field1: '" + $("#txtfield1").val() + "' field2: '" + $("#txtfield2").val() + "' field3: '" + $("#dattimefield3").val() + "'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function () {
alert('Data null');
},
success: function () {
alert('Success');
}
});
}
Here is my service that isn't being called by the Ajax call - the web service is supposed to be called. But it is not.
[HttpPost()]
public String xyzmethod(string json)
...
Have you tried:
function xyz() {
$.ajax({
type: 'POST',
url: 'http://localhost:9210/xyzmodule/xyzmethod',
data: {field1: $("#txtfield1").val(), field2: $("#txtfield2").val(), field3: $("#dattimefield3").val()},
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus + ' - ' + errorThrown);
for (var i in jqXHR) {
console.log(i + ' = ' + jqXHR[i]);
}
},
success: function () {
alert('Success');
}
});
}
syntax should be :
$.ajax({
type: 'POST',
url: 'http://localhost:9210/xyzmodule/xyzmethod',
data: { field1: $("#txtfield1").val(), field2: $("#txtfield2").val(), field3: $("#dattimefield3").val() },
error: function () {
alert('Data null');
},
success: function () {
alert('Success');
}
});
or you could build the data object before the call for simpler reading
var pars = {};
pars["textField1"] = $('#txtField1').val();
you can also do: (if you dynamic vars for example)
var myfield = "myfield2";
pars[myfield] = $('#'+myfield).val();
then:
$.ajax({
type: 'POST',
url: 'http://localhost:9210/xyzmodule/xyzmethod',
data: pars,
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function () {
alert('Data null');
},
success: function () {
alert('Success');
}
});
hope that helps