I am trying to perform ajax using webmethod on Asp.net,
And I am using JQuery-3.1.1
I want to pass the value to server and get back the value. I don't know what I did wrong.
Asp.net Code
<div class="row">
<asp:Button ID="btnSave" runat="server" CssClass="btn btn-info" Text="save" />
</div>
Jquery Code
$(document).ready(function () {
$('#btnSave').click(function () {
var name= 'xxx';
$.ajax({
type: "POST",
url: "AjaxWebMethod.aspx/getFileExistOrNot",
data: '{fileName:'+name+'}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert("failed ="+response.d);
},
error: function (response) {
alert("error ="+response.d); //This alert is executing
}
});
function OnSuccess(response) {
alert("Result ="+response.d.mydata);
}
return false;
});
});
C# code
public partial class AjaxWebMethod : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string getFileExistOrNot(string fileName)
{
string mydata="ajaxworking";
return mydata;
}
}
I don't know really where I did my mistake
Error message on console
{Message: "Invalid JSON primitive: xxx.",…}
ExceptionType:"System.ArgumentException"
Message:"Invalid JSON primitive: xxx."
Can you give the solution with proper reason. that will good for me to understand more, thanks
Your postData is invalid JSON, a string needs quotes around it:
'{fileName:'+name+'}'
It should be:
'{fileName:"'+name+'"}'