How to pass query string parameter to ajax call from data - javascript

I'm using ajax call for hit the API & i want to send an query parameter, How can i send query parameter with ajax call. Here is my code. Any help on this will be appreciated, Thanks.
$("[id*=btnok]").click(function (e) {
e.preventDefault();
var obj = {};
obj = $.trim($("[id*=nodays]").val());
$.ajax({
url: "/apilink",
"data": {
"api": "api",
"params": "?userType=driver&type=true&count=" + obj
},
type: "post",
dataType: "json",
success: function (r) {
console.log(r)
}
});
});

As you're sending a POST request any properties in the data object will be added to the body of the request. To force a value to be sent in the querystring you need to manually append it to the string you provide to the url property.
Also note that defining obj as an empty object is redundant as $.trim() always returns a string.
$("[id*=btnok]").click(function (e) {
e.preventDefault();
var obj = $.trim($("[id*=nodays]").val());
$.ajax({
url: "/apilink?params=" + obj,
data: {
api: "api",
},
type: "post",
dataType: "json",
success: function (r) {
console.log(r)
}
});
});

As I see you make a post request so parameters are passed in params property in request body. But as an option you can add string params to your /apilink. Like that: /apilink?param1=val1&param2=val2

Related

How do I pass an Array string data as parameter for Swagger API using a variable?

$("#nonjstest").click(function() {
$.ajax({
url:"https://petstore.swagger.io/v2/pet/findByStatus?status=sold",
type: "GET",
contentType:"application/json",
success: function(data){
alert(data[0].id)
}
})
})
Here, I am passing the required parameters directly in the URL status=sold.
I want to pass them via a variable instead, but it's not working. I've tried the following:
var requiredata = ["status=sold"]
$("#nonjstest").click(function() {
$.ajax({
url:"https://petstore.swagger.io/v2/pet/findByStatus",
type: "GET",
data: requiredata,
contentType:"application/json",
success: function(data){
alert(data[0].id)
}
})
})
The request itself is successful, but nothing is returned, meaning, the parameters are not passed correctly. What is the problem with the way I'm passing the Array string?
I've tried stringifying the data, but it didn't work either.
Why is it not working? How do I pass the array string data with a variable?
Try sending the params as an object instead of as an array:
var requiredata = {
status: 'sold'
};
$("#nonjstest").click(function() {
$.ajax({
url:"https://petstore.swagger.io/v2/pet/findByStatus",
type: "GET",
data: requiredata,
contentType:"application/json",
success: function(data){
alert(data[0].id)
}
})
});
Another option would be to pass the params as a string but it's worse because you have to pass it already encoded.
Check the docs for more information.

Passing a complex model to controller using AJAX in ASP.NET Core MVC

I'm trying to pass the model from the view to controller using AJAX, the AJAX call works with a hard-coded JSON string but fails with the actual JSON and I don't know why, any help is very appreciated. Step by step this is what I did:
In the view I have
<script>
var FeedData = #Html.Raw(Json.Serialize(Model));
</script>
In My JavaScript file
var index= $(this).val();
var test = window.FeedData[index];
var json = {
prop1: 'test',
prop2: 'test2',
};
var data = {
json: JSON.stringify(json)
};
var data2 = {
json: JSON.stringify(test)
};
$.ajax({
type: 'GET',
dataType: 'json',
url: "/Feed/GetFeedDetails",
data: data,
success: function (json) {
if (json) {
alert('ok');
} else {
alert('failed');
}
},
});
Ok, Both data and data2 variables are JSON stringified..
data: data, // Works
data: data2,//this does not work
My Controller
public async Task<PartialViewResult> GetFeedDetails(string json)
{
Feed feedData = JsonConvert.DeserializeObject<Feed>(json);
return PartialView("FeedDetailsModal", feedData );
}
Any help is much appreciated.
the AJAX call works with a hard-coded JSON string but fails with the actual JSON and I don't know why
In your code, we can find that you set Ajax request method to 'GET', so the data would be passed through query string, if you can not get expected data in action method, please use browser developer tools Network tool to capture request and check if well-formatted data is passed.
Besides, your action method accepts string-type parameter and manually convert to a Feed object, to achieve same, you can try to make action method accept Feed type parameter and make it automatically bind value to properties of model class via model binding feature.
public IActionResult GetFeedDetails([FromBody]Feed feed)
{
//...
Pass complex data through request body instead of in query string, like below.
var data2 = window.FeedData[index];
$.ajax({
type: 'Post',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: "/Feed/GetFeedDetails",
data: JSON.stringify(data2),
success: function (json) {
if (json) {
alert('ok');
} else {
alert('failed');
}
},
});
Test Result

I am Unable to Parse a JSON in JQuery

I have My jquery function that is returning me data of the formatt:
{"Suggestions":[{"name":"RR Restaurant","category_id":"166","locality":"Gayathri Nagar","listing_info":"listing","random_id":"1ll0f0wJ"},{"name":"Oko Restaurant","category_id":"166","locality":"Kumara Krupa","listing_info":"listing","random_id":"0F7ZGV9p"},{"name":"H2O Restaurant","category_id":"166","locality":"Maratha Halli","listing_info":"listing","random_id":"0JNPOyuP"},{"name":"Taj Restaurant","category_id":"166","locality":"Shivaji Nagar","listing_info":"listing","random_id":"7GeA0Kfq"},{"name":"PSR Restaurant","category_id":"166","locality":"Peenya Industrial Area","listing_info":"listing","random_id":"cRvJCwQ3"},{"name":"ac restaurant","category_id":"166","listing_info":"keyword"},{"name":"Indian Restaurant","category_id":"166","listing_info":"keyword"},{"name":"goan restaurant","category_id":"166","listing_info":"keyword"},{"name":"thai restaurant","category_id":"166","listing_info":"keyword"},{"name":"andhra restaurant","category_id":"166","listing_info":"keyword"}],"ImpressionID":"test"}
I wish to parse the same to get multiple variables with The field "Name" and "Random Id" in different js variables
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
My JSON object seems to be nested with "Suggestions" as the parent. Please help.
If you add a property to $.ajax function you be ensure that is json parsing:
dataType: 'json'
EDIT
To iterate above the string you can use for(in) or each() jquery
json = "[{'key':'value'},{'key':'value']";
for(var i in json) {
console.log(json[i]);
//if you see in console [OBJECT Object] you are
//in a new object you must to iterate nested of this.
}
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
dataType: "JSON", //You need this to be inserted in your ajax call.
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
After insert dataType you can probably do this.
console.log(data.Suggestions);
Also take a look at the API Doc at below url regardless of dataType.
http://api.jquery.com/jquery.ajax/
The data object you are specifying is what will be sent as the arguments to your success method, if you use the GET method.
$("#what).on("keypress", function() {
$.get("/AutoComplete.do", function(response) {
var data = JSON.parse(response);
//data.suggestions = [lots of objects];
//data.suggestions[0].locality = "Gayathri Nagar"
});
});

jquery ajax data object with multiple values for the same key

I would like to make an ajax call, and in the data object I need to have several values in the same key.
var data = {
foo: "bar",
foo: "baz"
}
$.ajax({
url: http://example.com/APIlocation,
data: data,
success: function (results) { console.log(results) },
dataType: 'json'
});
The intention is to get a URL that looks something like:
http://example.com/APIlocation?foo=bar&foo=baz
I tried structuring the data like this:
var data = {
foo: ["bar","baz"]
}
Which unsurprisingly, did not work because it encodes the url like this:
http://example.com/APILocation?foo%5B%5D=bar&foo%5B%5D=baz
I tried the solution here, but could not make it work.
You can use jQuery's $.param to convert an array to a parameter string that contains the same key multiple times. Set the second argument to true so it doesn't get url-encoded, and then just pass that string to the data property in the AJAX call:
var data = $.param({ foo: ['bar', 'baz'] }, true);
// data is now 'foo=bar&foo=baz'
$.ajax({
url: 'http://example.com/APIlocation',
data: data, // Will handle the string correctly.
success: function (results) { console.log(results) },
dataType: 'json'
});
Or, with an object, you can set the traditional property to true:
var data = {
foo: ["bar","baz"]
};
$.ajax({
url: 'http://example.com/APIlocation',
data: data,
success: function (results) { console.log(results) },
dataType: 'json',
traditional: true
});

Accessing ajax POST response in javascript

I'm making ajax POST request from javascript function:
function UpdateMetrics() {
$.ajax({
type: "POST",
url: "MyHandler.ashx?Param1=value1",
data: "{}",
contentType: "text/json; charset=utf-8",
dataType: "text",
success: function (msg) {
var jsonUpdatedData = msg;
...
}
});
}
From my handler, I'm sending json string with:
context.Response.write(json);
I think I'll get it in msg.
I also want to send other string (count). So I'm trying to use header info along with json data. So I added this line:
context.Response.Headers.Add("MaxCount",Convert.ToString(tempList.Count));
If this is right way to do it, how can I access it in my success function?
To access headers in your success function, add in 2 more arguments to your function, the status code and the jqXHR object, which you can read the documentation for at api.jquery.com.
So, your function should look like:
success: function (msg, status, jqXHR) {
var jsonUpdatedData = msg;
...
}
However, as pointed out in comments, it's probably best not to use the header to send data. You should probably just include it in the json you send out.
You also need to tell jQuery to interpret the response as json by setting
dataType: "json"
Otherwise, it will just be returned to you as text.
Your requirement to get the header data in ajax post success can be achieved using getResponseHeader method please refer the below code snippet.
function UpdateMetrics() {
var callback = $.ajax({
type: "POST",
url: "MyHandler.ashx?Param1=value1",
data: "{}",
contentType: "text/json; charset=utf-8",
dataType: "text",
success: function (msg) {
var jsonUpdatedData = msg;
var headerdata = callback.getResponseHeader("MaxCount");
// Where MaxCount is name provided in the header.
...
}
});
}
Thanks

Categories

Resources