Add additional data to jQuery wrapped object data in $.ajax call - javascript

I have this working code:
jQuery.ajax({
type: 'post',
url: 'http://www.someurl.com/callback.php',
dataType: 'json',
data: jQuery(':input[name^="option"][type=\'checkbox\']:checked, :input[name^="option"][type=\'text\']'),
complete: function (mydata) {
//do something with it
}
});
That successfully posts back any checked checkboxes and all textboxes. But now I want to add some arbitrary data as well to this. But not sure how to format it. Basically i want to simply add my own name=value pair "test=1" so that on the callback I see it like the others. But no matter what I try, I can't see to get the syntax correct in the format it expects. not sure if I should be adding it inside the jQuery() wrap or outside.. I've tried serializing, encodeURIComponent, basic string "&test=1"
Any ideas?

Your best bet is to build the parameters outside of the AJAX call, like so:
var params = jQuery(':input[name^="option"][type=\'checkbox\']:checked, :input[name^="option"][type=\'text\']');
params.test = 1;
params.test2 = 2;
Then in your AJAX call, simply use:
jQuery.ajax({
type: 'post',
url: 'http://www.someurl.com/callback.php',
dataType: 'json',
data: params,
complete: function (mydata) {
//do something with it
}
});
EDIT: Typically when using jQuery to collect input, I tend to use the .each function, like so:
var params = new Object();
$.each('input[name^=option]', function() {
if ((this.type === 'checkbox' && $(this).is(':checked')) || this.type === 'text' && this.value !== '') {
params[this.name] = this.value;
}
});
Then if you wish to add parameters, you'd do so either after this, or right after creating your new object.

I forgot I asked this previously. It was answered correctly so I'm sharing the link:
How can I pass form data AND my own variables via jQuery Ajax call?

Related

How To Open URL In New Tab Using Ajax Success?

Here i am trying to open the file in new tab by calling ViewFile action of Doctor controller using Ajax Success which is in functionabc(this) on click of anchor tag.
Now the problem is that everything is as required but the url doesnot open in new tab.
Below is my Ajax
<script>
function abc(thisEvent) {
debugger;
var getDoCredId = $(thisEvent).attr('docCredId');
var parameter = { id: getDoCredId };
$.ajax({
url: "/Doctor/ViewFile1",
type: "get",
dataType: "html",
data: parameter,
success: function (data) {
debugger;
if (data = true) {
debugger;
var getdoctorId = $(thisEvent).attr('docCredId');
var url = "/Doctor/ViewFile/" + getdoctorId;
window.open(url, "_blank");
}
else {
debugger;
showNotification("Error", "warning");
}
}
});
}
Below is my anchor tag HTML
<a title="View Attachment" docCredId = "' + getDocCredId + '" onclick="abc(this)"><i class="btn btn-web-tbl btn-warning fa fa-eye "></i></a>
Below is code behind
public bool ViewFile1(int id)
{
var document = _doctorService.GetDoctorCredentialDetails(id);
string AttachPath = ConfigPath.DoctorCredentialsAttachmentPath;
string strFileFullPath = Path.Combine(AttachPath, document.AttachedFile);
string contentType = MimeTypes.GetMimeType(strFileFullPath);
bool checkFileInFolder = System.IO.File.Exists(strFileFullPath);
if (checkFileInFolder == true)
{
return true;
}
else
{
return false;
}
}
public ActionResult ViewFile(int id)
{
var document = _doctorService.GetDoctorCredentialDetails(id);
string AttachPath = ConfigPath.DoctorCredentialsAttachmentPath;
string strFileFullPath = Path.Combine(AttachPath, document.AttachedFile);
string contentType = MimeTypes.GetMimeType(strFileFullPath);
bool checkFileInFolder = System.IO.File.Exists(strFileFullPath);
bool filedata = System.IO.File.ReadAllBytes(strFileFullPath).Any();
byte[] filedata1 = System.IO.File.ReadAllBytes(strFileFullPath);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = document.FileName,
Inline = true
};
Request.HttpContext.Response.Headers.Add("Content-Disposition", cd.ToString());
return File(filedata1, contentType);
}
Since this is too long for a regular comment, I am posting this as an answer, although it isn't directly going solve the problem because I am not able to reproduce it, but might give some insights and let you check the differences with what happens in your code as compared with this simplified example.
Calling window.open() from jQuery ajax success callback works just fine: https://codepen.io/nomaed/pen/dgezRa
I used the same pattern as you did, without your server code but using jsonplaceholder.typicode.com sample API instead.
There are some issues with the code sample that you might want to consider, even though you didn't ask for comments about it and it's not directly related to your issue (probably):
if (data = true) means data will always be true. You probably mean to do a if (data === true) if you know it's a boolean value, or if (data) if you want to accept any truthy value (true, {}, "something", 42, etc). Judging by the Java code and how you define the response format in the jQuery ajax call, it looks like you're expecting the "data" variable result be an HTML and not a boolean. You might want to try and remove the dataType: "html" row and let jQuery set the data format according to what is coming back from the server, and/or send a JSON formatted response, as in a POJO of { result: true } for a successful response. Then make sure that data.result === true to be sure that you got what you expect.
You should probably add arbitrary data to tags DOM elements the data-* attributes and if you're using jQuery, access them using the .data() selector. White adding just random attributs with string values may work, it's considered an abuse of the HTML and DOM, and the data-* attributes are there specifically for adding any data.
In the abc() function you grab the value of the attribute in the beginning (var getDoCredId = $(thisEvent).attr('docCredId');) but in the callback you're trying to get the value once more. You really don't need it since the success() callback is a closure in the scope of the abc() function and it has access to the value already, so doing var getdoctorId = $(thisEvent).attr('docCredId'); in the callback is really not needed.
I'd also suggest naming getDoCredId variable just as docCredId. Having a "get" prefix usually means that it's a getter function or a reference to some getter. Likewise, the "thisEvent" argument of the main function should probably be called "callerElement" or something like that since it's not an event, it's an actual element that you're passing directly from the DOM when calling abc(this) in the onClick event handler of the <a> anchor. This is just to make the code clearer to understand for anyone who's reading it, and for yourself when you're coming back to it several months in the future and trying to figure out what's going on :)
Try adding async: false to your Ajax request
function abc(thisEvent) {
debugger;
var getDoCredId = $(thisEvent).attr('docCredId');
var parameter = { id: getDoCredId };
$.ajax({
async: false, // <<<----------- add this
url: "/Doctor/ViewFile1",
type: "get",
dataType: "html",
data: parameter,
success: function (data) {
debugger;
if (data = true) {
debugger;
var getdoctorId = $(thisEvent).attr('docCredId');
var url = "/Doctor/ViewFile/" + getdoctorId;
window.open(url, "_blank");
}
else {
debugger;
showNotification("Error", "warning");
}
}
});
}

How do I convert this Ajax function (in prototype) to a jquery one?

Can anyone please help me to translate this function in prototype to the equivalent in jQuery
function updateNewsletter(){
if ($('newsletter_dump')){
$('newsletter_dump').remove();
}
newsletterParam = $('newsletter_form').serialize(true);
newsletterParam.template_output = 'box/plugin_newsletter';
new Ajax.Updater('newsletter_form_holder', 'index.php', {
parameters: newsletterParam,
evalScripts: true
});
}
Thanks is advance.
I tried this code but not working. I keep getting an object error
function updateNewsletter(){
if ($('#newsletter_dump')){
$('#newsletter_dump').remove();
}
newsletterParam = $('#newsletter_form').serialize(true);
newsletterParam.template_output = 'box/plugin_newsletter';
$.ajax({
type: 'GET',
url: 'index.php',
data: {"newsletterParam" : "newsletter_form_holder"},
dataType: 'script',
success: function(data){
alert(data);
},
error: function(e){
alert(e);
}
});
}
The problem may come from newsletterParam.template_output = 'box/plugin_newsletter'; Any idea on how to add another form element to the serialised one in jQuery?
Thanks
Unlike Prototype's serialize function, jQuery's serialize function returns a string only. Your error is due to the fact that you are using newsletterParam as an object rather than a string. So to fix the problem just append the template_output parameter as a string:
newsletterParam = $('newsletter_form').serialize();
newsletterParam += '&template_output=box/plugin_newsletter';
Also, the data setting in your ajax call should be
data: newsletterParam,

Change AJAX url with a variable inside success function?

I have an AJAX call that I need to loop over to achieve pagination.
I want to grab a value during each run from the success function, stick it back in the URL that AJAX is pulling and then run the next loop.
How can I change the AJAX url based on something I can find in the success data?
EDIT: Sorry for the lack of example. Here's my function as is now...
for (var i=0; i < 8; i++) {
$.ajax({
'url': 'https://someurl.com?paramone=xxx,
timeout: 8000,
'success': function(data) {
//do something with data
}
I'd like to change paramone's value each time through the loop
Just create a convenient function and call it again
function doAjax(url) {
return $.ajax({
url : url,
type : 'GET',
data : 'something',
dataType : 'json'
});
}
doAjax('mypage1.php').done(function(data) {
doAjax( data.url ).done(function(data2) {
// do something after second ajax call ?
});
});
It's hard to be more specific when the question is so generic, and lacks an example of what you're really trying to do ?

How to set values to array when async webservice responce is called

Friends,
I have declared array in javascipt
var Answer1 = new Array(50);
I want to call webserivce using $ajax & i want to store its response at appropriate index of array.
& want to use that array immediately after all the values are set.
Currently i am doing this by using async:false property of $ajax .
Does anyone know way with asynchrnous way because when i use asynchronous values of array remains undefined.
for(var j=0;j < mycollection.length-1;j++)
{
$.ajax({
type: 'GET',
url: webserviceURL,
dataType: 'json',
error: function(data)
{
//alert(data.error);
},
success: function(data)
{
if(data.error!=null)
{
console.log('data error');
Answer1[j] = data.name;
}
},
complete: function(data)
{
alert('completed:');
},
data: {},
async: false
});
Well you are using the wrong index for Answer1:
Answer1[i] = data.name;
should be:
Answer1[j] = data.name;
But if that still doesn't work, pass j as a parameter to your webservice and get the webservice to return it as part of the response so you know the index to assign to.
Also you are only assigning if data.error is not null? Is that what you want, didn't you want to assign if there is no error (i.e. data.error is null)?
Put whatever code uses the array into a function. Call that function from the success handler for your Ajax call.

howto "submit" a part of a form using jQuery

I'm got a form laid out like a spreadsheet. When the user leaves a row, I want to submit fields from that row to the server using jQuery Ajax. The page is one large form, so this isn't really a javascript clicking the submit button scenario - the form is huge and I only want to send a small portion of the content for reasons of speed.
I've got the code written that identifies the row and iterates through the fields in the row. My issue is how to build the dat object in order to submit something comprehensible I can disassemble and store at the server end.
At the moment my code looks like this
var dat=[];
$("#" + finalrow).find("input").each(function () {
var o = $(this).attr("name");
var v = $(this).val();
dat.push({ o: v });
});
$.ajax({
url: 'UpdateRowAjax',
dataType: 'json',
type: 'POST',
data: dat ,
success: function (data) {
renderAjaxResponse(data);
}
});
The assembling of dat doesn't work at all. So how should I build that dat object in order for it to "look" as much like a form submission as possible.
You can add the elements that contain the data you want to send to a jQuery collection, and then call the serialize method on that object. It will return a parameter string that you can send off to the server.
var params = $("#" + finalrow).find("input").serialize();
$.ajax({
url: 'UpdateRowAjax',
type: 'POST',
data: params ,
success: function (data) {
renderAjaxResponse(data);
}
});
You can use $.param() to serialize a list of elements. For example, in your code:
var dat= $.param($("input", "#finalrow"));
$.ajax({
url: 'UpdateRowAjax',
dataType: 'json',
type: 'POST',
data: dat ,
success: function (data) {
renderAjaxResponse(data);
}
});
Example of $.param(): http://jsfiddle.net/2nsTr/
serialize() maps to this function, so calling it this way should be slightly more efficient.
$.ajax 'data' parameter expects a map of key/value pairs (or a string), rather than an array of objects. Try this:
var dat = {};
$("#" + finalrow).find("input").each(function () {
dat[$(this).attr('name')] = $(this).val();
});

Categories