jQuery AJAX vs. XMLHttpRequest - javascript

Searching for an answer for this question
I got as a result that follwing code works fine:
xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
response = JSON.parse(xhr.responseText);
if(typeof response =='object') {
$('#modal-spinner-seo-update').hide('slow');
jQuery.each(result, function(field, message) {
$('#seo-'+field).next('div.error-message').html(message).fadeIn('fast');
});
} else {
$('#modal-spinner-seo-update').hide('slow', function() {
$("#seo-widget-message-success").fadeIn('slow').delay(2000).fadeOut('slow');
});
}
return false;
}
};
xhr.open('GET','/metas/saveMetas?model='+model+'&f_key='+f_key+'&pagetitle='+pagetitle+'&keywords='+keywords+'&description='+description+'&niceurl='+niceurl, true );
xhr.send();
but this jQuery Version does not work.
So can anyone spot the mistake? Is there any? The jQuery AJAX version works fine on my localhost but the server it does not, but return an 403 Forbidden Error. It is a cakePHP project.
So I hope someone ca tell me whats wrong or what setting is missing.
$.ajax({
url: '/metas/saveMetas',
data: {
"model": model,
"f_key": f_key,
"pagetitle": pagetitle,
"keywords": keywords,
"description": description,
"niceurl": niceurl
},
dataType: 'json',
complete: function(){
return false;
},
success: function(result) {
if(typeof result =='object') {
$('#modal-spinner-seo-update').hide('slow');
jQuery.each(result, function(field, message) {
$('#seo-'+field).next('div.error-message').html(message).fadeIn('fast');
});
} else {
$('#modal-spinner-seo-update').hide('slow', function() {
$("#seo-widget-message-success").fadeIn('slow').delay(2000).fadeOut('slow');
});
}
return false;
}
});

Something else to think about, in addition to the dataType:
Since it's returning a 403 error, have you added the 'saveMetas' method in the $this->Auth->allow() method in the beforeFilter() of 'MetasController' of your CakePHP project?
class MetasController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('saveMetas');
}
...
...
}
EDIT:
Since you said you have done this, do you have $this->autoRender = false; and $this->layout = 'ajax'; as well in your saveMetas function?
Lastly, since you can visit that page directly, do a pr( $this->request ) after the initial function call and visit the page without AJAX to see what it is telling you. 403 forbidden tells me it's a permissions issue.

Related

.NET MVC JSON Post Call response does not hit complete or success

I am new to .NET MVC so please bear with me.
I wrote a function that gets triggered when there is a blur action on the textarea control:
function extractURLInfo(url) {
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
complete: function (data) {
alert(data);
},
success: function (data) {
alert(data);
},
async: true
})
.done(function (r) {
$("#url-extracts").html(r);
});
}
jQuery(document).ready(function ($) {
$("#input-post-url").blur(function () {
extractURLInfo(this.value);
});
});
This works fine and will hit the controller:
[HttpPost]
public ActionResult Url(string url)
{
UrlCrawler crawler = new UrlCrawler();
if (crawler.IsValidUrl(url))
{
MasterModel model = new MasterModel();
model.NewPostModel = new NewPostModel();
return PartialView("~/Views/Shared/Partials/_ModalURLPartial.cshtml", model);
}
else
{
return Json(new { valid = false, message = "This URL is not valid." }, JsonRequestBehavior.AllowGet);
}
}
I get the intended results if the URL is valid; it will return a partialview to the .done() function and I just display it in code. However, if the URL is not valid i want it to hit either complete, success, or done (I have been playing around to see which it will hit but no luck!) and do something with the returned data. I had it at some point trigger either complete or success but the data was 'undefined'. Can someone help me out on this?
Thanks!
In both cases your controller action is returning 200 status code, so it's gonna hit your success callback:
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
success: function (data) {
if (data.message) {
// Your controller action return a JSON result with an error message
// => display that message to the user
alert(data.message);
} else {
// Your controller action returned a text/html partial view
// => inject this partial to the desired portion of your DOM
$('#url-extracts').html(data);
}
}
});
But of course a much better and semantically correct approach is to set the proper status code when errors occur instead of just returning some 200 status code:
[HttpPost]
public ActionResult Url(string url)
{
UrlCrawler crawler = new UrlCrawler();
if (crawler.IsValidUrl(url))
{
MasterModel model = new MasterModel();
model.NewPostModel = new NewPostModel();
return PartialView("~/Views/Shared/Partials/_ModalURLPartial.cshtml", model);
}
else
{
Response.StatusCode = 400;
Response.TrySkipIisCustomErrors = true;
return Json(new { valid = false, message = "This URL is not valid." }, JsonRequestBehavior.AllowGet);
}
}
and then in your AJAX call you would handle those cases appropriately:
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
success: function (data) {
$('#url-extracts').html(data);
},
error: function(xhr) {
if (xhr.status == 400) {
// The server returned Bad Request status code
// => we could parse the JSON result
var data = JSON.parse(xhr.responseText);
// and display the error message to the user
alert(data.message);
}
}
});
Also don't forget that you have some standard way of returning your error messages you could subscribe to a global .ajaxError() handler in jQuery instead of placing this code in all your AJAX requests.

Extending jQuery ajax success globally

I'm trying to create a global handler that gets called before the ajax success callback. I do a lot of ajax calls with my app, and if it is an error I return a specific structure, so I need to something to run before success runs to check the response data to see if it contains an error code bit like 1/0
Sample response
{"code": "0", "message": "your code is broken"}
or
{"code": "1", "data": "return some data"}
I can't find a way to do this in jQuery out of the box, looked at prefilters, ajaxSetup and other available methods, but they don't quite pull it off, the bets I could come up with is hacking the ajax method itself a little bit:
var oFn = $.ajax;
$.ajax = function(options, a, b, c)
{
if(options.success)
{
var oFn2 = options.success;
options.success = function(response)
{
//check the response code and do some processing
ajaxPostProcess(response);
//if no error run the success function otherwise don't bother
if(response.code > 0) oFn2(response);
}
}
oFn(options, a, b, c);
};
I've been using this for a while and it works fine, but was wondering if there is a better way to do it, or something I missed in the jQuery docs.
You can build your own AJAX handler instead of using the default ajax:
var ns = {};
ns.ajax = function(options,callback){
var defaults = { //set the defaults
success: function(data){ //hijack the success handler
if(check(data)){ //checks
callback(data); //if pass, call the callback
}
}
};
$.extend(options,defaults); //merge passed options to defaults
return $.ajax(options); //send request
}
so your call, instead of $.ajax, you now use;
ns.ajax({options},function(data){
//do whatever you want with the success data
});
This solution transparently adds a custom success handler to every $.ajax() call using the duck punching technique
(function() {
var _oldAjax = $.ajax;
$.ajax = function(options) {
$.extend(options, {
success: function() {
// do your stuff
}
});
return _oldAjax(options);
};
})();
Here's a couple suggestions:
var MADE_UP_JSON_RESPONSE = {
code: 1,
message: 'my company still uses IE6'
};
function ajaxHandler(resp) {
if (resp.code == 0) ajaxSuccess(resp);
if (resp.code == 1) ajaxFail(resp);
}
function ajaxSuccess(data) {
console.log(data);
}
function ajaxFail(data) {
alert('fml...' + data.message);
}
$(function() {
//
// setup with ajaxSuccess() and call ajax as usual
//
$(document).ajaxSuccess(function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
$.post('/echo/json/');
// ----------------------------------------------------
// or
// ----------------------------------------------------
//
// declare the handler right in your ajax call
//
$.post('/echo/json/', function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
});​
Working: http://jsfiddle.net/pF5cb/3/
Here is the most basic example:
$.ajaxSetup({
success: function(data){
//default code here
}
});
Feel free to look up the documentation on $.ajaxSetup()
this is your call to ajax method
function getData(newUrl, newData, callBack) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: newUrl,
data: newData,
dataType: "json",
ajaxSuccess: function () { alert('ajaxSuccess'); },
success: function (response) {
callBack(true, response);
if (callBack == null || callBack == undefined) {
callBack(false, null);
}
},
error: function () {
callBack(false, null);
}
});
}
and after that callback success or method success
$(document).ajaxStart(function () {
alert('ajax ajaxStart called');
});
$(document).ajaxSuccess(function () {
alert('ajax gvPerson ajaxSuccess called');
});

How to return a value inside AJAX function to parent in javascript?

I'm trying to return true or false to a function depending on the response of an AJAX function inside of it but I'm not sure how should I do it.
(function($) {
$('#example').ajaxForm({
beforeSubmit : function(arr, $form, options) {
var jsonStuff = JSON.stringify({ stuff: 'test' });
$.post('/echo/json/', { json: jsonStuff }, function(resp) {
if (resp.stuff !== $('#test').val()) {
// Cancel form submittion
alert('Need to type "test"');
return false; // This doesn't work
}
}, 'json');
},
success : function() {
alert('Form sent!');
}
});
})(jQuery);​
I made a fiddle to illustrate this better:
http://jsfiddle.net/vengiss/3W5qe/
I'm using jQuery and the Malsup's Ajax Form plugin but I believe this behavior is independent of the plugin, I just need to return false to the beforeSubmit function depending on the POST request so the form doesn't get submitted every time. Could anyone point me in the right direction?
Thanks in advance!
This is not possible to do when dealing with async functions. The function which calls post will return immediately while the ajax call back will return at some point in the future. It's not possible to return a future result from the present.
Instead what you need to do is pass a callback to the original function. This function will eventually be called with the result of the ajax call
var makePostCall = function(callback) {
$.post('/echo/json/', { json: jsonStuff }, function(resp) {
if (resp.stuff !== $('#test').val()) {
// Cancel form submittion
alert('Need to type "test"');
callback(false);
} else {
callback(true);
}}, 'json');
};
Then switch the code which expected a prompt response from makePostCall to using a callback instead.
// Synchronous version
if (makePostCall()) {
// True code
} else {
// false code
}
// Async version
makePostCall(function (result) {
if (result) {
// True code
} else {
// False code
}
});
you can put async:false parameter to ajax request then you can control future responce and send back the result to parent. see following main lines enclosed within ***
add: function (e, data) {
//before upload file check server has that file already uploaded
***var flag=false;***
$.ajax(
{
type: "POST",
dataType:'json',
url:"xyz.jsp",
***async:false,***
data:{
filename : upload_filename,
docname : upload_docname,
userid : upload_userid,
},
success:function(data)
{
***flag=true;***
},
error:function(request,errorType,errorMessage)
{
alert ('error - '+errorType+'with message - '+errorMessage);
}
});
***return flag;***
}

Fetch http status code in jquery

Below is an existing jquery code in our code base.
$("#download_").click( function() {
$("#error").html('');
$.ajax({
type : "GET",
cache : false,
async : false,
url : "/download",
success : function(data) {
var json_obj = $.parseJSON(data);
if(json_obj !== undefined && json_obj != null){
if(json_obj.download=="success"){
location=json_obj.url;
}
}
},
error : function(data) {
// TODO
$("#error").html(failed);
}
});
});
Here, In case of error (marked as TODO), I want to check if the http status is 404, then I need to redirect user to different url.
Can any one tell me how do I get the http status in this error: function(data) method?
Thanks!
Did you even look at the docs?
$.ajax({
...
statusCode: {
404: function() {
alert('page not found');
}
}
});
try: statusCode
from documentation:
$.ajax({
statusCode: {
404: function() {
alert('page not found');
}
}
});
http://api.jquery.com/jQuery.ajax/
EDIT:
Now that I think about it, do you only want to redirect if it's a 404? What about other error codes?

jQuery AJAX call into MVC controller action never returns

I've looked at the previously-posted jQuery/MVC questions and haven't found a workable answer.
I have the following JavaScript code:
appCode.runReports = function (e) {
var reportList = '';
$('.rptCheck:checked').each(function (index) {
reportList += ($(this).attr('reportName') + ',');
});
$.ajax({
url: '/Report/RunReports/?reports=' + reportList,
error: appCode.reportAjaxFailure,
success: appCode.listRunningReports,
complete: appCode.ajaxComplete,
dataType: 'json'
});
e.preventDefault();
}
$(document).ready(function () {
$('#runReportsButton').click(appCode.runReports);
});
The URL it calls into uses the following controller:
namespace workflowDemoMVC.Controllers
{
public class ReportController : Controller
{
public JsonResult RunReports(string reports = "")
{
try
{
var ret = reports.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
return Json(ret, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
ide.Trace.WriteLine(ex.ToString());
return Json(null, JsonRequestBehavior.AllowGet);
}
}
}
}
When I run the code in dev, the controller action executes as expected and returns, but none of the callbacks defined in the AJAX call (complete, error, or success) fire. Once, in an earlier code version, I saw an 500-coded exception (Internal Server Error,) but now I don't see anything at all.
Environment: MVC3, jQuery1.6 .net4
You should try and set the content type on the AJAX call. I had a problem like this and that fixed it for me. Basically you would do this. I know I had a lot of problems with IE until I specified this.
$.ajax({
url: '/Report/RunReports/?reports=' + reportList,
error: appCode.reportAjaxFailure,
success: appCode.listRunningReports,
complete: appCode.ajaxComplete,
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});

Categories

Resources