How to construct the POST data values in an AJAX call? - javascript

i've this piece of code that performs an AJAX call
$.ajax({
url : 'inviaCommento.php',
type : 'POST',
data : {page: page, category: category}
dataType : 'json',
success : function (msg)
//...and so on
The problem is that i want to check if a search parameter is set, if yes i've to add the word to the data parameters.
The question is: can i costruct the data parameters before the call appendig values to it?
Something like this:
if $('#searchBtn').val()!=''
{
data.append(search: $('#searchBtn').val())
}

Yeah, just create an array.
var data = {something: [], page: page, category: category, somekey: "default"};
data.something.push("a");
data.something.push("b");
if (...) {
data.somekey = "new value";
}
$.ajax({
...
data: data
});

Yup, but data isn't a list, it's an object, so you just assign to the appropriate key.
var data = {page:page}; // ... current value of data: param in the $.ajax call
if($('#searchBtn').val()!=='')
{
data.search= $('#searchBtn').val();
}
You'd put this above the $.ajax() call.

Related

Ajax Data Call with or without slash in Codeigniter getting error

suppose my URL is example.com/controller/method/
when I use this ajax code it makes URL like example.com/controller/method/method which not getting data.
function getProductList() {
var category = document.getElementById('Category').value;
$.ajax({
type: 'POST',
url: 'GetProductList',
data: {CategoryId: category},
dataType: 'json',
cache:false,
success: function (response) {
}
});
}
but when my URL is example.com/controller/method then ajax getting data correctly. but i want to get data from the database on both situations.
Typically there is a one-to-one relationship between a URL string and its corresponding controller class/method. So you can not use example.com/controller/method/method.The segments in a URI normally follow this pattern: example.com/class/function/id/ , So your last method argument treated as a id. so create method in controller with the default argument Ex. public function mymethod($method = ''){ /** Your logic goes here */ }

Can Mockjax handle single IDs Api from Json file

I'm using Mockjax for the first time to mock a Restful API which will return a series of data given an id. Right now i have a json file that has several Items, and i would like to have a function inside Mockjax (or where necessary) to return only the queried ID. how can I achieve this?
current code :
$.mockjax({
url: "/Api/Cases/{caseId}",
proxy: "/mocks/cases nuevo.json",
dataType: 'json',
responseTime: [500, 800]
});
$.ajax({
type: 'GET',
url: '/Api/Cases/',
data: {caseId: taskId},
success: function(data){
//use the returned
console.log(data);
}
});
current error:
GET http://localhost:8080/Api/Cases/?caseId=100 404 (Not Found)
Great question... yes, you can do this. But you'll have to write the functionality yourself using the response callback function and then making a "real" Ajax request for the file (instead of using the proxy option). Below I just make another $.ajax() call and since I have no mock handler setup for that endpoint, Mockjax lets it go through.
Note that setting up URL params is a little different than you suggest, here is what the mock setup looks like:
$.mockjax({
url: /\/Api\/Cases\/(\d+)/, // notice the regex here to allow for any ID
urlParams: ['caseID'], // This defines the first matching group as "caseID"
responseTime: [500, 800],
response: function(settings, mockDone) {
// hold onto the mock response object
var respObj = this;
// get the mock data file
$.ajax({
url: 'mocks/test-data.json',
success: function(data) {
respObj.status = 200;
// We can now use "caseID" off of the mock settings.urlParams object
respObj.responseText = data[settings.urlParams.caseID];
mockDone();
},
error: function() {
respObj.status = 500;
respObj.responseText = 'Error retrieving mock data';
mockDone();
}
});
}
});
There is one other problem with your code however, your Ajax call does not add the ID to the URL, it adds it to the query string. If you want to use that API endpoint you'll need to change your source code $.ajax() call as well. Here is the new Ajax call:
$.ajax({
type: 'GET',
url: '/Api/Cases/' + taskId, // this will add the ID to the URL
// data: {caseId: taskId}, // this adds the data to the query string
success: function(data){
//use the returned
console.log(data);
}
});
Note that this presumes the mock data is something like:
{
"13": { "name": "Jordan", "level": 21, "id": 13 },
"27": { "name": "Random Guy", "level": 20, "id": 27 }
}
What I have ended up doing, is: I have left the $.mockjax function untouched, and i have manipulated the data inside the ajax request, using jquery's $.grep function as follows:
$.ajax({
type: 'GET',
url: '/Api/Cases/' + taskId,
success: function(data){
//note you have to parse the data as it is received as string
data = JSON.parse(data);
var result = $.grep(data, function(e){ return e.caseId == taskId; });
//since i'm expecting only one result, i pull out the result on the 0 index position
requestedData = result[0];
}
});
The $.grep() method removes items from an array as necessary so that all remaining items pass a provided test see Jquery API, And since our test is that the caseId attribute of the element equals to the taksId variable sent, it will return all the elements that match the given Id, in this case, only one, this is why I've taken only the result on the 0 index position requestedData = result[0];
**Note: **
A more suited solution would be a mixture between what i've done and #jakerella 's answer, since their method implements the find element method inside the mockjacx function, and my function presumes a usual JSON response:
[{"caseId": 30,"name": "Michael"},{"caseId": 31,"name": "Sara"}]

.serialize() an array of variables in Javascript

I have a list of variables available to me and I want to send it via $.ajax post. What format would I have to keep these in to use the function .serialize? I keep getting this error:
Object 'blank' has no method 'serialize'
I've tried to make them an array and I've tried jQuery.param(). I have a feeling this is simple but I can't seem to get it. Thanks!
var $data = jQuery.makeArray(attachmentId = attachmentID, action = 'rename', oldName = filename, newName, bucketName, oldFolderName, newFolderName, projectId = PID, businessId = BID);
var serializedData = $data.serializeArray();
//alert(theurl);
$.ajax({ type: "post", url: theurl, data: serializedData, dataType: 'json', success: reCreateTree });
.serialize is for form elements:
Encode a set of form elements as a string for submission.
The $.ajax documentation says for the data option:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
So all you need to do is passing an object. For example:
$.ajax({
type: "post",
url: theurl,
data: { // <-- just pass an object
attachmentId: attachmentID,
action: 'rename',
// ...
},
dataType: 'json',
success: reCreateTree
});
It seems you're used to the PHP style of array's (associated arrays). In Javascript, objects are basically the same thing (though can be MUCH more complicated).
So if you are trying to create an array like this in php it would be
$array = array(
"foo" => "bar",
"bar" => "foo",
);
in Javascript using an object instead of an array it would be
var arr = {
foo: "bar",
bar: "foo"
}

convert objects to JSON and send via jquery ajax

I've 1 object:
var myobject = {first: 1, second: {test: 90}, third: [10, 20]};
and I want to send it as JSON string via jQuery ajax.
How can I do it? (i test JSON.stringify(), but it doesn't work in IE)
Thanks.
If you specify your myobject as the data parameter to the jQuery .ajax() method, it will automatically convert it to a query string, which I believe is what you want.
e.g.
$.ajax({
url: /* ... */,
data: myobject,
/* other settings/callbacks */
})
From the docs:
data
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs.
You should be able to pass your object to the 'data' parameter of the ajax function -
$.ajax({
type: "POST",
url: "some.php",
data: myobject ,
success: function(msg){
alert( "Data Saved: " + msg );
}
});

Jquery post to Action with Dictionary Parameter

I am feeling dejavu, but I cannot find the answer to this:
I have an array of objects that needs to look like this when inspecting a jQ $.post call:
limiter[0].Key
limiter[0].Value
so that it is mapped in the action
public ActionResult SomeAction(Dictionary<Guid, string> dictionary) { }
However, this javascript:
// Some Guid and Some Value
var param = [ { 'Key' : '00000000-0000-00000-000000', 'Value': 'someValue' } ];
$.post('/SomeController/SomeAction/',
{
dictionary: limiter,
otherPostData: data
},
function(data) {
callback(data);
}
)
produces this when inspecting it in firebug:
limiter[0][Key] = someKey // Guid Value
limiter[0][Value] = someValue
This is in jq 1.4.2. I seem to remember some flag you need to set to render json a different way in jQ. Does this ring any bells?
Try like this:
var param = {
'[0].Key': '28fff84a-76ad-4bf6-bc6d-aea4a30869b1',
'[0].Value': 'someValue 1',
'[1].Key': 'd29fdac3-5879-439d-80a8-10fe4bb97b18',
'[1].Value': 'someValue 2',
'otherPostData': 'some other data'
};
$.ajax({
url: '/Home/SomeAction/',
type: 'POST',
data: param,
success: function (data) {
alert(data);
}
});
should map to the following controller action:
public ActionResult SomeAction(Dictionary<Guid, string> dictionary, string otherPostData)
{
...
}
var dict = {}
dict["key1"] = 1
dict["key2"] = 2
dict["key3"] = 3
$.ajax({
type: "POST",
url: "/File/Import",
data: dict,
dataType: "json"
});
public void Import(Dictionary<string, int?> dict)
{
}
just send your obj as dataType: "json"
You can use this flag -
jQuery.ajaxSetting.traditional = true;
To get jQuery to post the data in a different format to the one you are seeing. See this question for further info -
Passing arrays in ajax call using jQuery 1.4
You will see the post param as limiter[0][Key] because jquery serializes the json data before it posts it. This is very well interpreted by the controller action and you get the required input in the action.
You can also use a list of objects and the result will be the same as what you wanted. This is a nice example.
http://www.mikesdotnetting.com/Article/96/Handling-JSON-Arrays-returned-from-ASP.NET-Web-Services-with-jQuery

Categories

Resources