Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert simple form submit to ajax call;

I have a form with input field which can be accessed like

var algorithm = document.forms["algoForm"]["algorithm"].value;
var input = document.forms["algoForm"]["input"].value;

and earlier call was

document.forms["algoForm"].submit();

and form was

<form name="algoForm" method="post" action="run.do">

It all run fine
Now I wanted convert it to the ajax call so that I can use the returned data from java code on the same page. So I used soemthing like

        var algorithm = document.forms["algoForm"]["algorithm"].value;
        var input = document.forms["algoForm"]["input"].value;
        var data = 'algorithm = ' + algorithm + '&input = ' + input;


    $.ajax(
            {
                url: "run.do",
                type: "POST",
                data: data,
                success: onSuccess(tableData) 
                { //line 75
                    alert(tableData);
                }

            }
        );

However the above code doesn't run. Please help me make it run

like image 755
veer7 Avatar asked Jun 18 '12 12:06

veer7


People also ask

Can we submit form using AJAX?

We can submit a form by ajax using submit button and by mentioning the values of the following parameters. type: It is used to specify the type of request. url: It is used to specify the URL to send the request to. data: It is used to specify data to be sent to the server.

What is the difference between AJAX and form submit?

A standard form submit sends a new HTTP request (POST or GET) and loads the new page in the browser. In Ajax, the data is sent to the server (POST or GET) in the background, without affecting the page at all, and the response is then received by javascript in the background, again without affecting the page at all.

What is AJAX form submission?

AJAX form submitting allows you to send data in the background, eliminating the need to reload websites to see the updates. This makes the user experience much smoother.


1 Answers

Let's use jQuery's serialize to get the data out of the form and then use the jQuery's ajax function to send the data to the server:

var data = $("form[name=algoForm]").serialize();
$.ajax({
    url: "run.do",
    type: "POST",
    data: data,
    success: function(tableData){
        alert(tableData);
    }
});
like image 149
Arash Milani Avatar answered Oct 02 '22 15:10

Arash Milani