13

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

veer7
  • 20,074
  • 9
  • 46
  • 74
  • First of all use the jQuery serialize http://api.jquery.com/serialize/ to convert your form data to "text string in standard URL-encoded notation" – Arash Milani Jun 18 '12 at 12:10
  • Do you recieve some js erros? – Anton L Jun 18 '12 at 12:10
  • And can you post the javascript error or the console log here? – Arash Milani Jun 18 '12 at 12:11
  • @ArashMilani: yes I have to use that I'll try. – veer7 Jun 18 '12 at 12:14
  • @veer7 Please use the jQuery serialize and update your question :) – Arash Milani Jun 18 '12 at 12:15
  • @ArashMilani : the error message is Webpage error details User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; MS-RTC LM 8; .NET CLR 4.0.20506) Timestamp: Mon, 18 Jun 2012 12:19:08 UTC Message: Expected '}' Line: 75 Char: 6 Code: 0 URI: file:///E:/DineshDocs/FromNilesh/dinesh/menu1.html Message: Object expected Line: 105 Char: 1 Code: 0 URI: file:///E:/DineshDocs/FromNilesh/dinesh/menu1.html – veer7 Jun 18 '12 at 12:21
  • Shouldn't your line:74 be like this: `success: function(tableData) {` – Arash Milani Jun 18 '12 at 12:28
  • I have posted the complete code as an answer. take a look @veer7 – Arash Milani Jun 18 '12 at 12:37

5 Answers5

15

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);
    }
});
Arash Milani
  • 6,149
  • 2
  • 41
  • 47
5

data expects a literal object, so you need:

var data = {
    'algorithm': algorithm,
    'input': input
};
Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
  • The current version of jQuery ([documentation for `ajax()`](http://api.jquery.com/jQuery.ajax/), as of Jun '15) allows the value of the `data` parameter to be a string, and is in fact converted to a URL-safe string if it isn't. – sameers Jun 15 '15 at 23:45
3

Instead of retrieving all the parameter value and then sending them separately (which can be done server side as well, using below code), Use this:

var $form = $("#divId").closest('form');
    data = $form.serializeArray();

    jqxhr = $.post("SERVLET_URL', data )
        .success(function() {
            if(jqxhr.responseText != ""){
                //on response
            }
        });
    }

divId is id of the div containing this form.

This code will send all the form parameters to your servlet. Now you can use request.getParameter in your servlet to get all the individual fields value on your servlet.

You can easily convert above jquery post to jquery ajax.

Hope this helps :)

Ankit
  • 3,083
  • 7
  • 35
  • 59
1

I don't know how but this one runs well,

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

    $.post('run.do', {  
            algorithm  : algorithm,
            input      : input
        }, function(data) {                  
            alert(data);
        }
    );
Michael McGuire
  • 1,034
  • 9
  • 20
veer7
  • 20,074
  • 9
  • 46
  • 74
1

// patching FORM - the style of data handling on server can remain untouched
$("#my-form").on("submit", function(evt) {
 var data = {};
 var $form = $(evt.target);
 var arr = $form.serializeArray(); // an array of all form items
 for (var i=0; i<arr.length; i++) { // transforming the array to object
  data[arr[i].name] = arr[i].value;
 }
 data.return_type = "json"; // optional identifier - you can handle it on server and respond with JSON instead of HTML output
 $.ajax({
  url: $form.attr('action') || document.URL, // server script from form action attribute or document URL (if action is empty or not specified)
  type: $form.attr('method') || 'get', // method by form method or GET if not specified
  dataType: 'json', // we expect JSON in response
  data: data // object with all form items
 }).done(function(respond) {
  console.log("data handled on server - response:", respond);
  // your code (after saving)

 }).fail(function(){
  alert("Server connection failed!");
 });
 
 return false; // suppress default submit action
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
kobliha
  • 27
  • 4