How to convert simple form submit to ajax call; - javascript

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

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);
}
});

data expects a literal object, so you need:
var data = {
'algorithm': algorithm,
'input': input
};

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 :)

// 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>

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);
}
);

Related

Is my formData to big to be sent through ajax?

I collect data into a JS object:
var elements = {};
$(checked).each(function(i){
elements[i] = {};
elements[i].obj = obj;
elements[i].el = $(this).data('el');
elements[i].height = $(this).data('height');
elements[i].type = $(this).data('type');
elements[i].length = $(this).data('length');
elements[i].width = $(this).data('width');
elements[i].weight = $(this).data('weight');
elements[i].created_by = $(this).data('created_by');
});
Then I'm sending it via an Ajax request:
//SEND TO PHP
$.ajax({
method: "POST",
url: "php/i.php",
data: {elements: elements, obj: obj},
success: function(result){
},
error: function(e){
console.log(e.message);
}
});
This works if the elements obj isn't too big. (I guess).
Is there a limit of size i need to change somewhere?
I have no problem uploading big files like photos etc.
This two dumps represent one Ajax call that works and have data in PHP $_POST,
and one where $_POST returns empty.. i guess it's the size that that makes the difference?!

How to send a serialized array to a php document?

I've got a JavaScript array named seat with many values in it.
As follows,I've serialized to be sent to a php file named confirm.php.
$('btnsubmit').click(function() {
var seat = [];
var seatar = JSON.stringify(seat);
$.ajax({
method: "POST",
url: "confirm.php",
data: seatar
})
})
And this is the code in my php file.
$seatarr = "";
if(isset($_POST['data']))
{
$seatarr = $_POST["data"];
print_r($seatarr);
}
I've tried with my level best, looking at the previous questions asked on this section. But no matter how hard I try to fix it, this code never works. Why not?
You're just sending raw JSON, but you're expecting to get a URI-encoded form with a data field in it. You can get that if you change your ajax call to use data: {data: seatar}:
$('btnsubmit').click(function() {
var seat = [];
var seatar = JSON.stringify(seat);
$.ajax({
method: "POST",
url: "confirm.php",
data: {data: seatar}
})
});
jQuery will automatically turn that object into a URI-encoded submission with a single field in it.
Then use json_decode if you want to parse it on the server:
if(isset($_POST['data']))
{
$seatarr = json_decode($_POST["data"]);
print_r($seatarr);
}
Also, as Mr. Blue pointed out, your button selector is probably incorrect. You have $('btnsubmit') which is looking for a <btnsubmit>...</btnsubmit> element. You probably meant $("#btnsubmit") (if you have id="btnsubmit" on the button) or $("[name=btnsubmit]") (if you have name="btnsubmit" on the button).
Another solution can be to rewrite the data like this:
seatar = $(this).serialize() + "&" + $.param(seatar);
and decode like T.J Crowder did propose:
if(isset($_POST['data']))
{
$seatarr = json_decode($_POST["data"]);
print_r($seatarr);
}

Accessing Ajax Response JSON Data in javascript

I use an AJAX request to get the data from the backend when user select an option from a dropdown menu.
$('#adSpace').change(function () {
var sel_opt = $(this).val();
alert(sel_opt);
var location = null;
var width = null;
var height = null;
$.ajax({
type: "GET",
dataType: 'json',
url: "advertisements-controller.php",
data: {
action: "getDimension",
location: sel_opt
},
success: function (response) {
location = response.banner_location;
alert(location);
},
error: function (xhr) {
alert("error");
}
});
});
Now i'm getting the data from backend in JSON format like below:
[{"banner_location":"category_group_sidebar","banner_width":250,"banner_height":225}]
I want to access the values of banner_location, banner_width, banner_height by assigning those to javascript variables but I'm failing to do it.
Any ideas?
Use this
location = response[0].banner_location;
Your response comes in the form of an array: [...]. That means you can access the first array item by using the index. Also if there are multiple objects you can iterate response with forEach or jQuery's each($(response).each).
response[0].banner_location
response is an array of json. In order to access the json you need to firsr access the index of the array which is done by array[indexNumber] then the key of the json.
In your case it will be response[0].banner_location

How to access the serialized data in PHP file in the following scenario?

How to access the serialized data in a PHP file in following situation?
The code and the serialized data is as follows:
$(document).ready(function() { $(document).on('click', '#delete_url', function (e) {
e.preventDefault();
var items = new Array();
$("input:checked:not(#ckbCheckAll)").each(function() {
items.push($(this).val());
});
var str = $("#user_filter").serialize();
$.ajax({
type: "POST",
url: "manage_users.php?op=delete_bulk_users&items="+items,
data: str,
dataType: 'json',
success: function(data) {
//var message = data.success_message;
var redirect_link = data.href;
alert(redirect_link);
window.location.href = redirect_link;
}
});
});
});
The data I'm getting in after serialize in str is as follows:
op=group_filter&page=1&from_date=11%2F10%2F2000&social_login=&to_date=11%2F10%2F2013&login_criteria=all&user_name=&user_state=&user_email_id=&user_city=
Now the PHP file(manage_users.php) is as follows:
/*The code is actually one of the switch casees*/
prepare_request();
$request = empty( $_GET ) ? $_POST : $_GET ;
$op = $request['op'];
switch( $op ) {
case "delete_bulk_users":
print_r($request);/*For printing the received array of values after form submission
Here I'm not getting serialized data */
}
Thanks in advance.
The serialize function is intended to be used to create a query string for a URL from a collection of inputs (or an entire form), and will out of necessity encode characters such as / (which denotes a directory in a URL). There's no way to tell .serialize() to convert to the "proper" format because it already is.
If you're using the result of .serialize() as part of an AJAX request it's fine to do that like so:
$.ajax({
url: 'yourpage.php',
data: str, // the string returned by calling .serialize()
... // other options go here
}).done(function(response) {
// do something with the response
});
Your server should handle decoding those characters when it receives the request and provide the correct values to you.
If you're using it for something else you could try using the native JavaScript decodeURIComponent function to convert those encoded characters back, like so:
str = decodeURIComponent(str);
Note that calling decodeURIComponent and then trying to use it for an AJAX request won't work.
For more information on URI encoding take a read through the MDN entry for encodeURIComponent.

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