Ajax call successful, but error block is executing - javascript

I'm trying to save a post to my database which it does, however the ajax error block is executing. It states ok in its response though so I looked around on some of the other questions and it seemed like I wasn't returning a Json object so I tried a few things:
Creating a NameValule variable and adding ("Success","true") and converting it to Json by Json.Encode(NameValue);
Returning a string in the format of Json:"{ \"Result\":[{\"Success\":\"true\"}]}";
Changing the dataType to "text json" "text/json"
The error block still executes for some reason, any ideas?
//Save it all in an object to be passed in ajax
var Post = {
Id: postID,
Title: postTitle.val(),
Author: postAuthor,
Date: postDate,
Content: postContent.val(),
metaDescription: metaDescription.val(),
metaKeywords: metaKeywords.val(),
metaID: metaId.text(),
Page: $(document).attr('title')
};
//save to database
$.ajax({
url: url,
type: 'POST',
dataType: "text json",
data: { data: JSON.stringify(Post) },
success: function (result) {
console.log("result: " + result);
if (result == "Success") {
// postContent.append("<br/><p>Edit Successful!</p>");
alert('Edit successfull');
//window.location.replace(window.location.href);
}
else {
postContent.replaceWith("<div>" + result + "</div>");
}
},
error: function (xhr, status) {
console.log('ajax error = ' + xhr.statusText);
}
});
Here is the response page:
#using WebMatrix.Data;
#functions{
public string EditPost()
{
var db = Database.Open("StarterSite");
var post = Request.Unvalidated["data"];
var result = Json.Decode(post);
var error = new System.Collections.Specialized.NameValueCollection();
/* Id: postID,
Title: postTitle,
Author: postAuthor,
Date: postDate,
Content: afterEdit,
Page: $(document).attr('title')
*/
if(string.IsNullOrEmpty(result["Id"]))
{
error.Add("Error", "Id empty");
return Json.Encode(error);
}
if (string.IsNullOrEmpty(result["Author"]))
{
error.Add("Error", "Author empty");
return Json.Encode(error);
}
if (string.IsNullOrEmpty(result["Content"]))
{
error.Add("Error", "Content empty");
return Json.Encode(error);
}
if (string.IsNullOrEmpty(result["Date"]))
{
error.Add("Error", "Date empty");
return Json.Encode(error);
}
//Page and Title only ones that can be empty
var cmd = "UPDATE Posts SET ID='" + result["Id"]
+ "',Author='" + result["Author"]
+ "',Content='" + result["Content"]
+ "',Date='" + result["Date"]
+ "',Title='" + result["Title"]
+ "',Page='" + result["Page"]
+ "' WHERE ID='" + result["Id"] + "';";
try { db.Execute(cmd); }
catch (Exception e)
{
error.Add("Error",e.Message);
return Json.Encode(error);
}
if (string.IsNullOrEmpty(result["metaDescription"]))
{
error.Add("Error", "metaDescription empty");
return Json.Encode(error);
}
if (string.IsNullOrEmpty(result["metaKeywords"]))
{
error.Add("Error", "metaKeywords empty");
return Json.Encode(error);
}
//Post was edited successfully add/update meta info
int parseResult = 0;
Int32.TryParse(result["metaID"], out parseResult);
if (parseResult > 0)//metaID is supplied
{
cmd = "UPDATE MetaInfo SET Description='" + result["metaDescription"]
+ "',Keywords='" + result["metaKeywords"]
+ "',postID='" + result["Id"]
+ "' WHERE ID='" + result["metaID"] + "';";
}
else //metaID is not supplied
{
cmd = "INSERT INTO MetaInfo (Description,Keywords,postID) VALUES('"
+ result["metaDescription"] + "','"
+ result["metaKeywords"] + "','"
+ result["Id"] + "');";
}
try
{
db.Execute(cmd);
}
catch (Exception e)
{
error.Add("Error",e.Message);
return Json.Encode(error);
}
//End Update meta info
error.Add("Success", "true");
return Json.Encode(error); //"{ \"Result\":[{\"Success\":\"true\"}]}";
}
}
#{
var result = EditPost();
}
#result

For anyone else that may have this same problem here was how I finally solved it: Just use Html.Raw(result) to send back only the json instead of extra stuff that gets added for some reason.

Can't be sure without knowing the requirements for the url. My guess would be that the data property is the reason you're off. I'm guess Post is an object defined elsewhere. When you send your request, the server will likely interpret the data field as an object not a string. Try to change {data: JSON.stringify(Post)} to just JSON.stringify(Post)

try with adding async: true, line after type: 'POST',

Problem is with your JSON response.
"{ \"Result\":[{\"Success\":\"true\"}]}";
There added slashes before double quotes(").
You can see the actual error thrown by jQuery using below updated error block:
error: function (xhr, status, errorThrown ) {
console.log(errorThrown )
Solution:
Remove slashes from your response try response like below:
'{ "Result":[{"Success":"true"}]}'
Hope this will help you.
Regards,

Related

Correct URL in ajax call JavaScript

I have a GET ajax call as follows :
var changeUrl = "changePriority?newValue=" + targetValue + "&justification=" + justification
if (dataInfo == "row") {
changeUrl += "&id=" + id
}
changeUrl += "&executedConfigId=" + executedConfigId + "&currUser=" + currentUser + "&productName=" + productName + "&eventName=" + eventName + "&alertDetails=" + JSON.stringify(alertArray);
//if the selected signal is not null then we show the product names
$.ajax({
url: changeUrl,
type: "GET",
success: function (data) {
for (var index = 0; index < checkedRowList.length; index++) {
var row = checkedRowList[index]
signal.list_utils.change_priority(row, targetValue);
}
$('#change-priority-modal').modal('hide');
if (applicationName == "Signal Management") {
signal.list_utils.set_value(parent_row, 'dueIn', id, signal.list_utils.get_due_in, applicationName);
$(parentField).html(targetValue);
}
location.reload();
},
error: function (exception) {
console.log(exception);
}
});
The value of changeUrl as I get in my browser's developer console is :
http://localhost:8080/signal/singleCaseAlert/changePriority?newValue=Medium&justification=test%20justification%20first.&id=6816&executedConfigId=6704&currUser=15&productName=Wonder%20Product&eventName=1.Pyrexia&alertDetails=[{%22alertId%22:%226816%22,%22event%22:%221.Pyrexia%22,%22currentUser%22:%2215%22}]
But I get a 400 bad request status and a http header parse error in the backend. Can someone help me resolve this?
On your JSON.stringify(alertArray) you'll need to also encodeURI();
encodeURI(JSON.stringify(alertArray));
A better solution would be send your JSON in the body of a POST request if thats feasible within your design

Display JSON Result Upon Button Click ASP.NET MVC

Hi I have this code in my controller:
[HttpPost]
public JsonResult CalculateAndSaveToDB(BMICalculation CalculateModel)
{
if (ModelState.IsValid)
{
CalculateModel.Id = User.Identity.GetUserId();
CalculateModel.Date = System.DateTime.Now;
CalculateModel.BMICalc = CalculateModel.CalculateMyBMI(CalculateModel.Weight, CalculateModel.Height);
CalculateModel.BMIMeaning = CalculateModel.BMIInfo(CalculateModel.BMICalc);
db.BMICalculations.Add(CalculateModel);
db.SaveChanges();
}
return Json(new {CalculatedBMI = CalculateModel.BMICalc.ToString(), CalculatedBMIMeaning = CalculateModel.BMIMeaning.ToString() }, JsonRequestBehavior.AllowGet);
}
I would like to display CalculatedModel.BMICalc and CalculatedModel.BMIMeaning on the page using this JavaScript:
$('#good').click(function () {
var request = new BMICalculation();
$.ajax({
url: "CalculateAndSaveToDB",
dataType: 'json',
contentType: "application/json",
type: "POST",
data: JSON.stringify(request),
success: function (response) {
var div = $('#ajaxDiv');
div.html("<br/> " + "<b>" + "Your BMI Calculations: " + "</b>");
printBMI(div, response);
},
});
});
function printBMI(div, data) {
div.append("<br/>" + "You are " + response.CalculatedBMI + ".");
div.append("<br/>" + "You exact BMI is: " + response.CalculatedBMIMeaning + ".");
};
Nothing happens however when I do the button click. The correct data from form goes correctly into DB. My Chrome debugger says however that CalculateAndSaveToDB isn't found 404 error. Please help.
Try to return false at the end of your click function.
$('#good').click(function () {
//Your code
return false;
});
Also I can see an error in your printBMI function. There is not reference to the variable "response". It should be "data"
function printBMI(div, data) {
div.append("<br/>" + "You are " + data.CalculatedBMI + ".");
div.append("<br/>" + "You exact BMI is: " + data.CalculatedBMIMeaning + ".");
};
There might be several problems:
Your routing is not correct and the post-action cannot be invoked. I dont see any information about routing, so this might be a problem.
You do not return false, as suggested by PraveeReddy. If you dont do so, the browser follows the link of your button.
Just a hint: In such simple scenarios it can be easier to use $.load: http://api.jquery.com/load/

Ajax / PHP / Json: One GET parameter is missing

I have a problem because one parameter (out of 2) is always missing on the server side (when I send them via AJAX to it).
My JS code looks like:
function import_websql(user_id) {
var db = openDatabase("database", "1.0", "table", 2*1024*1024);
var favourite_ids = "";
if (window.openDatabase){
db.transaction(
function(t){ // This is the callback with "t" as the transaction object
t.executeSql('SELECT * FROM favourites', [], function (t, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
favourite_ids += results.rows.item(i).id + "t";
}
});
}, onError, onReadyTransaction(user_id,favourite_ids)
);
} else{
alert("Your smartphone is too weird!");
};
}
function onReadyTransaction(user_id,favourite_ids) {
alert(favourite_ids);
send_websql(user_id,favourite_ids)
}
function onError() {
alert("error");
}
function send_websql(user_id,favourite_ids){
$.ajax({
url: 'fct.import_websql.php',
type: 'GET',
data: {user_id: user_id, favourite_ids: favourite_ids},
dataType: 'json',
beforeSend: function(){
},
success: function(data)
{
if(data) {
alert(favourite_ids + "Worked!" + data);
}
else {
console.log("Error: " + data);
}
},
complete: function(data){
},
error: function(xhr,textStatus,err)
{
console.log("readyState: " + xhr.readyState);
console.log("responseText: "+ xhr.responseText);
console.log("status: " + xhr.status);
console.log("text status: " + textStatus);
console.log("error: " + err);
}
});
}
And my PHP looks like:
<?php
include_once('database_connect.php');
include_once('clean.php');
$user_id = clean($_GET['user_id']);
$favourite_ids = clean($_GET['favourite_ids']);
$favourite_ids_arr = explode('t', $favourite_ids);
array_pop($favourite_ids_arr);
foreach ($favourite_ids_arr as &$favourite_id) {
$sql = "INSERT INTO map_favourite_user_bookmark (map_favourite_user_bookmark_favourite_id, map_favourite_user_bookmark_user_id) VALUES ($favourite_id, $user_id)";
$result = mysql_query($sql) or die(mysql_error());
$sql = "UPDATE user_info SET user_websql_imported = 1 WHERE user_id = $user_id)";
$result = mysql_query($sql) or die(mysql_error());
}
$response = "ok" . $favourite_ids;
echo json_encode($response);
?>
'Funny' thing is that on the JS side before I send the data EVERYTHING exists (and would be alerted), but on the PHP side the favourite_ids are completely missing (can't echo them, can't process them, and they are not given back... like they don't exist).
What I'm doing wrong?
Your problem is that the database API is asynchronous, so you will execute your ajax call while the database transaction has not yet finished.
One way to solve it, is to put the ajax call in the callback of the query function.

How to access result array returned in ajax?

Arg!! I had this working flawlessly and now I am back to banging head against the keyboard.
I want access defined columns inside the array, but I am getting undefined but if I display the results using an alert as detailed in snipped of code below I see the following:
[{"firstname":" Mr","0":" Mr","lastname":" Two","1":" Two","user_public_info_id":"3","2":"3","st_usage_id":null,"3":null},{"firstname":" Mr","0":" Mr","lastname":" Three","1":" Three","user_public_info_id":"5","2":"5","st_usage_id":null,"3":null}]
***
g
***
e
***
undefined
Here is the Ajax code:
$.ajax({
type: "POST",
url: "models/ajaxHandler.php",
data: "handler=getStActivitySharingList&stu_id="+stu_id,
datatype: "json",
success: function(result){
var count = 0;
if (result !== null)
{
//display results
alert(result + " <br />*** <br />" + result[0] +" <br />*** <br />" + result[1] + " <br />*** <br />" + result[0]["firstname"]);
//clears choice list
clearOptions();
//result = $.parseJSON(result); //if this is used cannot display result again
alert (result);
$.each(result, function (i, elem) {
alert("elem"+elem.st_usage_id ); //displays as undefined and won't break
if (elem.st_usage_id === null)
{
count++;
alert(elem.firstname + " "+ elem.lastname + " " + elem.user_public_info_id);
appendOption(elem);
}
});
}
alert(count);
if (count === 0){
noResultsAvailableOption();
}else{
resultsAvailableOption();
}
ShowDialog(false);
e.preventDefault();
},
error: function(){
alert("ajax failure: could not retrieve a list of contacts");
}
});
i not know how you return it from PHP, but in jquery try:
sucess: function (result)
{
console.log(JSON.parse(result)); // parse string to json
}
See json.org
To better answer this question is to implement better debugging procedures.
Here is the code that I used for debugging this issue. The breaking down of the xmlHttpRequest clearly displayed to me that issue was with the data and that I was encountering an illegal character exception when trying to encode the data to json.
A great way to solve any issue is to first implement the correct debugging procedures, and everything else will work itself out.
error: function(xmlHttpRequest, status, error){
alert("ajax failure: could not populate list of countires | " + status + " | error:" + error);
var xmlHttpRequestStr= "";
for(x in xmlHttpRequest)
xmlHttpRequestStr = xmlHttpRequestStr + xmlHttpRequest[x];
alert(xmlHttpRequest);
}

Not getting data value from [object XMLDocument] after success Ajax

I have created a javascript and a WebMethod. It works in IE but not in firefox and chrome
MyWebMethod
[WebMethod]
public string Send(string name, string email, string message)
{
try
{
MailMessage objMailMessage = default(MailMessage);
objMailMessage = new MailMessage();
objMailMessage.From = new MailAddress(email, name,System.Text.Encoding.UTF8);
objMailMessage.To.Add("feedback#abc.in");
objMailMessage.Subject = "Feedback";
objMailMessage.Body = "<b>Name :</b> " + name + "<br/><br/>";
objMailMessage.Body += "<b>Email :</b> " + email + "<br/><br/>";
objMailMessage.Body+= "<b>Message :</b> "+message;
objMailMessage.IsBodyHtml = true;
objMailMessage.Priority = MailPriority.High;
CommonFunctions.CommonFunctions.SendEmailMessage(objMailMessage);
return "success";
}
catch (Exception ex)
{
Logger.Log.Error(ex);
return "Fail";
}
}
MYScript
$.ajax({
datatype: 'text',
type: 'POST',
url: options.url,
data: { name: $(this_id_prefix + '#name').val(), email: $(this_id_prefix + '#email').val(), message: $(this_id_prefix + '#message').val() },
success: function (data) {
$(this_id_prefix + '#loading').css({ display: 'none' });
var xmlDoc = data;
var returnvalue = xmlDoc.childNodes(1).firstChild.nodeValue;
if (returnvalue == "success") {
$(this_id_prefix+'#callback').show().append(options.recievedMsg);
setTimeout(function () {
$(this_id_prefix + '.holder').show();
$(this_id_prefix + '#callback').hide().html('');
}, 2000);
if(options.hideOnSubmit == true) {
//hide the tab after successful submition if requested
$(this_id_prefix+'#contactForm').animate({dummy:1}, 2000).animate({"marginLeft": "-=450px"}, "slow");
$(this_id_prefix+'div#contactable_inner').animate({dummy:1}, 2000).animate({"marginLeft": "-=447px"}, "slow").animate({"marginLeft": "+=5px"}, "fast");
$(this_id_prefix+'#overlay').css({display: 'none'});
}
} else {
$(this_id_prefix+'#callback').show().append(options.notRecievedMsg);
setTimeout(function(){
$(this_id_prefix+'.holder').show();
$(this_id_prefix+'#callback').hide().html('');
},2000);
}
},
error:function(){
$(this_id_prefix+'#loading').css({display:'none'});
$(this_id_prefix+'#callback').show().append(options.notRecievedMsg);
}
});
I am not able to get return value from webmethod to script. In Success funcation I want to check that if(data=="Success") but here I am not able to check that. Is there anything wrong in script like datatype or any other issue? Here var returnvalue = xmlDoc.childNodes(1).firstChild.nodeValue; is not working. It works locally fine but after publish to server it's not working. It return object xmldocument in data. It's not returing string. I have changed datatype to text

Categories

Resources