Pass form data via Ajax to Action - javascript

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

Related

Issues passing form data to PHP using Ajax

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.

AJAX form submission hits proper endpoint but doesn't pass variables

I'm working on the review page before a user buys a product, and on the page is a small field for discount codes, which I want to pass to an endpoint via ajax. I'm using the following javascript function, and the submission happens and returns (even hits the intended endpoint) - but no data gets passed through (verified in logs).
Any idea why no params would be getting passed through?
<script>
$("#discount_code_submit").click(function() {
var url = "/confirm_discount"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#discount_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response
if(data != "false")
{
console.log(data);
}
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
This is because jQuery's serialize method creates a String representation of the form data, in the traditional url query string format. (Please see here: http://api.jquery.com/serialize/)
E.g., calling serialize can return a string such as:
'?query=help&numResults=200'
On the other hand, jQuery's ajax method expects the form data to be provided as an object literal. (Please see here: http://api.jquery.com/jQuery.ajax/)
E.g.
{
query: 'help',
numResults: 200
}
So you can change your ajax call to look like:
$.ajax({
type: "POST",
url: url,
data: {
param1: 'somevalue',
param2: 200
},
success: function(data)
{
alert(data); // show response
if(data != "false")
{
console.log(data);
}
}
});
Or, you could also construct your object literal from the form using a custom function and then provide the reference in the ajax call.
$.ajax({
type: "POST",
url: url,
data: myPreparedObjectLiteral,
success: function(data)
{
alert(data); // show response
if(data != "false")
{
console.log(data);
}
}
});
You could also use http://api.jquery.com/serializeArray/ since it does pretty much what you'll need to convert a form to the json literal representation.
Finally, for a good discussion on converting forms to json objects for posting, you can see the responses here on an SO question: Convert form data to JavaScript object with jQuery

Setting string in javascript function in ASP.NET MVC give NullReferenceException

Inside my MVC view I have javascript that is executed by a button click. I'm trying to set a string to a random set of characters which I can get to work fine but when I try and set that string to 'randomchars' string inside the javascript I get a NullReferenceException when I try and run the view.
Below is the code snippet, the CreateRString is where the model parameter (RString) is set to the random string.
<script type="text/javascript">
function showAndroidToast(toast) {
var url = '#Url.Action("CreateRString", "Functions")';
$.ajax({ url: url, success: function (response) { window.location.href = response.Url; }, type: 'POST', dataType: 'json' });
var randomchars = '#(Model.RString)';
}
</script>
Is the syntax correct? I'm not too sure why it's getting the NULL.
The javascript is executed after the page been delivered to the client (i.e. web browser). Your razor code here is executed on the server before the page is sent to the client. Therefore, the ajax method will execute after you try to access Model.RString
To fix this you can either call CreateRString on the server, or you can set randomchars by using the response in the success callback.
To explain option 2 a bit further. You could do something like this:
//Action Method that returns data which includes your random chars
public JsonResult CreateRString()
{
var myRandomChars = "ABCDEF";
return new JsonResult() { Data = new { RandomChars = myRandomChars } };
}
//The ajax request will receive json created in the CreateRString method which
//contains the RandomChars
$.ajax({ url: url, success: function (response) {
var randomchars = response.Data.RandomChars;
window.location.href = response.Url;
}, type: 'POST', dataType: 'json' });
More specifically, the razor calls #Url.Action("CreateRString", "Functions") and #(Model.RString) execute first on the server.
Then showAndroidToast executes in the client's browser when you call it.

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

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