How to solve Invalid JSON Primitive error on Ajax? - javascript

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+'"}'

The jQuery call that you are making is set up to expect JSON format in the response. It would appear that your server side code is simply returning a string which is not encoded as JSON. You either need to change the output from the server or change what is expected from the ajax invocation.

Related

Post Ajax call says Get not allowed

I'm trying to use ajax with post method but it keep poping me this error
An attempt was made to call the method \u0027SendEmail\u0027 using a GET request, which is not allowed
Here is the js
var obj = { name: name, company: company, country: country, email: email, msg: Msg }
var json = JSON.stringify(obj);
$.ajax({
method: "POST",
url: "ContactUs.aspx/SendEmail",
contentType: "application/json; charset=UTF-8",
data: json,
dataType:"json",
success: function (data) {
var a = 3;
},
error:function(a,b){
var a = 43;
}
})
and here is the server side on c#
[WebMethod]
public static void SendEmail(string name, string company, string country, string email, string msg)
{
}
Thanks in advance!
You should follow this way:
Your backend method which you already decorated with [WebMethod] and added a reference of using System.Web.Services;, I've changed the method to return something so it can be verified whether it works or not.
[WebMethod]
public static String sendEmail(string param)
{
return "Your String";
}
within your .aspx page, add scriptManager for enabling client side calling to your code behind methods
<asp:ScriptManager ID="scriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
Finally within your JQuery script, call the method like this:
$(document).ready(function () {
PageMethods.sendEmail("", onSuccess);
function onSuccess(response)
{
alert(response);
}});
Hope it helps!
Try to use [HttpPost] instead of [WebMethod] and remove static.
Is it a REST API or MVC?

How to make Rest Spring work with JS

Folks
I have a problem with consuming a rest using javascript.
This Rest is already being used in other applications, where PHP and Aspx conserve the same described below.
#Controller
#RequestMapping("/userlogin")
public class UserRest {
#Autowired
private UserService userService;
#RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.OK)
public ResponseEntity<RetornUser> login(#RequestBody User user) {
RetornUser retornUser = new RetornUser();
try {
user = userService.autenticarUsuario(user);
retornUser.setUsuario(usuario);
retornUser.setCodigoRetorno(1);
} catch (Exception e) {
retornUser.setCodigoRetorno(-1);
retornUser.setMensagem(e.getMessage());
}
return new ResponseEntity<>(retornUser, HttpStatus.OK);
}
}
The code above works perfectly with PHP, Aspx and Java calls.
When I call the routine, the JS is falling into the error function before receiving the return.
The worst thing is that the JS error is not bringing the reason. Below the code in pure HTML.
function logar() {
try {
var json = JSON.stringify(usuario);
json = "{\"nome\": \"garra\",\"senha\": \"1234\"}";
$.ajax({
type: "POST",
url: "http://localhost:8080/garrasystem/webservice/userlogin/login",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 300000, // sets timeout to 3 seconds
success: function (retorno) {
alert(retorno);
},
error: function (data, textStatus, xhr) {
alert(data.responseText);
}
});
} catch (e) {
console.log(e);
}
}
The way it is there, when I send debug, it calls the normal login method, but it falls into the error function, nor does it expect the login method to perform the return.
I put the method return String only and nothing too.
My Spring is 4.
I'm waiting for some help
Vinicius Castro
Looks like you are passing string instead of json object. Could you try passing the following:
var data = {
nome: "garra",
senha: "1234"
};
Folks
Being focused on a single problem, I forgot to analyze the button type. It was like type submit, so it was not working. It is like experiencing these kind of mistakes.
Thank you to all who supported me

jquery ajax doesn't fire

I am trying to call a server-side function using Jquery ajax, it doesn't work, I get no error. what can be the problem ? is there a set of rules to make sure my $ajax will work?
//HTML
<asp:DropDownList ID="DDL" runat="server">
<asp:ListItem>aaa</asp:ListItem>
<asp:ListItem>bbb</asp:ListItem>
</asp:DropDownList>
//JS
$(document).ready(function () {
$("#DDL").change(function () {
$.ajax({
type: "POST",
url: "signToCity.aspx/getStreets",
contentType: "application/json; charset=utf-8"
});
});
});
//Serverside
[WebMethod]
public static void getStreets()
{
string test="no return:just checking by breakpoint if function is working."
}
Here are the detail of rules to make a AJAX Call : See Here in detail
$.ajax({
url: 'http://api.joind.in/v2.1/talks/10889',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
dataType: 'jsonp',
success: function(data) {
var $title = $('<h1>').text(data.talks[0].talk_title);
var $description = $('<p>').text(data.talks[0].talk_description);
$('#info')
.append($title)
.append($description);
},
type: 'GET'
});
Change your server side code to the following: (change void to string and return value)
c#
[WebMethod]
public static string getStreets()
{
return "no return:just checking by breakpoint if function is working.";
}
jQuery: (add handlers for ajax response)
$.ajax({
type: "POST",
url: "signToCity.aspx/getStreets",
contentType: "application/json; charset=utf-8",
success: function (response) {
console.log(response.d);
},
error: function (response) {
console.log('error ' + JSON.stringify(response));
}
});
Are you setting the clientidmode to static for your web control somewhere? If not, ASP.NET renders it with an entirely different id
You labeled the follwing as HTML:
<asp:DropDownList ID="DDL" runat="server">
<asp:ListItem>aaa</asp:ListItem>
<asp:ListItem>bbb</asp:ListItem>
</asp:DropDownList>
but it is not HTML, it is your aspx page that will be processed and output html. Look at the page source and see the actual HTML that is rendered. You will notice your dropdown list is a select element with an id something like ctl00$ContentPlaceHolder1$Page$#DDL
Your jQuery cant find$("#DDL") because it doesnt exist.
Option 1:
If your javascript is directly on the .aspx page and not external, you can use the following to print the generated client id to your page
...$("#<%=DDL.ClientID%>").change(function () {
$.ajax({...
Option 2:
Your other option is to set the ClientIDMode of your DropDownList to static, so it doesn't change when the page is rendered
<asp:DropDownList ID="DDL" runat="server" ClientIDMode="static">
<asp:ListItem>aaa</asp:ListItem>
<asp:ListItem>bbb</asp:ListItem>
</asp:DropDownList>
Could your url be the problem?
signToCity.aspx/getStreets doesn't look right. Perhaps it's supposed to be signToCity/getStreets.aspx?
Or even just signToCity/getStreets?

Call c# function with javascript code

I would like to call a code behind function from the client side.
The function cannot be static - should modified unstatic variabels.
I was able to create a non-visible button, and when I need that function I demonstrate a click on that btn.
How can I send parameters to that code behind function?
$.ajax({
url: '/ControllerName/ActionName',
type: "GET",
data: { param1: val1 },
success: function (res) {
alert(res) // res is results that came from function
}
});
This is the client side to call backend method. The server side to accept this request:
public ActionResult ActionName(string param1)
{
return View(param1);
}
In this case, we used jQuery, the javascript plugin, and we used AJAX request, also sending parameters.
Using MVC and jQuery
Client Side ( Using Razor )
$.ajax({
url: '#Url.Action("ActionName","ControllerName",new{parameters})',
type: "GET",
contentType: "application/json",
data: { param1: val1 },
success: function (res) {
alert(res) // res is results that came from function
},
error: function (jqXHR, error, errorThrown) {
console.log('An error as occured');
},
});
Server Side
[HttpGet]
public JsonResult ActionName(string param1)
{
return Json(param1, JsonRequestBehavior.AllowGet);
}
Note: HttpGet Verb is the default verb for every ActionResult/JsonResult
the button have a CommandArgument attribute that you can use to send a value to that function and you can read it as follow :
public void yourFunction(object sender,Eventargs e)
{
string args = ((LinkButton)sender).CommandArgument.ToString();
// rest of code here
}

How to send Json Data from Aspx page

I tried to use TokenInput Jquery for multiple value autocomplete where it requires the JSON response as input data
http://loopj.com/jquery-tokeninput/
I am using ASPX page as source
<script type="text/javascript" >
$(document).ready(function() {
$("#txtTest").tokenInput("Complete.aspx", {
theme: "facebook"
});
});
</script>
Edited From Here
Question: How to provide the JSON data from a aspx page in the desired format as i have datatable with values according to Querystring from Complete.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request.QueryString["q"]))
{
string json = "[{\"Id\":\"1\",\"name\": \"Test 1\"},{\"Id\":\"2\",\"name\": \"Test 2\"}]";
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();
}
}
Any help will be appreciated.
Alternative to the WCF, you can create WebMethod in .aspx.
[WebMethod]
public static string Info()
{
JavaScriptSerializer js = new JavaScriptSerializer();
string result = js.Serialize(new string[] { "one", "two", "three" });
return result;
}
and request this WebMethod via Ajax call.
<script type="text/javascript">
$(function () {
$("#button1").click(function () {
$.ajax({
url: "Default.aspx/Info",
data: "{}",
contentType: "application/json",
success: function (data) {
alert(data.d);
},
type: "post",
dataType : "json"
});
});
});
</script>
EDIT:
Code-behind - Page_Load handler (JsonPage.aspx)
string json = "[{\"name\":\"Pratik\"},{\"name\": \"Parth\"}]";
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();
and request the JsonPage.aspx via TokenInput jQuery. (Sample.aspx & JsonPage.aspx are in same folder)
<script type="text/javascript">
$(function () {
$("#txt1").tokenInput("JsonPage.aspx");
});
</script>
<body>
<input type="text" id="txt1"/>
</body>
You should take a look at WCF. WCF has native support for returning JSON and you don't have to worry about string concatenation or HTTP content types.

Categories