JavaScript Post and wait for Response JSON - javascript

Right now i have the following code below, this code posts some data to my page and waits for a response of status = SUCCESS or Failure. I am trying to understand if this is async or sync. How can I make this JavaScript query wait for the response and then run what is inside success? It doesn't seem to wait for the response of what it is posting to.
Thanks!
my.submit = function() {
var form = $('#lines');
console.log(form)
var data = form.serialize();
console.log(data)
$.post('', form.serialize(), function(json) {
console.log(json)
if(json.status === 'SUCCESS') {
console.log('success');
window.open(json.imgid, '_self');
} else {
console.log('failure');
}
}, 'json');
$('#progress_bar').show();
}
I then tried to work on making it work the way i wanted by editing the code below but now its just returning the HTML contents of the entire page rather than the JSON response. Any idea why its not getting the JSON response?
my.submit = function() {
var form = $('#lines');
console.log(form)
var data = form.serialize();
console.log(data)
$.ajax({
url: '',
type: 'POST',
data: data,
success: function(json) {
console.log(json)
if (json.status === 'SUCCESS') {
console.log('Success!');
} else {
console.log('An error occurred.');
console.log(data);
}
}
}, 'json');
$('#progress_bar').show();
}

Add dataType: 'json', below data: data,
my.submit = function() {
var form = $('#lines');
//console.log(form)
var data = form.serialize();
//console.log(data)
$.ajax({
async: false,
url: '',
type: 'POST',
data: data,
dataType: 'json',
success: function(json) {
console.log(json)
if (json.status === 'SUCCESS') {
console.log('Success!');
window.open(json.imgid, '_self');
} else {
console.log('An error occurred.');
console.log(data);
}
}
}, 'json');
$('#progress_bar').show();
}

Related

Getting data back from database as undefined in html but defined in the console

I am creating a slim project using CRUD. I am trying to get 1 user, by using GET. When I use .append it returns data like this: the name is the request getting data from the database.
undefined
name
undefined
name
Obviously I only want one user to be shown, however when I add .html instead of .append it just comes back undefined.
This is my code that is coming back undefined
$(document).ready(function showStaff(processResponse) {
$.ajax({
type: 'GET',
dataType: "json",
url: "borrower.php/borrowers",
success: showAllBorrowers,
error: showError
});
});
//shows borrowers in HTML
function showAllBorrowers(responsedata){
$.each(responsedata.borrower,function(index,borrower){
$("#borrower_list").append("<li type='square'> Borrower Id:"+borrower.borrower_id+",FullName:"+borrower.first_name+" "+borrower.last_name+", Email:"+borrower.email);
$("#borrower_list").append("</li>");
});
}
$(document).ready(function(){
$("#btnSaveBorrower").click(function(){
var borrower=new Borrower($("#firstName_add").val(),
$("#lastName_add").val(),$("#email_add").val());
$.ajax({
type: 'POST',
dataType: "json",
url: "borrower.php/borrowers",
data:JSON.stringify(borrower),
success:function(data){
console.log(data)
location.reload();
},
});
});
});
function Borrower(firstName, lastName, email){
this.firstname=firstName;
this.lastname=lastName;
this.email=email;
}
$("#btnSearch").click(function(){
var id = $("#StaffBorrower_Id").val();
$( "#update" ).show();
$( ".delete" ).show();
$("#btnUpdateBorrower").show();
$("#btnDeleteBorrower").show();
$.ajax({
type: 'GET',
dataType: "json",
url: "borrower.php/borrowers/" + id,
success: showResponse,
error: showError
});
});
function showResponse(responsedata){
var item = $("<li>"); item.text("Borrower Id:"+responsedata.borrower_id+",FullName:" +responsedata.first_name+" "+responsedata.last_name+", Email:"+ responsedata.email);
$("#search_borrower").html(item);
item.attr("type", "square");
item.attr("data-delete-id", responsedata.borrower_id); item.attr("data-update-id", responsedata.borrower_id);
console.dir(responsedata);
}
$("#btnDeleteBorrower").click(function(){
var result = confirm("Are you sure you want to delete?");
if (result) {
var staff= delete Borrower($("#borrower_Id").val(), $("#firstName").val(), $("#lastName").val(), $("#email").val());
$.ajax({
type: 'DELETE',
dataType: "json",
url: "borrower.php/borrowers/"+$("[data-delete-id]").data("delete-id"),
success: function(res){
console.log(res);
location.reload();
},
error: showError
});
}
});
$("#btnUpdateBorrower").click(function(){
var result = confirm("Are you sure you want to update?");
if (result) {
var borrower = new Borrower ($("#firstName").val(),
$("#lastName").val(),
$("#email").val());
$.ajax({
type:'PUT',
dataType:"json",
url:"borrower.php/borrowers/"+$("[data-update-id]").data("update-id"),
data:JSON.stringify(borrower),
success:function(data){
console.log(data);
location.reload();
},
error: function(){
console.log("There seems to be an error")
}
});
}
});
The console log is working, I am getting the data in the console but it isn't being returned in the html for some reason. Does anyone have any ideas why? Thanks

I am struggling to pass data to controller through Ajax

Trying to hit DeleteJobQuote controller through Ajax but no luck. Please guide me if anyone has any idea about it. The code seems OK but not able to do so. I am writing this code to delete a particular record from database.
Controller
[HttpPost]
public ActionResult DeleteJobQuote(int jobQuoteid)
{
using (var db = new KeysEntities())
{
var delJob = db.JobQuote.FirstOrDefault(x => x.Id == jobQuoteid);
if (delJob != null)
{
delJob.Status = "Delete";
db.SaveChanges();
return Json(new { success = true, Message = "JobQuote SuccessFully Deleted!" });
}
else
{
return Json(new { success = false, Message = "Delete UnSuccessFul " });
}
}
}
And JavaScript and Knockout code for this
self.deleteJobQuote = function (jobQuote) {
debugger;
$.ajax({
url: '/Companies/Manage/DeleteJobQuote',
type: 'POST',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: function (result) {
if (result.success) {
$('#jobQuoteDeleteModal').modal('show');
}
else {
alert("You can not delete this record !!");
}
}
});
};
Change "data : ko.toJSON(this)" to "data: JSON.stringify({ jobQuoteid: 1 })". I have hardcoded jobQuoteid value to 1. Get it from jobQoute object.
complete code:
$.ajax({
url: '/Companies/Manage/DeleteJobQuote',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ jobQuoteid: 1 }),
contentType: 'application/json',
success: function (result) {
if (result.success) {
$('#jobQuoteDeleteModal').modal('show');
}
else {
alert("You can not delete this record !!");
}
}
});

ajax request posting undefined data from form in nodejs

I am trying to make a comment form which adds a comment in array of blog schema
but when I am using ajax it is giving undefined below the places where I have console log and when I am using simple post request it is working fine.
I am using mongoose, nodejs , express, jquery ajax
my script is as follows
var frm = $('#commentForm');
frm.submit(function (e) {
e.preventDefault();
console.log('clicked');
$.ajax({
type: 'POST',
url: "/blog/addComment",
contentType: "application/json; charset=utf-8",
dataType: 'json'
})
.done(function(data) {
addNewComment(data);
})
.fail(function() {
console.log("Ajax failed to fetch data");
});
});
function addNewComment(data){
console.log(data);
}
my routes is as follows
//add comments
router.post('/addComment',function(req,res,next){
console.log(req.body.comment+" "+ req.body.userId+" "+req.body.postId);
var newComment = {
'text': req.body.comment,
'author': req.body.userId
}
Post.addComment(req.body.postId, newComment, function(err,comment){
if(err) throw err;
console.log(comment);
res.send(comment);
});
});
and my mongoose schema is
//add comments
module.exports.addComment = function( postId, newComment, callback){
var query = { '_id': postId};
console.log('postid: '+postId+" newcomment: "+newComment.text+ " "+newComment.author);
Post.findOneAndUpdate( query, { $push:{'comments': newComment} }, {new:true} , callback);
}
That's because data is not defined in ajax call ,
use following provide the frm is the actallu form or use
use data : form name.serialize()
var frm = $('#commentForm');
frm.submit(function (e) {
e.preventDefault();
console.log('clicked');
$.ajax({
data : $(this).serialize(),
type: 'POST',
url: "/blog/addComment",
contentType: "application/json; charset=utf-8",
dataType: 'json'
})
.done(function(data) {
addNewComment(data);
})
.fail(function() {
console.log("Ajax failed to fetch data");
});
});

Ajax code working in some parts and not working in others

I have a problem with my Ajax request to download some data from a database.
There are two codes down below: one that works and one that doesn't, even though they are basically the same. I've also set up later down my code to display the variable (console.log(location)) but it just reads undefined.
I know the php part of it is working because I also do another console.log(data) on success of the ajax call and that returns with the data I entered on my database. What's going on and how do I fix it?
Code that doesn't work:
var location;
function downloadCoords() {
$.ajax({
type: 'GET',
url: 'transformerthing.php',
dataType: "json",
success: function(data) {
console.log(data);
location = data.location;
},
error: function(data) {
console.log(data);
}
});
}
Code that does work:
var mapCode;
var used;
var active;
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
dataType: "json",
success: function(data) {
console.log(data);
mapCode = data.mapCode;
used = data.used;
active = data.active;
},
error: function(data) {
console.log(data);
}
});
}
//shorthand deferred way
$.getJSON( "transformerthing.php")
.done(function(data){
console.log(data);
}).fail(function(msg){
console.log(msg)
});
var location;
function downloadCoords() {
$.ajax({
type: 'GET',
url: 'transformerthing.php',
dataType: "json",
success: function(data) {
console.log(data);
location = data.location;
console.log(location);
},
error: function(data) {
console.log(data);
}
});
}
Try it again.

Combining Ajax posts with MVC controllers and redirects

I'm trying to get my server-side code to play nicely with some page templates we got from a design agency. All is good except that I'm struggling to implement the correct behaviour with the results of the form submission.
What should happen is, if the form submits successfully, some JQuery is triggered to animate into a success message. If not, the user should be redirected to an error page.
Here's the form submit script:
$.ajax({
type: 'POST',
data: JSON.stringify(userObject),
url: submitFormUrl,
contentType: 'application/json; charset=utf-8',
cache: 'false',
dataType: 'json',
success: function (data) {
if(data.Success){
console.log('success');
$('.thanks-msg').fadeIn(1000);
$('#market-message').hide();
}else{
console.log('Error');
}
}
});
And here's the controller action that it posts to:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(User userObject)
{
bool userExists;
try
{
if (ModelState.IsValid)
{
userExists = InsertUser(userObject); //calls a sproc
}
else
{
return CollectValidationErrors(); // collects all validation errors into a string
}
}
catch(Exception ex)
{
ViewBag.ErrorMessage = "Sorry! There has been an error " + ex.Message;
return Json(new { result = "Redirect", url = Url.Action("Error", "Home") });
}
if(userExists)
{
ViewBag.ErrorMessage = "This user already exists";
return Json(new { result = "Redirect", url = Url.Action("Error", "Home") });
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
What happens is that the form submission is received and the code inside executed successfully. But if an error state is returned, there's no redirect.
What am I doing wrong?
Try to use error property of ajax call:
$.ajax({
type: 'POST',
data: JSON.stringify(userObject),
url: submitFormUrl,
contentType: 'application/json; charset=utf-8',
cache: 'false',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
//Do Something
},
success: function (data) {
if(data.Success){
console.log('success');
$('.thanks-msg').fadeIn(1000);
$('#market-message').hide();
}else{
console.log('Error');
}
}
});
You do not send an error.
You can throw an Exception (forces HTTP Status 500 Internal Server Error) in the Controller Action. It will result that the success is not invoked, but the error function of ajax.
$.ajax({
type: 'POST',
data: JSON.stringify(userObject),
url: submitFormUrl,
contentType: 'application/json; charset=utf-8',
cache: 'false',
dataType: 'json',
success: function (data) {
if(data.Success){
console.log('success');
$('.thanks-msg').fadeIn(1000);
$('#market-message').hide();
}else{
console.log('Error');
}
},
error: function(function (xhr, status, errorThrown)){
// Do Redirect
}
});

Categories