I have this form in HTML.
<input type="text" id="myID">
<input type="text" id="myName[]">
<input type="text" id="myName[]">
myID field is used once while myName field is used multiple time in form. How can I pass the value of myName to AJAX? I am doing the following but it only works for myID and not myName
document.getElementById('myForm').onsubmit = function ()
{
var model = new FormData();
model.append("myID", $('#myID').val());
model.append("myName", $('#myName').val());
$.ajax({
url: "/MyController/MyMethod",
type: "POST",
data: model,
contentType: false,
processData: false,
success: function (response) {
Do_Something_Here;
},
error: function (xhr, error, thrown) {
alert(xhr.responseText);
}
});
}
Related
I am sending ajax request in asp.net i get this error
POST http://localhost:1549/AdminArea/Roles.aspx/Create 500 (Internal
Server Error)
it is with Master Page Also shown code is in individual page Roles.aspx
my HTML Code
<form id="FormSave">
<input type="text" name="txtName" id="txtName" required="required"
class="form-control"/>
<input type="radio" name="Status" value="1" checked="checked"/> Active
<input type="radio" name="Status" value="0"/> In-active
</form>
Javascript Code For Sending Request
<script type="text/javascript">
$(document).ready(function () {
$("#BtnSave").click(function () {
var jsonText = JSON.stringify({ Name: $("txtName").val(), Status: $("Status").val() });
$.ajax({
type: "POST",
url: "Roles.aspx/Create",
contentType: "application/json; charset=utf-8",
data: jsonText,
dataType: "json",
success: function (response) {
alert(response);
}
});
});
});
</script>
SERVER SIDE C# SCRIPT /// IN Roles.aspx.cs file
[WebMethod]
public static string Create(string Name, string Status)
{
return "Hello " + Name + "With " + Status;
}
I want to alert this Hello Name With Status
I have seen answers to this question many times, but most of them are related to MVC controllers.
The issue I am having while trying to send a form using Ajax is that while in debug mode, the execution flow won't reach the break point I have in my code behind. Also, I notice that when I click in the submit button, the page refreshes very quickly; I though that the whole idea of ajax was to not refresh the page.
This is my index.aspx
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="ajaxform.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<fieldset class="fs1">
<input id="inputData" tabindex="1" name="theinputData" class="field" placeholder="Paste URL, docId or docSetId" runat="server"/>
<input id="form1Send" type="submit" class="button" onclick="submit()"/>
</fieldset>
</div>
</form>
</body>
Here is the code of my ajaxform.js
$(document).ready(function () {
$('#form1').submit(function (e) {
var formData = new FormData(this);
$.ajax({
url: 'index.aspx/OnSubmit',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: formData,
contentType: false,
processData: false,
success: function (result) {
alert("We returned: " + result);
},
error: function (result) {
alert("Error");
}
});
e.preventDefault();
});
});
Finally, here is my code behind
namespace mySpace
{
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string OnSubmit()
{
return "I was in code behind";
}
}
}
My break point is on the return line. Why the program never reach the WebMethod?
There are a couple of issues with your code:
You're double declaring something to handle the form. Your form1send button has onclick="submit()" in it as well as the form submit handler you're wiring up via jQuery
The content of your JavaScript handler is slightly off, for example you set contentType twice.
Here's a simplified version of the JavaScript that works on my machine:
$(document).ready(function () {
$('#form1').submit(function (e) {
$.ajax({
type: "POST",
url: "index.aspx/OnSubmit",
contentType: "application/json; charset=utf-8",
data: '{}',
dataType: "json",
success: function (response) {
alert(response.d);
},
failure: function (response) {
}
});
e.preventDefault();
});
});
NOTE: I based this (the content of the $.ajax call) on a code sample I found elsewhere, which is why the parameters and order of the parameters are different to yours.
If your app has a RouteConfig.cs file present, you may also need to change settings.AutoRedirectMode = RedirectMode.Permanent; to settings.AutoRedirectMode = RedirectMode.Off; if you see an HTTP 401 error in your browsers developer tools console for the request to your WebMethod decorated method in index.aspx.
By executing event.preventDefault() before FormData(this) a premature refresh is prevented.
See below:
$(document).ready(function () {
$('#form1').submit(function (event) {
event.preventDefault();
var formData = new FormData(this);
$.ajax({
url: 'index.aspx/OnSubmit',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: formData,
contentType: false,
processData: false,
success: function (result) {
alert("We returned: " + result);
},
error: function (result) {
alert("Error");
}
});
});
});
This question already has answers here:
How to append whole set of model to formdata and obtain it in MVC
(4 answers)
Closed 6 years ago.
I'm new to front-end development and i'm trying to get a better understanding of front-end and how it connects with the back-end. Basically I am trying to submit a file to an action method in the back-end but for some reason it never hits the method.
Front-end:
<form id="Form2" name="Form2">
<input type="file" name="file" id="file" multiple />
<input type="submit" value="Upload" />
</form>
<script>
$(function () {
$("#Form2").submit(function (event) {
var formData = new FormData(this);
$.ajax({
url: "Property/UploadPropertyCSV",
type: 'POST',
datatype: 'json',
data: formData
}).done(function (data) {
alert(data);
});
});
});
</script>
Back end:
public ActionResult UploadPropertyCSV(HttpPostedFileBase file)
{
// bunch of processing
return Json(true);
}
Any ideas why this is happening?
Thanks in advance
im not really sure about your ajax method, but basically, I would do it like bellow :
$("#Form2").submit(function (event) {
var formData = new FormData(this);
$.ajax({
url: '#Url.Action("UploadPropertyCSV", "Property")',
type: 'POST',
datatype: 'json',
data: { file: formData},
success: function (result) {
alert(result);
}
})
});
I'm trying to pass my JSON object and two input file fields back to my MVC 4 controller from my view. If I set async: true, in my ajax I get the JSON object and no files. If I set my async: false, I get the files and no JSON.
Any ideas as to why I can't send everything back to my controller? I'm trying to upload images to my server.
Also as a side note, my JSON never returns success, it always errors, but the value is still passed to the controller when async: true,.
Any help would be great, thank you!
JSON:
var json = {Details:{"Name":"Person Name","Url":"http://stackoverflow.com/"};
AJAX:
$.ajax({
url: '/Admin/Create',
type: 'POST',
data: JSON.stringify(json),
dataType: 'json',
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
success: function () {
console.log('SUCCESS');
},
complete: function () {
console.log('COMPLETE');
}
});
Controller:
[HttpPost, ValidateInput(false)]
public ActionResult Create(AdminObjectModel jsonData,
IEnumerable<HttpPostedFileBase> images, IEnumerable<HttpPostedFileBase> small_images)
{
...
return Redirect("/admin/create");
}
HTML:
<form action="/Admin/Create" enctype="multipart/form-data" method="post">
...
<input type="file" id="images" class="span6" name="images" multiple />
...
<input type="file" id="small-images" class="span6" name="small_images" />
...
</form>
I think I figured out a solution, not sure if it's the best one, but it works.
View > AJAX:
$.ajax({
url: '/Admin/CreateJSON',
type: 'POST',
data: JSON.stringify(json),
dataType: 'json',
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
success: function () {
console.log('SUCCESS');
},
complete: function () {
console.log('COMPLETE');
}
});
View > HTML:
<form action="/Admin/Create" enctype="multipart/form-data" method="post">
...
<input type="file" id="images" class="span6" name="images" multiple />
...
<input type="file" id="small-images" class="span6" name="small_images" />
...
</form>
Controller:
private static AdminObjectModel create = new RecipeObjectModel();
[HttpPost, ValidateInput(false)]
public void CreateJSON(AdminObjectModel jsonData)
{
create = jsonData;
}
[HttpPost, ValidateInput(false)]
public ActionResult Create(IEnumerable<HttpPostedFileBase> images, IEnumerable<HttpPostedFileBase> small_images)
{
string t = create.Details.Name;
...
return Redirect("/admin/create");
}
my script
<script type ="text/javascript">
$(document).ready(function () {
$('#<%=Button1.ClientID %>').click(function () {
var ABC = 'TEST';
$.ajax({
type: "POST",
url: "Default.aspx/ServerSideMethod" ,
data: "{ EmailAddress : ABC }",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
alert(msg);
$('#myDiv').text(msg.d);
}
})
return false;
});
});
</script>
Code behind method
[WebMethod]
public static string ServerSideMethod(string EmailAddress)
{
return EmailAddress ;
}
<asp:Button ID="Button1" runat="server" Text="Click" />
<br /><br />
<div id="myDiv"></div>
at button click it give me InvalidJSONprimitive:ABC this error can any body tell what i m doing wron.
As the error clearly states, the JSON that you're sending to the server is invalid.
String literals in JSON must be quoted.
You should call JSON.stringify({ EmailAddress: ABC }) to build a JSON string from a Javascript object expression.