jQuery.ajax: How do I get the data to send easily? - javascript

I have lots of forms on a project I'm working on.
All the forms pretty much go through AJAX.
$.ajax({
type: "GET",
cache: false,
url: $(this).attr("action"),
data: ???,
success: function(msg){
}
});
I want to be able to intercept these POST's and instead run them through AJAX.
The code is written into a method that will be reused.
So the question is: How can I select all the data that was going to be passed, turn it into a query string and insert it into the data: ???, part.
Thanks

You need to intercept the submit event. Bind an event handler on your <form> elements. When encountered, stop its propagation and its default behavior by returning false from within that event handler.
Now, you can create your .ajax() request in that handler to. To create a serialized form of your form-data into a query-string, use jQuerys .serialize() method on that form aswell.
For instance:
$('#myFormId').on('submit', function( event ) {
$.ajax({
type: "GET",
cache: false,
url: $(this).attr("action"),
data: $(this).serialize(),
success: function(msg){
}
});
return false;
});
Or just create that as delegated event, which handles all of your forms, like
$(document).on('submit', 'form', function( event ) {
});

Use serialize method:
http://api.jquery.com/serialize/

Related

Equivalent code without the library

I used a tutorial to get the following ajax code. In the tutorial, they have the library jquery.form.js. Here is the code:
function onsuccess(response,status){
$("#onsuccessmsg").html(response);
alert(response);
}
$("#uploadform").on('change',function(){
var options={
url : $(this).attr("action"),
success : onsuccess
};
$(this).ajaxSubmit(options);
return false;
});
What if I don't want to have jquery.form.js implemented. What would be the equivalent code with normal ajax (without the library)?
Update
I tried the following code:
$("#uploadform").on('change',function(){
$.ajax({
url: $(this).attr("action"),
context: document.body,
success: function(){
$("#onsuccessmsg").html(response);
alert("asdf");
}
});
return false;
});
and it doesn't do anything now.
It would be something more like: (apologies for the formatting, I'm on my mobile)
$("#uploadform").on('submit',function(e){
e. preventDefault() ;
var formData = new FormData($(this)[0]);
$.ajax({
url: $(this).attr("action"),
context: document.body,
data: formData,
type: "POST",
contentType: false,
processData: false,
success: function(response, status, jqxhr){
$("#onsuccessmsg").html(response);
alert("asdf");
}
});
return false;
});
The data var will need to be built up manually by you by running through the form fields. You may also want to check out jquery post, which is a shorthand way of writing the above.
You can use this previously answered question to get the form data that you need to pass in to the ajax data field:
How can I get form data with Javascript/jQuery?
It's also worth noting that if you are posting a file from your form, your form must have enctype="multipart/form-data".
When submitting your form using ajax you need to set contentType: false, processData: false. See this post for reference.
I have updated the code snippet above to reflect this.
If this has answered your question please mark it as the correct answer.

Using jQuery event on ajax html response

I'm want to use jcarousel on an ajax html response. Here is how i use jcarousel on elements loaded with the DOM.
jQuery(document).ready(function() {
jQuery('#mycarousel-2').jcarousel({ wrap: 'circular' });
});
Now when i use ajax, the above code doesn't work on the returned html. What do i have to do to refire the jcarousel script?
var data = {
action: 'get_thumbnails',
id: id
};
jQuery.post(ajaxurl, data, function(response) {
});
call it inside ajax success callback to initate jcarousel again for dynamically loaded element
jQuery.post(ajaxurl, data, function(response) {
//success callback
jQuery('#mycarousel-2').jcarousel({wrap:'circular'});
});
Might not be the proper approach, but you may use jQuery's event delegation, I think it can be useful, if not in a straight way, then a tricky way :)
Hey buddy i believe that the right code for ajax is this
$.ajax(
{
type: "POST", /// your URL
url: pageurl + "/testajaxfunc1", /// backend function
data: '{"testval":"' + $('#testField').val() + '"}', /// data fields
contentType: "application/json;charset=utf-8", // content type
dataType: "json", // datatype
success: OnSuccessReturnValues, // function that it would initiate on success
error: OnError // function that it would initiate on Error
}
);
hope this help

DOM not updating, jquery selectors not detecting dynamic elements for further processing

I am adding table into my html using ajax call
$.ajax({
url: "/getdata",
type: "POST",
data: {data : jsonString},
success: function( resp ){
//console.log(resp);
$('div.table-responsive').html(resp);
}
});
I am able to get table at right place in broswer view. However when i run in separate script tag
console.log("Tables found"+$('table').length)
i get 0 in output.
How do I update dom after adding elements dynamically so that i can further process them.
I read many answers on this question, everyone is talking about assigning events to these dynamically added elements however I just need to add some classes to some of these tags so my css and javascript can process them.
Your table manipulations should be in the callback :
$.ajax({
url: "/getdata",
type: "POST",
data: {
data: jsonString
},
success: function (resp) {
//console.log(resp);
$('div.table-responsive').html(resp);
console.log('table length: ' + $('.table-responsive table').length);
// Do something with the tables here
}
});
Since this is async, you're gonna need an event or callback. Try something like this:
$('table').contentChange( function(){
// do something
console.log('table length: '+this.length);
});

Accessing DOM object after AJAX call?

I have a typical AJAX call that appends some HTML to the current page. I want to be able to access the newly inserted HTML with typical jQuery selectors.
Here's what I'd like to be able to do...
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
}
});
$('#new_div').show();
#new_div would be some HTML element from the data I retrieved. I don't necessarily want to attach events to the new elements (like click), so using something like .load() or .on() doesn't work here (as far as I know).
I tried setting the $.ajax() call to a variable: var new_div = $.ajax(...) but that didn't get me anywhere.
If you would like to manipulate the new content immediately after (or even before) inserting it to the DOM, you can put that in the AJAX success callback too:
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
$('#new_div').show();
}
});
On the other hand, if you want to bind handlers to content that will be added to the page via ajax, jQuery does that like this:
$(document).on('click', '#new_div', function(){
alert("This function is bound to all #new_div's click events, even if they are added to the DOM via ajax later!")
});
If you want to decouple your code from the callback:
functionWithALotOfStuffToDo = function(data){
// do stuff here
}
$.ajax({
url: url,
success: functionWithALotOfStuffToDo
});
how about:
$.ajax({
url: url,
success: function(data) {
$('body').append(data).find('#new_div').show();
}
});
Assuming the data being returned is something like <div id='new_div' /> then try something such as
var newDiv = null;
$.ajax({
url: url,
success: function(data) {
newDiv = $(data).appendTo($('body'));
}
});
This will add the <div /> to the body of your page, and assign the jQuery element to the variable newDiv which can then be accessed again at a later stage.
However, if you access newDiv before success has been returned, it will be null or the previous value, if it was assigned previously.
Actually this sort of things can be solved by following way:
(I know it is similar to others, but a little bit more clear)
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
afterHtmlAppendCallback();
}
});
function afterHtmlAppendCallback()
{
$('#new_div').show();
}
I think it's ajax async cause the problem you mention.
In jQuery ajax funciton API says:
Perform an asynchronous HTTP (Ajax) request.
If you want to access the data from ajax right after request
you should put you code in the ajax.success function like:
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
$('#new_div').show();
}
});
Or turn the async setting into false
$.ajax({
url: url,
async:false,
success: function(data) {
$('body').append(data);
}
});
$('#new_div').show();
that will make sure the $('#new_div') selector gets the object
I have the same issue and find a method that was great.
If you have the jQuery functions in a file for example library_jquery.js, just load that file again in the success.
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
//LOAD THE SCRIPT FILE AGAIN
var path_script_file="libray_jquery.js";
$.getScript(path_script_file);
}
});

Post form to web2py function using ajax

The server is written in web2py, and hosted on google app engine. I can visit my index.html by entering domain.com/index and I can send form by entering domain.com/register where "register" is a function defined by default.py
However, in html, where I would like to send form to the server and get a response, I use ajax which has cross domain issues. So I use "register" as URL, and it does not work. Help?
$("#signup").click(function() {
$.ajax({
type: "POST",
url: "register",
data: $("#formsignup").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
return false; // avoid to execute the actual submit of the form.
});
By typing domain.com/register, I can totally trigger the function. What is the problem here? And the form is sent to domain.com... In browser it appears as htt[://domain.com/?email=ada#ad.com&password=adsa
Its very possible register is looking for GET instead of POST
try changing the type in ajax
$("#signup").click(function() {
$.ajax({
type: "GET",
url: "register",
data: $("#formsignup").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
return false; // avoid to execute the actual submit of the form.
});

Categories