Ajax request inside loop, page reload after completion - javascript

I m using Jquery ajax request inside loop, all goes well till the last request. but after last request, page automatically reloads.I m not being able to understand what is happening there.
Plz review and help.
I m using asp.net web form and web services for handling ajax request.
Jquery Code:
var mainData = GetFromExcel();
function StartSaving()
{
for (i = 0; i < totalCount; i++)
{
DoPost(i);
}
}
function DoPost(i)
{
var mainCode = MainData[i].MainCode;
var noOfAllot = MainData[i].NoOfAllotment;
var CompanyCode = MainData[i].CompanyCode;
console.log(mainCode +' Company Code:'+ CompanyCode+':' + noOfAllot);
$.ajax({
url: "Allotment.asmx/DoAllotment",
data: "{MainCode:'" + mainCode + "', sNoOfAllotment:'" + noOfAllot + "',CompanyCode:'" + CompanyCode + "'}", // the data in JSON format. Note it is *not* a JSON object, is is a literal string in JSON format
dataType: 'text',
contentType: "application/json; charset=utf-8",
type: "Post",
async: false ,
success: function (res) {
console.log(res);
},
error: function (res) {
}
});
}
GetFromExcel is function that takes excelsheet and convert into json array. for that i have used xlsx.js
WebServices Code:
[WebMethod]
public String DoAllotment(string MainCode, string sNoOfAllotment, string CompanyCode)
{
JavaScriptSerializer js = new JavaScriptSerializer();
if(checkData())
return "Error";
else
return "Success";
}

this is a common pitfall.
Modify your javascript method to return false, see below:
function StartSaving() {
for (i = 0; i < totalCount; i++) {
DoPost(i);
}
return false; //This is important for not allowing button click post back
}
In The asp.Net button add OnclientClick as shown below:
<asp:button ..... OnClientClick="return StartSaving();"></asp:button>
***Everything else is perfect in your code!!!!

Related

MVC Controller is not receiving the values that comes from the Ajax /Javascript script

I debugged the JS and Ajax code with console.log. I can see that what I entered into the textbox, is displayed in the console. However, when these values are supposed to send to the controller, they are empty or null when I hover over the tbl_stuff List. Not sure where I am making a mistake.
Here is the JS:
$("body").on("click", "#btnSave", function () {
var table = $("table tbody");
var array= new Array();
table.find('tr').each(function (i) {
var $tds = $(this).find('td'),
Amount = $(this).find('.val').val();
valuestoupdate = { Amount: amount };
array.push(valuestoupdate);
});
$.ajax({
type: "POST",
url: "#Url.Action("StuffAction","Home")",
data: JSON.stringify(array),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) saved.");
}
});
Here is the controller action:
public JsonResult StuffAction(List<tbl_Stuff> stuffs)
{
int getID = (int)TempData["id"];
TempData.Keep();
var GetData = _context.tbl_Detail.Where(x => x.detId == getID).FirstOrDefault();
if (GetData != null)
{
foreach (tbl_Stuff moreThings in stuffs)
{
tbl_Stuff stuff = new tbl_Stuff();
stuff.Amount = moreThings.Amount;
_context.tbl_Stuff.Add(stuff);
}
}
int insertedRecords = _context.SaveChanges();
return Json(insertedRecords);
}
I get an error saying that moreThings.Amount is empty. But during debugging, the JS code gets the value entered into the textbox.
The .Net routing can't match the request
change the action signature to public JsonResult StuffAction(List< string > stuffs)
or in your ajax call change the array to an array of objects matching the properties of tbl_Stuff

'undefined' reported when bind gridview using AJAX in C#

I want to bind the gridview using AJAX. So, for that I done client side code using AJAX and server side code as a webmethod.
Everything is working fine even I alert the data in success method at that time also data is showing but in loop I really confused that it is showing undefined in alert. So for that's why grid is not binding.
Here is my code
$.ajax({
type: "POST",
url: "schoolregistration.aspx/GetGridData",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#grid_schooldata").append("<tr><td>" + data.d[i].schoolName);
}
},
failure: function () {
alert("error! try again...");
}
});
using (var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var cmd = new SqlCommand("select schoolname as [School Name] from tbl_schoolregistration", con))
{
con.Open();
object val = cmd.ExecuteScalar();
return val == DBNull.Value ? "" : (string)val;
}
First of all
ExecuteScalar Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
In this case you will have a single string.
Secondly beware of the name in your query leave it as schoolname not [School Name].
Then you have to Serialize into json and again parse into json in order to loop through objects.
Here is fully working code:
$.ajax({
type: "POST",
url: "schoolregistration.aspx/GetGridData",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (data) {
data = JSON.parse(data.d);
for (var i = 0; i < data.length; i++) {
$("#grid_schooldata").append("<tr><td>" + data[i].schoolname +"</td></tr>");
}
},
failure: function () {
alert("error! try again...");
}
});
[WebMethod]
public static string GetGridData()
{
using (var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var cmd = new SqlCommand("select schoolname from tbl_schoolregistration", con))
{
con.Open();
//object val = cmd.ExecuteScalar();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt); // fills data from select query
// return val == DBNull.Value ? "" : (string)val;
return JsonConvert.SerializeObject(dt);
}
}

How to receive a data from the JSon method?

I have a method in my controller that submits some changes in the database after receiving a filename that being uploaded to the server. Also this method is getting the fileNameOrigin and fileNameUnique (to be downloaded for saving in the server folder)
public JsonResult Upload()
{
var upload = Request.Files[file];
string fileNameOrigin = System.IO.Path.GetFileName(upload.FileName);
string fileNameUnique = String.Format("{0}_" + fileNameOrigin,
DateTime.Now.ToString("yyyyMMddHHmmss"));
//there is more code that isn't needed in my case
return Json(fileNameOrigin, fileNameUnique);
}
So, here's the question - how to send and receive this data on the client side?
$('#uploadFile').on('change', function (e) {
e.preventDefault();
var files = document.getElementById('uploadFile').files;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
}
$.ajax({
type: "POST",
url: '#Url.Action("Upload", "ChatRooms")',
contentType: false,
processData: false,
data: data,
success: onSuccess, //here I need to receive data and do smth with it
error: onError
});
}
}
});
Create a anonymous object with the properties that are required and then pass that single object to the JSON method like:
var data = new {
FileNameOrigin = fileNameOrigin,
FileNameUnique = fileNameUnique
};
return Json(data);
In success callback of ajax, you can access it, for just to check it is working log it on console to see what server has returned like:
success: function(data) {
console.log(data);
},
you might also need to specify datatype in ajax call to json which dictates that JSON is expected from server to be returned in response to this ajax call:
dataType: "json"
Hope it helps!

How to POST both normal JSON data and multiple files to Spring MVC controller through single Ajax request?

I am trying to create a form page consisting of both normal HTML form fields like text boxes, dropdown lists, checkboxes, etc. along with multiple HTML file elements.
Is it possible to POST both the normal JSON data that is built from the normal HTML elements and also the multiple files that are selected to the Spring MVC controller through a single Ajax request?
Is it possible to append stringify-ed JSON object to JavaScript's FormData object?
I'm trying to create a form as shown in the image below:-
Following is the JavaScript code that I'm trying onclick of submit button :-
function submitMyForm() {
function MyFormData(arrOfCityVisitData,arrOfUploadDocsData) {
this.citiesVisitedData = arrOfCityVisitData;
this.uploadDocsData = arrOfUploadDocsData;
}
function CityVisitData(intStateID,intCityID,strVisitDate,strVisitRemarks,intRecID) {
this.stateID = intStateID;
this.cityID = intCityID;
this.visiteDate = strVisitDate;
this.visitRemarks = strVisitRemarks;
this.recID = intRecID;
}
function UploadDocsData(strFileName,strUploadDocsRemarks,intRecID) {
this.fileName = strFileName;
this.uploadDocRemarks = strUploadDocsRemarks;
this.recID = intRecID;
}
var arrOfCityVisitData = new Array();
var intVisitDataTblRowCount=document.getElementById("citiesVisitedByDateTbl").rows.length-1; // 1 static header row
for(var i=0;i<intVisitDataTblRowCount;i++) {
var cityVisitData = new CityVisitData(parseInt(document.myForm.visitedState[i].value,10),
parseInt(document.myForm.visitedCity[i].value,10),
document.myForm.visitDate[i].value,
document.myForm.visitRemarks[i].value,
(document.myForm.visitRecID[i].value!=="") ? parseInt(document.myForm.visitRecID[i].value,10) : -1);
arrOfCityVisitData[i]=cityVisitData;
}
var arrOfUploadDocsData = new Array();
var intUploadDocsTblRowCount=document.getElementById("uploadDocumentsTbl").rows.length-1; // 1 static header row
for(var i=0;i<intUploadDocsTblRowCount;i++) {
var uploadDocData = new UploadDocsData(document.myForm.uploadDocsFile[i].value,
document.myForm.uploadDocsRemarks[i].value,
(document.myForm.uploadDocsRecID[i].value!=="") ? parseInt(document.myForm.uploadDocsRecID[i].value,10) : -1);
arrOfUploadDocsData[i]=uploadDocData;
}
var formData = new FormData();
for (var i = 0, len = $('input[type=file]').length; i < len; i++) {
if($('input[type=file]')[i].files[0]) {
formData.append('file'+i, $('input[type=file]')[i].files[0]);
}
}
alert(JSON.stringify(new MyFormData(arrOfCityVisitData,arrOfUploadDocsData)));
formData.append('myFormData',JSON.stringify(new MyFormData(arrOfCityVisitData,arrOfUploadDocsData)));
console.log("form data " + JSON.stringify(formData));
$.ajax({
url: 'http://localhost:8080/springcrud/ajax/processFormData.do',
data: formData,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
//enctype: 'multipart/form-data',
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (data) {
console.log(data);
}
});}
And following is the Spring MVC controller class's request handler method :-
#RequestMapping(value="/processFormData.do",method=RequestMethod.POST,headers = {"Content-type=application/json"})
#ResponseBody
public String processFormData(#RequestBody MyFormData myFormData) {
System.out.println(((myFormData.getCitiesVisitedData()).get(0)).getVisiteDate());
return "ajaxTrial";
}
And currently this code is throwing 415 (Unsupported Media Type) error in the browser. What changes are to be done to the above code so that files can be uploaded along with normal form data through jQuery ajax request?

$.ajax json method does not hit the web method

When this function is hit , it does not call my function in code behind? Why could it be doing this? How can I fix this error.
$(document).ready(function() {
$('[id$=btn_Update]').click(function() {
var reten = $('[id$=txt_Reten]').val();
var i=0;
var selectValues = "";
var ProdID = new Array();
$("#lst_ProdId option").each(function() {
selectValues = selectValues + $(this).text() + ",";
ProdID[i] = $(this).text();
i++;
});
for(var j=0; j < ProdID.length;j++)
{
// alert(ProdID[j]);
}
var params = "{'ProdID':'" + ProdID + "','RetenP':'" + reten + "'}";
$.ajax({
type: "POST",
url: "/ProductPricing/Products/RetenPeriod.aspx/UpdateRetenPeriod",
data: params,
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function(result) {
alert("sucess");
},
error:function(e) {
alert(e.statusText);
// if(errorThrown != null)
// alert(textStatus+ ":"+errorThrown);
// else
// alert("fail");
}
});
return false;
});
return false;
});
This is my webmethod in code behind:
[WebMethod]
public static bool UpdateRetenPeriod(string[] ProdID,string RetenP)
{
for (int i = 0; i < ProdID.Length; i++)
{
update(ProdID[i],RetenP);
}
return true;
}
You're passing your parameters as a string instead of as an object literal:
var params = "{'ProdID':'" + ProdID + "','RetenP':'" + reten + "'}";
should (almost certainly) be:
var params = {'ProdID': ProdID,'RetenP': reten};
Also, how do you know that the ajax request is not making it to the server? Have you tried tracing the HTTP requests with something like TamperData (for Firefox) or Firebug (also Firefox)?
Does it call the error method?
You need to return JSON. Not a boolean. Perhaps something like {success: true}.
Then:
success: function(data) {
if(data.success) {
...
}
else {
...
}
}
jQuery expects JSON and will throw an error if it doesn't receive well-formed JSON. Also, what is the exact response you're getting back? You can use something like Firebug to figure this out.
One more thing. Can you verify that you can successfully hit that URL? Are you able to successfully point your browser to http://your.url.here/ProductPricing/Products/RetenPeriod.aspx/UpdateRetenPeriod?
Also look at Pointy's solution. Your request is unlikely to succeed since you aren't passing in an actual object literal.
Do you have a ScriptManager defined in the markup with EnablePageMethods set to true?
Also, I believe your params line should be:
var params = "{ProdID:'" + ProdID + "', RetenP:'" + reten + "'}";
I have several functions in my own apps that do it this way. You want the value of params to look like this: "{ProdID:'1,2', RetenP:'undefined'}"
Can you place a breakpoint at alert(e.statusText); to see what the error message is?
Have u got error message.. please, try to get the error message
I think, u can use this by replacing error block
error:
function(XMLHttpRequest, textStatus, errorThrown){
alert( "Error Occured!" + errorThrown.toString());
}
I think, problems occurred in code behind method.. if in [web method] has any problem, then ajax doesn't call the method..

Categories