AJAX Post call no data - javascript

Hello wenn i want to send a post request to my Controller there is no data.
I tried to log my Json file and there is something. But when I send the post request my controller shows it is empty.
Here is my call:
var item = {};
var jsonObj = [];
item["ProductCategoryId"] = i;
item["Name"] = txtName;
item["Description"] = txtDescription;
item["Price"] = txtPrice;
item["Stock"] = txtStock;
item["ProductCategory"] = txtProductCategory;
item["Image"] = await getAsByteArray(txtImage);
jsonObj.push(item);
var jsonString = JSON.stringify(jsonObj);
console.log("jsonString : " + jsonString);
$.ajax({
url: "/Admin/SaveProductToDB",
type: "POST",
data: { dataToSend: jsonString},
success: function (data) {
if (data.status == "Success") {
BootstrapDialog.show({
title: 'Success!',
message: "Data Updated Successfully!",
buttons: [{
label: 'OK',
action: function (dialog) {
window.location.href = "/Admin/Product";
removeProdData(i);
$("#btnAddProd").attr("disabled",false);
dialog.close();
}
}]
});
}
}
});
//Here I make a breakpoint but my string is empty
public JsonResult SaveProductToDB(string dataToSend)
{
List<Product> _List = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Product>>(dataToSend);
}
the getAsByteArray
async function getAsByteArray(file) {
return new Uint8Array(await readFile(file))
}
function readFile(file) {
return new Promise((resolve, reject) => {
// Create file reader
let reader = new FileReader()
// Register event listeners
reader.addEventListener("loadend", e => resolve(e.target.result))
reader.addEventListener("error", reject)
// Read file
reader.readAsArrayBuffer(file)
})
}
I found out if I remove the Image. that the controller is then able to resize it. Thanks for the help so far. So I need to look at this place where the problem is.

You are checking against data.status as if it's a given that it exists. Just console.log(data) instead and you will see whether or not status is being returned.
Also, if you open the Network tab in Chrome you can click on the post request & see if your headers are going through accurately and also click on 'Preview' to see an unfiltered result from the controller.
You might want to modify your code to catch errors for debugging, ie:
$.ajax({
url: "/Admin/SaveProductToDB",
type: "POST",
data: { dataToSend: jsonString},
success: function (data) {
if (data.status == "Success") {
BootstrapDialog.show({
title: 'Success!',
message: "Data Updated Successfully!",
buttons: [{
label: 'OK',
action: function (dialog) {
window.location.href = "/Admin/Product";
removeProdData(i);
$("#btnAddProd").attr("disabled",false);
dialog.close();
}
}]
});
}
},
error:function (xhr, ajaxOptions, thrownError) {
// Set up whatever error reaction you want, here. ie:
console.log('An error was encountered.');
alert(xhr.status);
alert(thrownError);
}
});
Another tip is to validate empty data being submitted prior to the Ajax call, so you only touch the backend server when your data is valid - to avoid an error.

Related

How can I get response ajax correctly?

I am learning C# and jQuery AJAX. I'm currently having a problem where I cannot get Ajax to run correctly and I am not sure why.
Here is the error log:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Here is my code:
HTML
<button class="btn btn-primary btn-edit" id="{{SubjectId}}" id1="
{{StudentId}}" >Edit</button>
JavaScript AJAX code:
$('.btn-edit').off('click').on('click', function () {
$('#editModal').modal('show');
var id = parseInt($(this).attr('id'));
var id1 = parseInt($(this).attr('id1'));
ExamsController.LoadDetail(id, id1);
});
LoadDetail: function (id, id1) {
$.ajax({
url: '/Exams/LoadDetail',
type: 'GET',
data: {
id : id,
id1 : id1
},
dataType: 'json',
success: function (response) {
console.log(response.status);
if (response.status == true) {
var data = response.data;
$('#txtSubjectName').val(data.Subject.SubjectName);
$('#txtStudentName').val(data.Student.StudentName);
$('#numScore').val(data.Score);
} else {
alert("Error!")
}
},
Error: function (err) {
console.log(err);
}
});
},
And ExamsController
[HttpGet]
public JsonResult LoadDetail(int id, int id1)
{
bool status = false;
Exam exam = new Exam();
exam = db.Exams.Find(id, id1);
status = true;
return Json(new
{
data = exam,
status = status
}, JsonRequestBehavior.AllowGet);
}
Internal server error means you have error in C# script, please double check error logs.
And also your code isnt cleanest, missing semi-colons.
Try add semi-colons, add name to function , and check error log, it can be useful, we can make better answer.
Maybe try this code with semi colon :) :
$('.btn-edit').off('click').on('click', function () {
$('#editModal').modal('show');
var id = parseInt($(this).attr('id'));
var id1 = parseInt($(this).attr('id1'));
ExamsController.LoadDetail(id, id1);
});
LoadDetail: function (id, id1) {
$.ajax({
url: '/Exams/LoadDetail',
type: 'GET',
data: {
id : id,
id1 : id1
},
dataType: 'json',
success: function (response) {
console.log(response.status);
if (response.status == true) {
var data = response.data;
$('#txtSubjectName').val(data.Subject.SubjectName);
$('#txtStudentName').val(data.Student.StudentName);
$('#numScore').val(data.Score);
} else {
alert("Error!");
}
},
Error: function (err) {
console.log(err);
}
});
},
Thanks!

chrome.storage.local.get not working

Here i'm using to store the multiple value[below is the code]
Here DocName is the Name of the PDF and Base64File is the base64 string of the pdf
var obj = { DocName: res.Value.DocumentName, Base64File: res.Value.Base64File };
chrome.storage.local.set({ 'MyFile': obj });
In next page i'm retriving like this
$(document).on('click', '.sendToPdf', function(){
chrome.storage.local.get('MyFile', function (result) {
var PdfBase64 = result.MyFile.Base64File;
var DocumentName = result.MyFile.DocName;
var arr=new Array();
var item={"CategoryID": 11,"DocumentNumber": "22022018053567","Base64FileData": PdfBase64,"DocumentName": DocumentName,
"OptionalParam1": "sample string 5"};
arr.push(item);
$.ajax({
type: "POST",
url: Documentupload,
headers: {
'Authorization': headerdata,
'Content-Type':'application/json'
},
data:JSON.stringify(arr),
dataType: 'json',
success: function (res) {
if (res.IsSuccess) {
setTimeout(function () {
$("#divLoading").hide();
}, 2000);
//$("#divLoading").hide();
$(".modal-iframe1").attr("src", window.emSigner.OnlineSignUrl + res.Response[0].DocumentID + "&AuthToken=" + AuthToken);
//window.location.reload();
}else{
alert(res.Messages);
window.location.href='/PdfLogin.html';
}
},
error: function (error) {
//alert("Error while communicating to the server");
alert(error.responseText);
window.location.href='/PdfLogin.html';
}
});
});
});
[check this image .sendToPdf(button)]
Question is, if i click the button first time on any icon, the values are retriving correctly, but in second time if i click other than 1st icon i'm getting the values as the before one? it is accepting the previous values only?
How to resolve this,
Help me to come out of this problem.

Ajax call showing error cant debug

this is how the javascript looks like
<script type="text/javascript">
$(document).ready(function () {
$('#loginButton').click(function () {
//this.disabled = true;
debugger;
var data = {
"userid": $("#username").val(),
"password": $("#password").val()
};
$.ajax({
url: "/Account/LoginPost",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
},
error: function () {
alert('Login Fail!!!');
}
});
});
});
I am getting the alert('Login fail') also debugger not getting hit.
I am using jquery 1.9.1 and have included unobstrusive
my controller is this as you can i am passing string values not object values
to the controller so stringify is justified here
[HttpPost]
public JsonResult LoginPost(string userid, string password)
{
using (someentities wk = new someentities())
{
var LoginUser = wk.tblUsers.Where(a => a.Username.Equals(userid)&&a.Password.Equals(password)).FirstOrDefault();
if (LoginUser != null)
{
FormsAuthentication.SetAuthCookie(userid,false);
Session["Username"] = LoginUser.Username;
Session["Password"] = LoginUser.Password;
Session["Name"] = LoginUser.Name;
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
else
{
TempData["Login"] = "Please Enter Correct Login Details";
return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
}
}
// If we got this far, something failed, redisplay form
}
when page is loading these error are shown
$(..) live is not a valid function in
(anonymous function) # jquery.unobtrusive-ajax.js:115
(anonymous function) # jquery.unobtrusive-ajax.js:163
take a look to the success function
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
}
you are using multiple ", combine it with the single one ', this is a syntax error, try to check the code on an editor such as Atom, to avoid this kind of errors
Stringify converts an object to a string. Have you tried passing data an object instead of a string? Try replacing JSON.stringify(data), with data?

Asynchronous Add/Update save method not updating

I am building a .NET page for a project that adds a new City and State for a new user or updates the City and state if their ID is already in the database. Everything is working fine except for the fact that if a past user clicks submit to update their information, an entirely new entry is added to the database.
I have created the method already in the repository listed below.
public async Task<LocationViewModel> SaveLocationAsync(LocationViewModel model)
{
try
{
var location = new Location()
{
City = model.City,
State = model.State
};
if (model.Id != 0)
{
location.Id = model.Id;
}
_dbcontext.Location.AddOrUpdate(location);
await _dbcontext.SaveChangesAsync();
return model;
}
catch (Exception ex)
{
model.Error = true;
model.ErrorMessages = new List<string>()
{
string.Format("Something went wrong - Message: {0} \n Stack Trace: {1}", ex.Message,
ex.StackTrace)
};
return model;
}
}
I have also built a controller that saves and updates existing records asynchronously shown below.
[System.Web.Mvc.AllowAnonymous]
[System.Web.Http.HttpPost]
public async Task<LocationViewModel> SaveLocationApiAsync(LocationViewModel model)
{
var result = new LocationViewModel();
if (ModelState.IsValid)
{
result = await _locationRepository.SaveLocationAsync(model);
}
return result;
}
In addition, I have added added all of my routes and references.
Why is a new entry put in the database instead of the current one updating? The Javascript is shown below.
self.Submit = function () {
if (self.errors().length !== 0) {
self.errors.showAllMessages();
return;
}
if (isNumber(locationId)) {
self.Location().LocationId(locationId);
swal("Success", "Thank you for your submission \nYour information has been updated.", "success");
}
var newData = ko.mapping.toJSON(self.Location());
var url = "/Admin/SaveLocationApiAsync/Post/";
$.ajax({
url: url,
method: "POST",
data: newData,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (result.Error === true) {
swal("Error", result.ErrorMessages.join('\n'), "error");
} else {
//TOdo
}
},
error: function () {
swal("Error", "Something went wrong.\nPlease contact help.", "error");
}
});
};
I apologize if it is a lot. I have checked everything repeatedly and have fixed all bugs. I am out of ideas.
Thanks in advance.
Your url looks to the controller action seems incorrect. You have var url = "/Admin/SaveLocationApiAsync/Post/"; when it should be var url = "/Admin/SaveLocationApiAsync";
Another approach to getting the correct url would be:
var url = '#Url.Action("SaveLocationApiAsync", "<ControllerName>")';
Also, in your ajax error handler you can get the HTTP status code and error message, which would help.
error: function (jqXHR, textStatus, errorThrown) {
swal("Error", "Something went wrong.\nPlease contact help.", "error");
}
EDIT:
I should have prefaced that using Url.Action works when your JavaScript is in a view (assuming Razor view in this case).
Fiddler is great tool to use when debugging ajax calls.

JavaScript is Doing a Post on Server Side Twice

Student Data Grid that display the student id and a description in the grid. It also has a select button when the user click on it that would route to a javascript function. This function will set some flags on the server side, close the window, past the studentID on a search box and do an automatic search on the studentID. The click appears to be doing exactly what I want it to do.
However, if the user were to double click on a row in the grid, it is supposed to do the exact same thing. it should also do a post. The double click is doing the post twice. What is causing it to do the post twice? I have not been able to figure it out. I've been putting alert all over the place and no success as to why.
In case you may be wondering why I have the dataroute and a client side script. This grid is in a pop up page that is also being called from other pages. When the user calls the grid from another page, the user will have the ability to select multiple records vs. only being able to select one records when they are calling it from the Course Page.
Here is the Grid:
#(Html
.Telerik()
.Grid((IEnumerable<OverrideStudent>)SessionWrapper.Student.OtherStudentSelected)
.Name("StudentData")
.DataKeys(Keys =>
{
Keys.Add(c => c.StudentID);
})
.DataBinding(databinding => databinding.Server())
.Columns(columns =>
{
columns.Bound(p => p.StudentId)
.Title("Student ID")
.Width(15)
.Sortable(true)
.Filterable(false);
columns.Bound(p => p.StudentDescription)
.Title("Description")
.Width(65)
.Sortable(true)
.Filterable(false);
columns.Command(command =>
{
command.Custom("AddStudent")
.Text("Select")
.DataRouteValues(routes =>
{
routes.Add(o => o.StudentID).RouteKey("StudentID");
routes.Add(o => o.StudentDescription).RouteKey("StudentDescription");
})
.Action("Student", "StudentInfo");
.HtmlAttributes(new { onclick = "PostData(this);StudentSelectClick(this)" });
}).Width(20);
}).ClientEvents(clients => clients
.OnComplete("OnComplete")
//.OnDataBinding("DataBinding")
//.OnDataBound("onRowDataBound")
.OnRowSelected("StudentDoubleClick")
)
.Sortable()
.Selectable()
.Filterable(filtering => filtering
.Enabled(true)
.Footer(true)
.HtmlAttributes(new { style = "padding-right: 0.0em;" }))
Here are the JavaScripts that are doing the post:
function StudentDoubleClick(e) {
var fromCourse = "#SessionWrapper.Student.FromCoursePage";
var fromList = "#SessionWrapper.Student.FromListingPage";
if (fromCourse == "True") {
$('tr', this).live('dblclick', function () {
alert("Inside TR count = " + count);
count = count + 1;
DoSearchStudent(e);
});
}
if (fromList == "True") {
$('tr', this).live('dblclick', function () {
DoSearchStudent(e);
});
}
}
function DoSearchStudent(e) {
var row = e.row;
var StudentID = row.cells[0].innerHTML;
var StudentDescription = row.cells[1].innerHTML;
// alert(procCodeDesc);
var data = { "StudentID": StudentID, "StudentDescription": StudentDescription, "action": "Double Click" };
var url = '#Url.Action("Student", "StudentInfo")';
$.ajax({
url: url,
type: 'post',
dataType: 'text',
cache: false,
async: false,
data: data,
success: function (data) {
window.top.location.href = window.top.location.href;
},
error: function (error) {
alert("An error has occured and the window will not be closed.");
}
});
}
//Single Click on BUtton
function StudentSelectClick(e) {
var windows = this.parent.$('#Window').data('tWindow');
var fromCourse = "#SessionWrapper.Student.FromCoursePage";
var fromList = "#SessionWrapper.Student.FromListingPage";
if (fromCourse == "True") {
var studentInformation = e.toString();
var data = { "myModel": "null", "studentInformation": studentInformation };
var url = '#Url.Action("UpdatedFromSelect", "StudentProcedure")';
$.ajax({
url: url,
type: 'post',
dataType: 'text',
cache: false,
async: false,
data: data,
success: function (data) {
// window.top.location.href = window.top.location.href;
windows.close();
// setTimeout(this.window.top.location.href = this.window.top.location.href, 1000);
window.top.location.href = window.top.location.href;
},
error: function (error) {
alert("An error has occured and the window will not be closed.");
}
});
}
}
This is the method where the double is being posted to. It simply redirect to a different method of return type ActionResult that also does a redirect to the index page of return ActionResult:
public string Student(string StudentID, string StudentDescription, string action)
{
if (StudentDescription != null)
{
StudentDescription = HttpUtility.HtmlDecode(StudentDescription);
}
try
{
AddStudent(StudentID, StudentDescription, action);
}
catch (Exception e)
{
return "Error " + e.ToString();
}
return "Success";
}
Your help would be greatly appreciated, thanks.
Have you checked the number of times jQuery and the Unobtrusive scripts are added in your html? I had an issue in a previous project where one of these was duplicated and caused a double post.

Categories