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();
});
Related
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);
}
I try to pass many values to Action in MVC but, user is always null.
var form = $('form');
$.ajax({
type: "POST",
url: '#Url.Content("~/User/UpdateUser")',
data: { user: form.serialize(), NameOfCare: care },
success: function (result) {
if (result == "Ok") {
document.location.href = '#Url.Content("~/User/Index")';
}
}
});
how to pass form with many values in Ajax ?
First of all, you have to use #Url.Action instead #Url.Content because you have to send your form data to a controller in order to process data.
.serialize method encode a set of form elements as a string for submission.
You should use this: data:form.serialize() + "&NameOfCare="+care.
On server-side your method should looks like this:
public ActionResult(UserViewModel user,string NameOfCare){
}
user object will be filled with your data , using Model Binding
you are sending a serialized object while it's actually a string. try below example. The action will de-serialize the string automatically.
function load() {
var dataT = $("#searchform").serialize();
var urlx = "#Url.Action("SR15Fetch", "SR15", new { area = "SALES" })";
debugger;
$.ajax({
type: "GET",
url: urlx,
data: dataT,
cache: false,
success: HandellerOnSuccess,
error: HandellerOnFailer,
beforeSend: Ajax_beforeSend(),
complete: Ajax_Complete(),
});
}
I originally had a regular HTML form that submitted the data entered through a button, which redirected the user to the PHP code page ran the code and everything worked.
Since everything now is confirmed working I need to pass the variables in the form to PHP using Ajax instead to keep the user on the original page.
All of my code checks out everywhere except for any Ajax request I use in the below function. The function correctly grabs all the variables from the form but no matter what form of Ajax or $.post that I use it fails to pass anything.
I am trying to pass all data to http://localhost/send-email.php and respond to the user with a pop up including the echo response from the PHP code.
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"
function capacity(){
var fullname = document.getElementById("fullname").value;
var time = document.getElementById("time").value;
var aux = document.getElementById("aux").value;
var issue = document.getElementById("issue").value;
var issueid = document.getElementById("issueid").value;
var reason = document.getElementById("reason").value;
}
Like I said I read all documentation on Ajax and followed many examples on here but i could not get anything to work. Any help on what my Ajax call should look like is appreciated.
There are a couple of different ways you can POST in the backend.
Method 1 (POST Serialize Array from Form) -
jQuery.post()
$.post('/send-email.php', $('form').serializeArray(), function(response) {
alert(response);
});
Method 2 (Structure Object and POST Object) -
jQuery.post()
var formObject = {
fullname: $('#fullname').val(),
time: $('#time').val(),
aux: $('#aux').val(),
issue: $('#issue').val(),
issueid: $('#issueid').val(),
reason: $('#reason').val()
};
$.post('/send-email.php', formObject, function(response) {
alert(response);
});
Method 3 (Use AJAX to POST Serialize Array from Form) -
jQuery.ajax()
$.ajax({
method: 'POST',
url: '/send-email.php',
data: $('form').serializeArray(),
}).done(function(response) {
alert(response);
});
Method 4 (Use AJAX to POST Form Data) -
jQuery.ajax() - FormData Objects
var formData = new FormData();
formData.append('fullname', $('#fullname').val());
formData.append('time', $('#time').val());
formData.append('aux', $('#aux').val());
formData.append('issue', $('#issue').val());
formData.append('issueid', $('#issueid').val());
formData.append('reason', $('#reason').val());
$.ajax({
url: '/send-email.php',
dataType: 'json',
contentType: false,
processData: false,
data: formData,
type: 'POST',
success: function(response) {
alert(response);
}
});
Virtually, there are many different methods to achieving what you are attempting.
I have this working code:
jQuery.ajax({
type: 'post',
url: 'http://www.someurl.com/callback.php',
dataType: 'json',
data: jQuery(':input[name^="option"][type=\'checkbox\']:checked, :input[name^="option"][type=\'text\']'),
complete: function (mydata) {
//do something with it
}
});
That successfully posts back any checked checkboxes and all textboxes. But now I want to add some arbitrary data as well to this. But not sure how to format it. Basically i want to simply add my own name=value pair "test=1" so that on the callback I see it like the others. But no matter what I try, I can't see to get the syntax correct in the format it expects. not sure if I should be adding it inside the jQuery() wrap or outside.. I've tried serializing, encodeURIComponent, basic string "&test=1"
Any ideas?
Your best bet is to build the parameters outside of the AJAX call, like so:
var params = jQuery(':input[name^="option"][type=\'checkbox\']:checked, :input[name^="option"][type=\'text\']');
params.test = 1;
params.test2 = 2;
Then in your AJAX call, simply use:
jQuery.ajax({
type: 'post',
url: 'http://www.someurl.com/callback.php',
dataType: 'json',
data: params,
complete: function (mydata) {
//do something with it
}
});
EDIT: Typically when using jQuery to collect input, I tend to use the .each function, like so:
var params = new Object();
$.each('input[name^=option]', function() {
if ((this.type === 'checkbox' && $(this).is(':checked')) || this.type === 'text' && this.value !== '') {
params[this.name] = this.value;
}
});
Then if you wish to add parameters, you'd do so either after this, or right after creating your new object.
I forgot I asked this previously. It was answered correctly so I'm sharing the link:
How can I pass form data AND my own variables via jQuery 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
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);
}
);