Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ajax - When to use $.ajax(), $('#myForm').ajaxForm, or $('#myForm').submit

Tags:

ajax

Given so much different options to submit sth to the server, I feel a little confused.

Can someone help me to clear the idea when I should use which and why?

1> $.ajax()
2> $('#myForm').ajaxForm
3> ajaxSubmit
4> $('#myForm').submit

Thank you

like image 932
q0987 Avatar asked Aug 12 '10 16:08

q0987


People also ask

When should we use AJAX?

Ajax should be used anywhere in a web application where small amounts of information could be saved or retrieved from the server without posting back the entire pages. A good example of this is data validation on save actions.

What is the use of AJAX () method?

The ajax() method is used to perform an AJAX (asynchronous HTTP) request. All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.

Which method is prefer to use in AJAX?

The $. ajax() method is particularly valuable because it offers the ability to specify both success and failure callbacks. Also, its ability to take a configuration object that can be defined separately makes it easier to write reusable code.

Why is it important to use AJAX for requests?

The purpose of AJAX is to increase the performance, speed, and usability of web applications. So, the AJAX technique reduces the server traffic inside requests and lowers the time consumption on both side's responses. One of the most significant advantages of AJAX is it allows users to make asynchronous calls.


1 Answers

I personally prefer creating a function such as submitForm(url,data) that way it can be reused.

Javascript:

function submitForm(t_url,t_data) {
$.ajax({
  type: 'POST',
  url: t_url,
  data: t_data,
  success: function(data) {
    $('#responseArea').html(data);
  }
});
}

HTML:

<form action='javascript: submitForm("whatever.php",$("#whatevervalue").val());' method='POST'> etc etc

edit try this then:

$('#yourForm').submit(function() {
    var yourValues = {};
    $.each($('#yourForm').serializeArray(), function(i, field) {
        yourValues[field.name] = field.value;
    });
    submitForm('whatever.php',yourvalues);
});
like image 143
Robert Avatar answered Sep 27 '22 16:09

Robert