Facebook wall post using ajax post request inconsistent with Chrome and IE - debugging

I am using the posted code for posting content to a Facebook wall.
FB.init({ appId: 'my app id', status: true, cookie: true, xfbml: true, oauth: true })
$('#share_button').click(function (e) {
if ($('#textfield').val() != 'Whats Happening' && $('#textfield').val() != '') {
var lin = window.location.href;
FB.login(function (response) {
if (response.authResponse) {
console.log("User is connected to the application.");
var accessToken = response.authResponse.accessToken;
var fbURL = "https://graph.facebook.com/me/feed?access_token=" + accessToken;
$.ajax({
url: fbURL,
data: "message=" + $('#textfield').val() + "&picture=MyUrl/images/logo.png&name=FutureZoom&link=MyUrl",
type: 'POST',
success: function (resp) {
$('#ValidationMessage').html(' Post has been shared on your wall!')
.css('color', 'green');
setTimeout(function () {
$('#ValidationMessage').html('');
}, 3000);
},
error: function (request, status, error) {
alert("Facebook Error : \n" + request.responseText + '\n' + status + '\n' + error);
}
});
}
}, { scope: 'publish_stream' });
}
else {
$('#ValidationMessage').html(' Please write something to share!')
.addClass('red');
}
});
Above is working fine in Firefox browser but problem is with IE and Chrome.
In Chrome, above code posts the comment on wall but when returns, it goes into error block instead of success. Below is the error getting in chrome.
Facebook Error:
{
"id": "100002506055900_30229318964214"
}
parseerror
SyntaxError: Unexpected token:
And in IE, nothing happens. Neither posts the comment nor returns in error/success block.
What could be reason?

Instead of doing a AJAX call to post something to the user's timeline, you should use the FB.api function in the Facebook JavaScript SDK instead. It simplifies the process:
FB.api('/me/feed', 'post', { message: body, picture: pic }, function(response) {
if ( !response || response.error ) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
You can see the documentation for the JS call here: http://developers.facebook.com/docs/reference/javascript/FB.api/
You will be able to reduce your code quite a bit by using this method.

Related

How to get(handle) Error (Not Acceptable & Internal Server Error) Exception content in Ajax

I added internal Error (throw exception) in server side. Now I want to handle this error in client side. However , I get error content undefined.
I am using Postman , and see my response is JSON format, it has response parameter like "Message". I tried to parse JSON , and again I got Cannot read property 'Message' of undefined
Ajax function defined like this:
function Ajax(url, method, json, successFunction, errorFunction, skipErrorDlg) {
$.ajax({
url: url,
data: json,
type: method,
contentType: 'application/json',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', GlobalAuthToken);
},
processData: false,
dataType: 'json',
success: function (data) {
successFunction(data);
},
error: function(event, jqxhr, settings, thrownError) {
if (errorFunction != null) {
errorFunction();
}
}
});
}
I used this function in my code , error part like this, In this function how can I get exception content?
function(event, jqxhr, settings, thrownError)
{
alert("ERROR HAPPENED");
var responseString = JSON.stringify(event);
alert(responseString.Message);
alert("event" + event.Message);
},
Postman Result:
{
"Message": "Please select corresponding template."}
Expected Result should be : Please select corresponding template.
I solved the problem, if you face this kind problem , trying like this:
function showAjaxError(event, jqxhr, settings, thrownError) {
var msg = "";
if (event.hasOwnProperty('responseJSON')) {
var resp = event['responseJSON'];
msg = (resp && resp.hasOwnProperty('Message')) ? resp.Message : "";
msg = msg + ((resp && resp.hasOwnProperty('ExceptionMessage')) ? "\n\n" + resp.ExceptionMessage : "");
if (resp && resp.hasOwnProperty('InnerException')) {
msg = msg + ((resp && resp.InnerException.hasOwnProperty('ExceptionMessage')) ? "\n\n" + resp.InnerException.ExceptionMessage : "");
}
} else {
msg = event.responseText;
}
}

Does Vue.JS work with AJAX http calls?

I am trying to do the following from my HTML:
var vm = new Vue({
el: '#loginContent',
data: {
main_message: 'Login',
isLoggedIn: false,
loginError: '',
loginButton:'Login'
},
methods: {
onLogin: function() {
//this.$set(loginSubmit, 'Logging In...');
var data = {
email: $('#email').val(),
password: $('#password').val(),
};
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then(function (response) {
if(response.error) {
console.err("There was an error " + response.error);
this.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
this.isLoggedIn = true;
} else {
this.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
}
}
});
Basically user presses the login button, onLogin method is called that sends a post to my API. The post is working fine and I do get the response back in the .then() promise.
But, trying to do things like this.isLoggedIn = true; does not update my DOM with what I am expecting the HTML to do when the user logs in.
Could be that I am in some sort of background thread (sorry, mobile developer here) when I get the response in the promise and it can't find the "vm" instance?
Thanks
It is probably happening because your this is not pointing to correct scope, scope of this changes inside an $.ajax call, so you just have to do something like following:
methods: {
onLogin: function() {
//this.$set(loginSubmit, 'Logging In...');
var data = {
email: $('#email').val(),
password: $('#password').val(),
};
var that = this
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then(function (response) {
if(response.error) {
console.err("There was an error " + response.error);
that.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
that.isLoggedIn = true;
} else {
that.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
}
}
I would propose another method use ES6 Arrow Functions like '=>'. It is simple and do not need extra variable.Like following:
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then((response) => {
if(response.error) {
console.err("There was an error " + response.error);
this.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
this.isLoggedIn = true;
} else {
this.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
You might want to take a look at axios. I used $.ajax and got it working, but found axios and prefer axios over the ajax library.

Ext.Msg.show in ajax not append the page

I have a function for saving data. Before saving data there is dialog confirmation Yes or No. While I click option Yes the page behind this is back to the gridview (it's list). What i want is while click Yes the page behind is not change.
This is my function :
function SaveData(StatusSubmit) {
var d = ControlToData();
if (state == FormState.ADD) {
ShowLoading("sa-body", "Updating data .. Please Wait ...");
$.ajax({
url: root + "PF/Add?status=" + StatusSubmit,
type: 'POST',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(d),
success: function (result, status, xhr) {
storePF.add(
{
PFID: result.PF.PFID
, Title: result.PF.Title
});
ChangeFormState(FormState.VIEW);
tabs.setActiveTab('pageGrid');
if (result.ErrorMail.length > 0) {
alert("Error while sending email !\nError description : " + result.ErrorMail + "\nPlease contact your System Administrator !");
}
if (result.Error.length > 0) {
var str = "<br/><br/><span style='color:red;font-weight:bold'>Success add new PF !</span>";
MsgBox2("Budget Validation", result.Error + str);
}
else
MsgBox("Success add new PF !");
},
complete: function () {
HideLoading();
}
});
}
}
I add new dialog confirmation like this, but it does not work (didn't append the page after click Yes button):
function SaveData(StatusSubmit) {
var d = ControlToData();
if (state == FormState.ADD) {
ShowLoading("sa-body", "Updating data .. Please Wait ...");
$.ajax({
url: root + "PF/Add?status=" + StatusSubmit,
type: 'POST',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(d),
success: function (result, status, xhr) {
storePF.add(
{
PFID: result.PF.PFID
, Title: result.PF.Title
});
ChangeFormState(FormState.VIEW);
tabs.setActiveTab('pageGrid');
if (result.ErrorMail.length > 0) {
alert("Error while sending email !\nError description : " + result.ErrorMail + "\nPlease contact your System Administrator !");
}
if (result.Error.length > 0) {
$.post(root + "PF/GetSetupName", function (datas) {
if (datas == "FILTER_BRAND") {
Ext.Msg.show({
title: 'Over Budget',
msg: 'Budget is over. Modify or Not ?',
fn: function (btn) {
if (btn == "yes") {
SaveData("none");
}
else {
CancelData();
}
},
buttons: Ext.Msg.YESNO,
icon: Ext.Msg.QUESTION
});
}
});
}
else
MsgBox("Success add new PF !");
},
complete: function () {
HideLoading();
}
});
}
}
I try also separate this Ext.Msg.show in another function. but it doesn't work. Is there any idea please ?
I've found that when I try to do a mask and an ajax request at the same time, Ext gets overwhelmed and will not properly display the mask.
To fix this, I delay doing my ajax request until Ext & the browser have had enough time to properly display the mask. It generally does not need much time. In the example below, it waits 50 ms before posting.
Ext.get(document.body).mask("Updating data .. Please Wait ...", 'x-mask-loading');
Ext.defer(function() {
Ext.Ajax.request({ ... });
}, 50);
This gives the browser enough time to render the masking before it has to do anything else.

Unexpected token for ajax request

I am using json with jquery's ajax. There are two options for results in this code:
one of them null result
one of them is html result for example ...
When I used firefox this code result not enter if(sdata!="") or sdata!=null
If I try to return with json type it's return, but I don't return html token. It returns an exception
unexcepted token <
How can I solve?
$.ajax({
url: '#Url.Action("RefreshPage", "VeriAktarim")',
type: "POST",
data: { key: id },
success: function (sdata) {
if (sdata != "") {
$("#" + change).closest("tr").replaceWith(sdata);
}
},
error: function (req, status, error) {
alert(status + "error" + error);
}
});

Can I return custom error from JsonResult to jQuery ajax error method?

How can I pass custom error information from an ASP.NET MVC3 JsonResult method to the error (or success or complete, if need be) function of jQuery.ajax()? Ideally I'd like to be able to:
Still throw the error on the server (this is used for logging)
Retrieve custom information about the error on the client
Here is a basic version of my code:
Controller JsonResult method
public JsonResult DoStuff(string argString)
{
string errorInfo = "";
try
{
DoOtherStuff(argString);
}
catch(Exception e)
{
errorInfo = "Failed to call DoOtherStuff()";
//Edit HTTP Response here to include 'errorInfo' ?
throw e;
}
return Json(true);
}
JavaScript
$.ajax({
type: "POST",
url: "../MyController/DoStuff",
data: {argString: "arg string"},
dataType: "json",
traditional: true,
success: function(data, statusCode, xhr){
if (data === true)
//Success handling
else
//Error handling here? But error still needs to be thrown on server...
},
error: function(xhr, errorType, exception) {
//Here 'exception' is 'Internal Server Error'
//Haven't had luck editing the Response on the server to pass something here
}
});
Things I've tried (that didn't work out):
Returning error info from catch block
This works, but the exception can't be thrown
Editing HTTP response in catch block
Then inspected xhr in the jQuery error handler
xhr.getResponseHeader(), etc. contained the default ASP.NET error page, but none of my information
I think this may be possible, but I just did it wrong?
You could write a custom error filter:
public class JsonExceptionFilterAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new
{
// obviously here you could include whatever information you want about the exception
// for example if you have some custom exceptions you could test
// the type of the actual exception and extract additional data
// For the sake of simplicity let's suppose that we want to
// send only the exception message to the client
errorMessage = filterContext.Exception.Message
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
}
and then register it either as a global filter or only apply to particular controllers/actions that you intend to invoke with AJAX.
And on the client:
$.ajax({
type: "POST",
url: "#Url.Action("DoStuff", "My")",
data: { argString: "arg string" },
dataType: "json",
traditional: true,
success: function(data) {
//Success handling
},
error: function(xhr) {
try {
// a try/catch is recommended as the error handler
// could occur in many events and there might not be
// a JSON response from the server
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
} catch(e) {
alert('something bad happened');
}
}
});
Obviously you could be quickly bored to write repetitive error handling code for each AJAX request so it would be better to write it once for all AJAX requests on your page:
$(document).ajaxError(function (evt, xhr) {
try {
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
} catch (e) {
alert('something bad happened');
}
});
and then:
$.ajax({
type: "POST",
url: "#Url.Action("DoStuff", "My")",
data: { argString: "arg string" },
dataType: "json",
traditional: true,
success: function(data) {
//Success handling
}
});
Another possibility is to adapt a global exception handler I presented so that inside the ErrorController you check if it was an AJAX request and simply return the exception details as JSON.
The advice above wouldn't work on IIS for remote clients. They will receive a standard error page like 500.htm instead of a response with a message.
You have to use customError mode in web.config, or add
<system.webServer>
<httpErrors existingResponse="PassThrough" />
</system.webServer>
or
"You can also go into IIS manager --> Error Pages then click on the
right on "Edit feature settings..." And set the option to "Detailed
errors" then it will be your application that process the error and
not IIS."
you can return JsonResult with error and track the status at javascript side to show error message :
JsonResult jsonOutput = null;
try
{
// do Stuff
}
catch
{
jsonOutput = Json(
new
{
reply = new
{
status = "Failed",
message = "Custom message "
}
});
}
return jsonOutput ;
My MVC project wasn't returning any error message (custom or otherwise).
I found that this worked well for me:
$.ajax({
url: '/SomePath/Create',
data: JSON.stringify(salesmain),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
alert("start JSON");
if (result.Success == "1") {
window.location.href = "/SomePath/index";
}
else {
alert(result.ex);
}
alert("end JSON");
},
error: function (xhr) {
alert(xhr.responseText);
}
//error: AjaxFailed
});
Showing the xhr.responseText resulted in a very detailed HTML formatted alert message.
If for some reason you can't send a server error. Here's an option that you can do.
server side
var items = Newtonsoft.Json.JsonConvert.DeserializeObject<SubCat>(data); // Returning a parse object or complete object
if (!String.IsNullOrEmpty(items.OldName))
{
DataTable update = Access.update_SubCategories_ByBrand_andCategory_andLikeSubCategories_BY_PRODUCTNAME(items.OldName, items.Name, items.Description);
if(update.Rows.Count > 0)
{
List<errors> errors_ = new List<errors>();
errors_.Add(new errors(update.Rows[0]["ErrorMessage"].ToString(), "Duplicate Field", true));
return Newtonsoft.Json.JsonConvert.SerializeObject(errors_[0]); // returning a stringify object which equals a string | noncomplete object
}
}
return items;
client side
$.ajax({
method: 'POST',
url: `legacy.aspx/${place}`,
contentType: 'application/json',
data: JSON.stringify({data_}),
headers: {
'Accept': 'application/json, text/plain, *',
'Content-type': 'application/json',
'dataType': 'json'
},
success: function (data) {
if (typeof data.d === 'object') { //If data returns an object then its a success
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000
})
Toast.fire({
type: 'success',
title: 'Information Saved Successfully'
})
editChange(place, data.d, data_);
} else { // If data returns a stringify object or string then it failed and run error
var myData = JSON.parse(data.d);
Swal.fire({
type: 'error',
title: 'Oops...',
text: 'Something went wrong!',
footer: `<a href='javascript:showError("${myData.errorMessage}", "${myData.type}", ${data_})'>Why do I have this issue?</a>`
})
}
},
error: function (error) { console.log("FAIL....================="); }
});

Resources