How can I make ajax parameters dynamic? - javascript

Here is a part of my code:
if ( external_link ) {
data = {external_link : external_link};
} else {
data = form_data;
}
$.ajax({
url: base_url + frm.attr('action'),
type: frm.attr('method'),
data: data,
cache: false,
contentType: false, // this
processData: false, // and this should be removed when external_link isn't false
success: function (imageUpload) {
All I'm trying to do is making contentType: false and processData: false parameters dynamic. I mean, if the condition above was true, then those two mentioned parameters should be removed. How can I do that?

var ajaxParams = {
url: base_url + frm.attr('action'),
data: data
// contentType not here
};
if (something) {
ajaxParams.contentType = false; // add new parameter
}
$.ajax(ajaxParams);

What about defining the minimum set of options first, and add the other two if the condition is met?
var options = {
url: base_url + frm.attr('action'),
type: frm.attr('method'),
data: data,
cache: false,
success: function (imageUpload) {
...
};
if ( external_link ) { // the external link entered
options.contentType: false; // this
options.processData: false; // and this should be removed when external_link isn't false
options.data = {external_link : external_link};
} else {
options.data = form_data;
}
$.ajax(options);

Pass an object into ajax call instead creating a literal object there? Preferably by wrapping a function around the call.
Code below is not direct implementation but showcase of principle:
var makeAjaxAndExecute = function(param1, param2){
var ajaxObjectInitiate = {object literal here}
ajaxObjectInitiate.param1 = param1;
ajaxObjectInitiate.param2 = param2;
$.ajax(ajaxObjectInitiate //.... rest of your code
}
You can further separate configuring the object and actually making the call, you can have general generator of requests elsewhere totally depends what are your needs and how complex do you wanna / need it to be.
If you need to do it on a lot of calls, I would opt for totally isolated builder that holds onto object and has getters and setters for options and possibly internal states and logic. And once object is set simple pass it to ajax call.
Scale-able, maintainable and easy to debug but not needed if you have simple logic as this.

Related

jQuery .ajax() - add query parameters to POST request?

To add query parameters to a url using jQuery AJAX, you do this:
$.ajax({
url: 'www.some.url',
method: 'GET',
data: {
param1: 'val1'
}
)}
Which results in a url like www.some.url?param1=val1
How do I do the same when the method is POST? When that is the case, data no longer gets appended as query parameters - it instead makes up the body of the request.
I know that I could manually append the params to the url manually before the ajax request, but I just have this nagging feeling that I'm missing some obvious way to do this that is shorter than the ~5 lines I'll need to execute before the ajax call.
jQuery.param() allows you to serialize the properties of an object as a query string, which you could append to the URL yourself:
$.ajax({
url: 'http://www.example.com?' + $.param({ paramInQuery: 1 }),
method: 'POST',
data: {
paramInBody: 2
}
});
Thank you #Ates Goral for the jQuery.ajaxPrefilter() tip. My problem was I could not change the url because it was bound to kendoGrid and the backend web API didn't support kendoGrid's server paging options (i.e. page, pageSize, skip and take). Furthermore, the backend paging options had to be query parameters of a different name. So had to put a property in data to trigger the prefiltering.
var grid = $('#grid').kendoGrid({
// options here...
dataSource: {
transport: {
read: {
url: url,
contentType: 'application/json',
dataType: 'json',
type: httpRequestType,
beforeSend: authentication.beforeSend,
data: function(data) {
// added preFilterMe property
if (httpRequestType === 'POST') {
return {
preFilterMe: true,
parameters: parameters,
page: data.page,
itemsPerPage: data.pageSize,
};
}
return {
page: data.page,
itemsPerPage: data.pageSize,
};
},
},
},
},
});
As you can see, the transport.read options are the same options for jQuery.ajax(). And in the prefiltering bit:
$.ajaxPrefilter(function(options, originalOptions, xhr) {
// only mess with POST request as GET requests automatically
// put the data as query parameters
if (originalOptions.type === 'POST' && originalOptions.data.preFilterMe) {
options.url = options.url + '?page=' + originalOptions.data.page
+ '&itemsPerPage=' + originalOptions.data.itemsPerPage;
if (originalOptions.data.parameters.length > 0) {
options.data = JSON.stringify(originalOptions.data.parameters);
}
}
});

How can I ajax only html table rows instead of sending the entire form inputs?

I have tried to ajax using post to jsp script my html table rows for weeks now with no success.Can anyone please guide me on this?Below is what I have done so far.
window.addEventListener("DOMContentLoaded", function () {
var form = document.getElementById("updateDealPmtForm");
document.getElementById("btn").addEventListener("click", function () {
$('#notSoCoolGrid > tr').each(function(event) {
event.preventDefault();
var postData = {
paymentId:$('#paymentId').text(),
id:$('#deald').text(),
pType:$('#pType').text(),
pAmt:$('#pAmt').text(),
currency:$('#currency').text(),
pInvDate:$('#pInvDate').text(),
pRecDate:$('#pRecDate').text(),
comments:$('#comments').text()
};
console.log(postData);
$.ajax({
async: false,
type: "POST",
cache: false,
url: "/update_deal_pmt_script.jsp",
data: postData.$('input, select').serialize() ,
success: function(msg){
alert("submitted");
}
});
});
});
If I correctly understand your need, you want to transmit the content of your rows, each in the form showed in your current postData.
So this can be made at once for all rows (instead of ajaxing successively each of them).
It might be something like this:
window.addEventListener("DOMContentLoaded", function () {
var form = document.getElementById("updateDealPmtForm");
document.getElementById("btn").addEventListener("click", function () {
event.preventDefault();
var postData = [];
$('#notSoCoolGrid > tr').each(function(event) {
postData.push(
paymentId:$('#paymentId').text(),
id:$('#deald').text(),
pType:$('#pType').text(),
pAmt:$('#pAmt').text(),
currency:$('#currency').text(),
pInvDate:$('#pInvDate').text(),
pRecDate:$('#pRecDate').text(),
comments:$('#comments').text()
);
});
console.log(postData);
$.ajax({
async: false,
type: "POST",
cache: false,
url: "/update_deal_pmt_script.jsp",
data: postData,
success: function(msg){
alert("submitted");
}
});
});
});
Note that I choosed (the simplest way, IMO) to make a simple array of rows, where each one is an object like you already structured them.
Last point: I notice you specified async: false.
I don't know why you did that, and so I kept it unchanged.
But note that it's not recommended, and is being on the road to become deprecated.
I finally was able to solve this issue,for that I want to post my answer it might be helpful for someone out there.My previous code was submitting a form before even ajax call being triggered and I have to use Classes instead of IDs to identify my rows.I had to change the code completely to be able to submit the form
$('#btn').click(function(e) {
e.preventDefault();
$('#notSoCoolGrid tr').each(function(i, tr) {
var postData = {
paymentId : $('.paymentId', tr).val(),
id : $('.deald', tr).val(),
pType:$('.pType', tr).val(),
pAmt:$('.pAmt',tr).val(),
currency:$('.currency',tr).val(),
pInvDate:$('.pInvDate',tr).val(),
pRecDate:$('.pRecDate',tr).val(),
comments:$('.comments',tr).val()
}
$.ajax({
async: false,
type: "post",
url: "/update_deal_pmt_script.jsp",
data: postData
})
.done(function(response) {
console.log(response);
})
.fail(function(x, status, error) {
alert("Error: " + error);
});
});
});

JQuery prototyping functions

I am trying to create a prototype of the ajax object.
I have created these functions:
$.extend({
ajax_prototype : function(parammeters){
instance = this;
instance.cache = false;
instance.crossDomain = false;
instance.dataType = 'json';
instance.timeout = 30000;
instance.error = default_error_function;
$.each(parammeters,function(key,value){
instance[key] = value;
});
},
set_ajax_action : function(template,action,func,def){
template[action] = func;
}
});
ajax_prototype
Is a constructor for the object.
Sets some default settings and some defined based on every need.
set_ajax_action
Sets the function to be executed on each event.
When I create an object like this:
temp1 = new $.ajax_prototype({
'type' : 'post',
'url' : 'controller.php',
});
I get this object:
Object { cache: false, crossDomain: false, dataType: "json", timeout: 30000, error: default_error_function(), type: "post", url: "controller.php", success: function () }
But after I use this:
$.set_ajax_action(temp1,'error',function(){console.log();});
The object becomes like this:
Object { cache: false, crossDomain: false, dataType: "json", timeout: 30000, error: function (), type: "post", url: "controller.php", success: function () }
Basicly their difference is the way error function is set.
Both objects work prety good.
But I would like to make the prototype to create the object with the second form.
Can someone explain me why the difference on the two objects and how to resolve my problem?
Edit 1
I can also create the second object even if I remove the error property from my prototype and call $.set_ajax_action(...) .
My problem is why there is difference to the functions presentation to console.
I know my question is trivial and that either way the result would be the same, but I wan to know how it works.
By the way, even if I set the error property like this:
instance.error = function(){ ... };
The result will be:
Object { cache: false, ifModified: false, processData: true, crossDomain: false, dataType: "json", timeout: 30000, error: .ajax_prototype/instance.error(), url: "test" }
Console is able to trace if a function can be identified somehow. For example, if it has a name or it is assigned to variable, console will show its/variable's name. If it's created inside a function, console will show it. Example:
(function testt(){
$.set_ajax_action(temp1,'error',function(){console.log();});
})()
console.log(temp1)
this code will produce error: testt/<() (firefox).
You can hide name of function, not giving your default handler a name. For example, like this:
(function(default_error_function){
$.extend({
ajax_prototype : function(parammeters){
instance = this;
...
instance.error=default_error_function
...
},
set_ajax_action : ...
});
})(function() {/* default error handler */})
Here, scope of default_error_function symbol is not global, therefore console does not show it. At the same time, handler was created outside any other function, so console only has function () to show.

Pass object from javascript to Perl dancer framework

I have following ajax code to pass values to dancer framework.
BookSave: function(data) {
### data is an object that contain more than one key value pair
var book = Book.code;
$.ajax ({
type: "GET",
url : 'textbook/save/' + book + '/' + data,
success: function(data) {
if(data.status == 1) {
alert("success");
} else {
alert("fail");
}
},
});
},
In dancer:
any [ 'ajax', 'get' ] => '/save/:book/:data' => sub {
set serializer => 'JSON';
my $book = params->{book};
my $data = params->{data}; ## This I am getting as object object instead of hash
};
Is there any way to pass object from js and getting as hash in dancer?
First and foremost, consider using the http PUT or POST verbs, and not GET. Not only is doing so more semantically correct, it allows you to include more complex objects in the http body, such as your 'data' hash (serialized, per my comments below).
I've had limited success with Dancer's native AJAXy methods, plus there is a bug that causes problems in some versions of Firefox. So instead, I serialize and then deserialize the JSON object.
Suggested changes (note I suggested changes to your routes as well):
$.ajax ({
type: "PUT",
url : '/textbook/' + book,
data: {
myhash : JSON.stringify(data)
},
dataType: 'json',
contentType: 'application/json',
success: function (response) {
if (response.status == 1) {
alert("success")
} else {
alert("fail")
}
}
})
and your Perl Dancer code changes as follows:
any [ 'ajax', 'put' ] => '/textbook/:book' => sub {
set serializer => 'JSON';
my $book = param('book');
my $data = from_json(param('myhash'));
};
I did not go as far as testing this code, but it should at least give you a good starting point to finish solving this problem.
Good luck with your project!

.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"
}

Categories

Resources