InvalidJSONprimitive:ABC Ajax call in Asp.net - c#

my script
<script type ="text/javascript">
$(document).ready(function () {
$('#<%=Button1.ClientID %>').click(function () {
var ABC = 'TEST';
$.ajax({
type: "POST",
url: "Default.aspx/ServerSideMethod" ,
data: "{ EmailAddress : ABC }",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
alert(msg);
$('#myDiv').text(msg.d);
}
})
return false;
});
});
</script>
Code behind method
[WebMethod]
public static string ServerSideMethod(string EmailAddress)
{
return EmailAddress ;
}
<asp:Button ID="Button1" runat="server" Text="Click" />
<br /><br />
<div id="myDiv"></div>
at button click it give me InvalidJSONprimitive:ABC this error can any body tell what i m doing wron.

As the error clearly states, the JSON that you're sending to the server is invalid.
String literals in JSON must be quoted.
You should call JSON.stringify({ EmailAddress: ABC }) to build a JSON string from a Javascript object expression.

Related

How to pass array HTML elements to AJAX POST to C# controller

I have this form in HTML.
<input type="text" id="myID">
<input type="text" id="myName[]">
<input type="text" id="myName[]">
myID field is used once while myName field is used multiple time in form. How can I pass the value of myName to AJAX? I am doing the following but it only works for myID and not myName
document.getElementById('myForm').onsubmit = function ()
{
var model = new FormData();
model.append("myID", $('#myID').val());
model.append("myName", $('#myName').val());
$.ajax({
url: "/MyController/MyMethod",
type: "POST",
data: model,
contentType: false,
processData: false,
success: function (response) {
Do_Something_Here;
},
error: function (xhr, error, thrown) {
alert(xhr.responseText);
}
});
}

Why is ajax call to webmethod returning 401 from code behind?

ajax
function verify() {
$.ajax({
type: "POST",
url: "Register.aspx/verifyImage",
data: '{text: "' + $("#<%=TextBox4.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response.d)
},
failure: function(response) {
alert(response.d);
}
});
}
C# webmethod
[WebMethod]
public void verifyImage(string text)
{
string imageString = Session["imageString"].ToString();
if (imageString.Equals(text))
{
Response.Write("<script>alert('Memeber Page');</script>");
}
else
{
Response.Write("<script>alert('Incorrect');</script>");
}
}
Page controls
<div style="height: 50px">
<asp:Image ID="Image1" runat="server" />
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
<input id="Button1" type="button" value="Submit" onclick="verify()"/>
</div>
Debug Output
"name":"POST /Register.aspx/verifyImage","duration":"00:00:00.0161020","success":true,"responseCode":"401","url":"http://localhost:54506/Register.aspx/verifyImage","properties":{"DeveloperMode":"true","_MS.ProcessedByMetricExtractors":"(Name:'Requests', Ver:'1.0')
I'm new to ajax and am building an image verifier page. I want to compare the image text to asp textbox text using ajax to send the textbox text to a web method in the code behind. In the output, the ajax call writes success: true, but returns a 401 (unauthorized) code. What am I doing wrong? At this point I'm just trying to get the call to work and will fill in the webmethod more later.

Can't send a basic, non MVC form using ajax in .Net (C#)

I have seen answers to this question many times, but most of them are related to MVC controllers.
The issue I am having while trying to send a form using Ajax is that while in debug mode, the execution flow won't reach the break point I have in my code behind. Also, I notice that when I click in the submit button, the page refreshes very quickly; I though that the whole idea of ajax was to not refresh the page.
This is my index.aspx
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="ajaxform.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<fieldset class="fs1">
<input id="inputData" tabindex="1" name="theinputData" class="field" placeholder="Paste URL, docId or docSetId" runat="server"/>
<input id="form1Send" type="submit" class="button" onclick="submit()"/>
</fieldset>
</div>
</form>
</body>
Here is the code of my ajaxform.js
$(document).ready(function () {
$('#form1').submit(function (e) {
var formData = new FormData(this);
$.ajax({
url: 'index.aspx/OnSubmit',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: formData,
contentType: false,
processData: false,
success: function (result) {
alert("We returned: " + result);
},
error: function (result) {
alert("Error");
}
});
e.preventDefault();
});
});
Finally, here is my code behind
namespace mySpace
{
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string OnSubmit()
{
return "I was in code behind";
}
}
}
My break point is on the return line. Why the program never reach the WebMethod?
There are a couple of issues with your code:
You're double declaring something to handle the form. Your form1send button has onclick="submit()" in it as well as the form submit handler you're wiring up via jQuery
The content of your JavaScript handler is slightly off, for example you set contentType twice.
Here's a simplified version of the JavaScript that works on my machine:
$(document).ready(function () {
$('#form1').submit(function (e) {
$.ajax({
type: "POST",
url: "index.aspx/OnSubmit",
contentType: "application/json; charset=utf-8",
data: '{}',
dataType: "json",
success: function (response) {
alert(response.d);
},
failure: function (response) {
}
});
e.preventDefault();
});
});
NOTE: I based this (the content of the $.ajax call) on a code sample I found elsewhere, which is why the parameters and order of the parameters are different to yours.
If your app has a RouteConfig.cs file present, you may also need to change settings.AutoRedirectMode = RedirectMode.Permanent; to settings.AutoRedirectMode = RedirectMode.Off; if you see an HTTP 401 error in your browsers developer tools console for the request to your WebMethod decorated method in index.aspx.
By executing event.preventDefault() before FormData(this) a premature refresh is prevented.
See below:
$(document).ready(function () {
$('#form1').submit(function (event) {
event.preventDefault();
var formData = new FormData(this);
$.ajax({
url: 'index.aspx/OnSubmit',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: formData,
contentType: false,
processData: false,
success: function (result) {
alert("We returned: " + result);
},
error: function (result) {
alert("Error");
}
});
});
});

Autocomplete JQuery is not working

Merged with jQueryUI Autocomplete Plugin not working.
I am NEW in JQ stuff. So basically I have a simple textbox in which I want user to search some items. I am using JQ for this. I read this link which implements this example:
http://aspnetnova.blogspot.com/2009/06/simple-jquery-ajax-server-side.html
Here is my code:
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<style type="text/css">
.login
{}
</style>
<script type ="text/javascript">
var data = "";
$(document).ready(function () {
$("#tbSearch").click(function () {
$.ajax({
type: "POST",
url: "AgentList.aspx/LoadData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
data = msg.d.split(" ");
$('#<%= tbSearch.ClientID %>').autocomplete(data);
}
});
});
});
</script>
</asp:Content>
<asp:TextBox ID="tbSearch" runat="server" ontextchanged="tbSearch_TextChanged"></asp:TextBox>
Here is my code behind:
#region "Auto Complete"
[System.Web.Services.WebMethod]
public static string LoadData()
{
return "S M SMI SM A ABC ABCD ABCI";
}
#endregion
What I am doing wrong here?

Ajax method call

I am trying to call a simple method in my code behind using Jquery with Ajax. But I get a 404 not found exception everytime. Unfortunately this is a web forms solution. So I dont have all the perks of MVC :(
It does get into the javascript method and gives the alert but won't go into my c# method. My previous experience of using this Jquery method is in an MVC website. Is it compatible with webforms sites?
My Javascript is:
$(document).ready(function() {
$('#btn_<%=UserStuff.tag %>').click(function() {
var value = $('#<%#Eval("tag") %>twink').val();
something(value);
});
});
function something(theval) {
alert(theval);
$.ajax({
type: "POST",
url: "/Default.aspx/MyMethod?something=" + theval,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
}
});
}
}
And my C# code is:
public JsonResult MyMethod(string something)
{
JsonResult ret = new JsonResult();
return ret;
}
Thanks in advance.
Your method returns JsonResult. This is MVC specific and you cannot use it in a webforms application.
If you want to call methods in the code behind in a classic WebForms application you could use PageMethods:
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
And then to call the method:
$.ajax({
type: 'POST',
url: 'PageName.aspx/GetDate',
data: '{ }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
// Do something interesting here.
}
});
And here's a full working example I wrote for you:
<%# Page Language="C#" %>
<%# Import Namespace="System.Web.Services" %>
<script type="text/C#" runat="server">
[WebMethod]
public static string SayHello(string name)
{
return "Hello " + name;
}
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="/scripts/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: 'POST',
url: 'default.aspx/sayhello',
data: JSON.stringify({ name: 'John' }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
// Notice that msg.d is used to retrieve the result object
alert(msg.d);
}
});
});
</script>
</head>
<body>
<form id="Form1" runat="server">
</form>
</body>
</html>
PageMethods are not limited to simple argument types. You could use any type as input and output, it will be automatically JSON serialized.

Categories

Resources