If I have a webservice that needs several querystring parameters in order to query the underlying DB, should I place them in the URL or can I place them into a variable which is then passed to the data parameter of the $.ajax request? Part of my question is simply - What exactly does the data parameter represent?
In the snippet below, targetURL is successfully passed in as the URL. However, when I try and passing 'parameters' as the data parameter(data: parameters), the call fails.
function JSONTest() {
//var targetURL = "http://localhost:49633/compass/compatability/webservices/SearchDatabase.ashx?mode=contact&searchvalue=" + encodeURI(document.getElementById("jsonInput").value) + "&format=json";
var targetURL = "http://localhost:49633/compass/compatability/webservices/SearchDatabase.ashx";
var parameters = "mode=contact&searchvalue=da&format=json";
document.getElementById("targetURL1").innerText = targetURL;
document.getElementById("ResultTable").innerHTML = "";
$.ajax({
type: "POST", //rest Type
url: targetURL,
data: parameters,
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (jqXHR, textStatus) {
jsonResponse = $.parseJSON(jqXHR.responseText);
for (i = 0; i < jsonResponse.length; i++) {
if (i % 2 == 0) {
createTableRow(i, "tableRow");
} else {
createTableRow(i, "tableRowAlternating");
}
}
document.getElementById("ReturnTest2").style.display = "block";
}
});
};
If you want json sent as your contentType implies then you need to change your data from urlencoded string to json by starting with an object then stringifying that object
var data = {
mode: 'contact',
searchvalue: 'da',
format: 'json'
}
var parameters = JSON.stringify(data);
If you are expecting standard form encoded data at server then remove:
contentType: "application/json; charset=utf-8",
Also never ever use async: false, it is deprecated and has always been a terrible practice
Related
In my controller I have a method that gets triggered by an AJAX call. I have a list of strings that I want to return
List<string> Usernames = new List<string>();
Then when data is loaded into Usernames I convert it into JSON
var JsonResults = Json(Usernames);
finally I return that JSON as below
return Json(new { success = true, resultsList =JsonResults });
In JavaScript, How can I loop through that array resultsList? Here is what the JS code looks like -
$.ajax({
url: "#Url.Action("StartNewChat")",
data: { SearchedText: searchedText },
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.success == true) {
// READ THROUGH result.resultsList
}
}
});
I tried JSON.parse() and result.resultsList[0] and converting result.resultsList into string and back to JSON it didn't work.
Edit:
When I do a console.log(result.resultsList) here is what I get which is pretty strange
{"contentType":null,"serializerSettings":null,"statusCode":null,"value":["a","aa","aaa"]}
the last array is the result from Username array in c#
I'm not familiar with the Json method you are using, but from version 3.1 .Net Core has its own json serializer JsonSerializer (in System.Text.Json namespace) and I'm going to use that one in my answer.
As of your issue, you are serializing twice and it might not give you the resultsList in your final result as an array of string which you might be expecting.
Your first conversion will result in an array of strings -
["alice","bob","charlie"]
But your second conversion, depending on the serializer used, might put the entire array above inside a string and give that as the value of resultsList in your final result.
You should serialize once, the final object only -
// you need to import the following
// using System.Text.Json;
List<string> userNames = new List<string>();
names.Add("alice");
names.Add("bob");
names.Add("charlie");
return JsonSerializer.Serialize(new { success = true, resultsList = userNames });
It will give you resultsList as an array of strings -
{"success":true,"resultsList":["alice","bob","charlie"]}
Then you can loop through that array on the client end like -
result.resultsList.forEach(p=> console.log(p))
The response has already a JSON so no need to parse anything.
It will be something like this:
$.ajax({
url: "#Url.Action("StartNewChat")",
data: { SearchedText: searchedText},
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.success == true)
{
result.resultsList.forEach( el => {
console.log(el)
})
}
}
});
});
```
sometimes you have to parse the json response first try this. straight after the success line
let result = JSON.parse(result);
Then
if (result.success == true)
{
result.resultsList.forEach( el => {
console.log(el)
})
}
You can try this using by through the resultlist length.
$.ajax({
url: "#Url.Action("StartNewChat")",
data: { SearchedText: searchedText},
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.success == true)
{
for (var i = 0; i <result.resultsList.length; i++) {
console.log(result.resultsList[i]);
}
}
}
});
I want to pass the variable from view to controller I am using ajax call to achieve it i am getting the error below. I don't know what i am missing here.
WARN 41440 --- [nio-8080-exec-9] o.s.web.servlet.PageNotFound : Request method 'POST' not supported
This is my code
document.getElementById('btntest').onclick = function(){
var selchbox = getSelectedChbox(this.form); // gets the array returned by getSelectedChbox()
myvalue = JSON.stringify(selchbox);
//document.write("check check"+selchbox);
$.ajax({
type: "POST",
url: "UserController/delete",
contentType: "application/json; charset=utf-8",
data: {key:myvalue},
cache: false,
success: function (data) {
alert("Are you sure?");
},
error: function (args) {
alert("Error on ajax post");
}
});
alert(selchbox);
}
My controller method looks like below
#RequestMapping(value = "/delete", method = RequestMethod.POST)
public String delete(#RequestBody String key) {
System.out.println("My Array value"+key.toString());
return key;
}
What i am missing here? Any Help
Finally i could able to pass the values from my view to controller I am posting the code.
This is my js code
document.getElementById('btntest').onclick = function(){
var selchbox = getSelectedChbox(this.form); // gets the array returned by getSelectedChbox()
var myvalue = JSON.stringify(selchbox);
//document.write("check check"+selchbox);
$.ajax({
type: "POST",
url: "/delete",
dataType : "JSON",
contentType:"application/json; charset=utf-8",
data: JSON.stringify(selchbox),
cache: false,
success: function (data) {
alert("Are you sure?");
},
error: function (args) {
alert("Error on ajax post");
}
});
alert(selchbox);
}
And my controller code
#RequestMapping(value = "/delete", method = RequestMethod.POST)
public String delete(#RequestBody String value){
System.out.println("My Array value"+value.toString());
return value;
}
First, if you want to delete, why not use the verb delete http?
I think you are not using the correct parameter: RequestParam is used to map your sORGID parameter to the URL (a parameter you did not use on the client side, you must use it or delete it).
If you want to map Json, you must use #RequestBody.
I hope it helps
At leaset two problems
url: "UserController/delete" in your ajax won't match "/delete/{sORGID}" in your controller.
data: {key:myvalue} in your ajax, the property name is key, in your controller it's myvalue[], this should also be the same.
// something defined deleteArr and pass values to it
var postData = { deleteArr: deleteArr };
if(deleteArr.length > 0)
{
$.ajax({
url: "#Url.Action("Delete", "ASZ01")",
type: "POST",
data: postData,
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("success.");
},
error: function (response) {
alert(deleteArr[0]);
}
});
deleteArr.length = 0;
}
The above code is javascript.
Until $.ajax begin I can confirm that values in array is correct in immediate window,but when it comes to error: I got "undefined".
And the following is my function in controller
public void Delete(List<string> deleteArr)
{
service.Delete(deleteArr);
}
The second question is that I set breakpoint on that function but it can't stop.
I think maybe my ajax form is wrong?
Stringify to JSON, add the dataType: 'json' and then pass and also correct your ""
var postData = JSON.stringify({ deleteArr: deleteArr });
if(deleteArr.length > 0)
{
$.ajax({
url: #Url.Action("Delete", "ASZ01"),
type: "POST",
data: postData,
dataType: 'json'
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("success.");
},
error: function (response) {
alert(deleteArr[0]);
}
});
deleteArr.length = 0;
}
Small change to your postData
var postData = { deleteArr: JSON.stringify(deleteArr) };
Idea is to convert your array data into string format ie:JSON and posting to the server, The default Model binder of MVC framework will handle the part to convert them into List<string> for you
I have a dropdown that has a list of ID's in it. The customer will select one and it will reflect a price total on the page. Im creating an ajax call that will update the total when a different ID is pulled from the Dropdown.
$("#BrandId").on('focus', function () {
// Store the current value on focus and on change
previous = this.value;
}).change(function () {
alert("Previous: " +previous);
sel = this.value;
alert("Selected: " +sel);
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetBrandCost", "Shocks")',
data: JSON.stringify({ idp: previous, id: sel }),
dataType: "json",
aysnc: false,
success: function (data1) {
alert(data1);
//ShockTotal = $("#ShockTotal").html();
//ShockTotal = ShockTotal / 1;
////ShockTotal = ShockTotal - data1;
//$("#ShockTotal").html(data1);
}
});
});
The alerts are working perfectly but the ajax isnt passing those ID's into the controller, the controller is just receiving nulls.
public decimal GetBrandCost(string idp, string id)
{
decimal costp = 0;
decimal cost = 0;
if (id == "" || id == null || idp == "" || idp == null)
{
return 0;
}
ShockBrand brandp = db.ShockBrands.Find(idp);
costp = brandp.Cost;
ShockBrand brand = db.ShockBrands.Find(id);
cost = brand.Cost;
cost = cost - costp;
return cost;
}
Since they are null I am hitting my if statement and just returning zero inside the success. Most of the things I read were to add the content type but that didnt seem to help in my case, Im sure it is something little.
From browser console, this
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: 'http://google.com',
data: JSON.stringify({ idp: 1, id: 2 }),
dataType: "json",
aysnc: false,
success: function (data1) {
console.log(data1)
}
});
returns request to http://google.com/?{%22idp%22:1,%22id%22:2}&_=1440696352799, which is incorrect
and without stringify
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: 'http://google.com',
data: { idp: 1, id: 2 },
dataType: "json",
aysnc: false,
success: function (data1) {
console.log(data1)
}
});
returns http://google.com/?idp=1&id=2&_=1440696381239 (see Network tab)
So don't use JSON.stringify
Why it's gonna work - your asp.net controller action receives simple typed parameters (string, numbers, etc) and jquery is fairly enought smart to determine what are going to send, if it was object inside object it will send it as POST data for POST, and string represenation of object for GET (you have GET request, but for purpose of knowledge, just stick with 2 types of data that can be send, params & data) So when jquery configures url, asp.net understands conventions, and matches request to approciated action
But Don't believe me, check it yourself
chrome dev console is your friend
By removing the
contentType: "application/json; charset=utf-8
and
dataType: "json"
it worked for me. Otherwise, I was always getting value = null in the controller action.
My code for calling ajax with data is now:
$(function () {
$.noConflict();
$.ajax({
type: "POST",
url: "../Case/AjaxMethodForUpdate",
data: {typ: $('#typeID').val()},
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
You can just put it like
var dataReq={ idp: previous, id: sel };
data: dataReq
And no need to use dataType and contentType.
Basically I am trying to extract JSON returned from servlet in JavaScript. I have tested my servlet class already and it did returned some JSON so I guess I no need to post the code for that class. Here is my returned JSON format:
[{"mrtpopAmt":"7000","mrtpopX":"17854.99820","mrtpopY":"35056.35003"},{"mrtpopAmt":"6300","mrtpopX":"29798.58427","mrtpopY":"37036.56434"}]
And in my JavaScript, I am trying to extract mrtpopAmt, mrtpopX and mrtpopY as one object. Then I will add all object into an array:
function getAllMRTPop(time){
var jsonArray;
var Data = JSON.stringify({ time: time });
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time="+ Data + "",
type: "GET",
data: Data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var parsed = JSON.parse(data.d);
console.log(data.d);
$.each(parsed, function (i, jsondata) {
var jsonObject;
jsonObject.put("mrtpopAmt", jsondata.mrtpopAmt);
jsonObject.put("mrtstationX", jsondata.mrtstationX);
jsonObject.put("mrtstationY", jsondata.mrtstationY);
alert(jsonObject);
jsonArray.push(jsonObject);
});;
},
error: function (request, state, errors) {
}
});
}
However, I am getting error message like Unexpected token: u at this line:
var parsed = JSON.parse(data.d);
My URL for the servlet contains two parameter, one is action and the other one is time:
http://localhost:8080/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time=8:00
So I wonder am I passing the parameter correctly by passing it in url and as well as data from the code above?
I wonder which part went wrong? Thanks in advance.
EDIT
So I have updated my JavaScript part to this:
function getAllMRTPop(time){
var jsonArray = [];
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time=8:00",
type: "GET",
data: time,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
//var parsed = JSON.parse(data.d);
$.each(data, function (i, jsondata) {
var jsonObject;
console.log(mrtpopAmt);
jsonObject.put("mrtpopAmt", jsondata.mrtpopAmt);
jsonObject.put("mrtstationX", jsondata.mrtstationX);
jsonObject.put("mrtstationY", jsondata.mrtstationY);
jsonArray.push(jsonObject);
});;
},
error: function (request, state, errors) {
}
});
}
I tried to print out the mrtpopAmt and it did returned something. But there is an error message:
Cannot call method 'put' of undefined
Any ideas?
By specifying dataType: "json", jQuery already knows you will be getting a JSON response, there is no no need to do var parsed = JSON.parse(data.d)
Just do:
var parsed = data.d
Edit:
function getAllMRTPop(time){
var jsonArray = [];
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time=8:00",
type: "GET",
data: time,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
$.each(data, function (i, jsondata) {
var jsonObject = {};
jsonObject.mrtpopAmt = jsondata.mrtpopAmt;
jsonObject.mrtstationX = jsondata.mrtstationX;
jsonObject.mrtstationY = jsondata.mrtstationY;
jsonArray.push(jsonObject);
});;
},
error: function (request, state, errors) {
}
});
}
I think what is happening is that data.d is undefined, so you are getting the odd message about unexpected u.
Try this instead:
var parsed = JSON.parse(data);
Edit And I think you are probably not formatting your request right:
var Data = JSON.stringify({ time: time });
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time="+ Data + "",
Seems to me that would make the final bit: &time={"time":"time"}, so you probably want to look at how you construct Data. Maybe just pass time directly?
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time="+ time + "",