MooTools: How to use responseText directly - javascript

In following example of code, I want to traverse the responseText object which consist the html code came from request_page.php file. In onSuccess event, i want to check whether < Div > with id 'ersDiv' has any errors posted in it.
new Request.HTML({
url: 'request_page.php',
onSuccess: function(responseText, responseXML) {
// My expected code to handle responseText object
alert(errorMessage);
},
onFailure: function() { }
});
request_page.php file is like this :
<div align='center'><div id='ersDiv'>Page loaded with insufficient data</div></div>

try this for 1.2.x (example tweaked for the jsfiddle api):
new Request.HTML({
url: '/echo/html/',
method: "post",
data: {
html: "<div align='center'><div id='ersDiv'>Page loaded with insufficient data</div></div>",
delay: 1
},
onComplete: function(responseText, responseXML) {
var error, errors = responseXML.getElements("div").filter(function(el) {
return el.get("id") == "ersDiv";
});
if (errors.length) {
error = errors[0].get("text");
alert(error);
}
}
}).send();
working example:
http://www.jsfiddle.net/dimitar/vLgqB/
in 1.3 this can work as oskar suggested:
console.log($$(this.response.tree).getElement("#ersDiv")[0].get("text"));
http://www.jsfiddle.net/dimitar/vLgqB/2/
have fun.

function(responseText, responseXML) {
if (responseText.getElement('#ersDiv').get('text') === 'Page loaded with insufficient data'){
console.log('There was an error');
}
}
Btw. 1990 called, they want their align='center''s back :-)

Related

Why can't I wrap js promise resolve in a jquery object?

I wanted to be able to send the data from a successful jquery ajax call to other methods in my application because its quite large and it made coding sense to have one api method to work from, so I opted to try out promises. This is my first shot. I am getting some good results but clearly I am still a bit confused on context and timing.
When I run the following code, I am unable to wrap my return data from the ajax call as a jquery object without getting an error:
var widgetSystem={
listenForClick: function(){
$('div').on('click','a',function(){
var $selectTarget = $(this),
widgetid = $(this).data('widgetid');
apiRequestData = widgetSystem.makeApiRequestForSingleWidget(widgetid);
apiRequestData.then(function(result) {
widgetSystem.showWidget(result);
}).catch(function(e) {
console.log('no way big error ' +e);
});
});
},
makeApiRequest: function(widgetid){
return new Promise(function(resolve, reject) {
$.ajax({
method: "POST",
url: "localhost",
dataType: 'json',
data: {
data: {
widgetId: widgetid
},
action: 'apiMethod'
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
reject();
},
success: function (data) {
resolve(data);
}
});
});
},
showWidget: function(data){
$(data).appendTo('body');
//this causes an exception in my apiRequestData.then function in listenForClick
}
}
I am running un minified jquery and getting the following error in my console:
no way big error TypeError: context is undefined
I don't know exactly what your HTML looks like or how the API is set up, but assuming that the API is working correctly and the data sent via POST is correct, I was able to get it working using jsonplaceholder api with the following code (you can find it on JSbin).
var widgetSystem={
listenForClick: function(){
$('div').on('click','a',function(){
console.log('clicked');
var $selectTarget = $(this);
var widgetid = $(this).data('widgetid');
widgetSystem.makeApiRequest(widgetid)
.then(function(result) {
widgetSystem.showWidget(result);
return result;
})
.catch(function(e) {
console.log('no way big error ' +e);
});
});
},
makeApiRequest: function(widgetid){
return new Promise(function(resolve, reject) {
var root = 'http://jsonplaceholder.typicode.com';
$.ajax({
method: "POST",
url: root+'/posts/',
dataType: 'json',
data: {
userId:1,
title:"Havanagila",
body:"Testing the greatness"
},
success: function(xData, status){
resolve(xData);
//reject('whoops');
},
error: function(xhr, status, error){
reject(status);
}
});
});
},
showWidget: function(data){
$('#space').append(document.createTextNode(JSON.stringify(data)));
}
}
widgetSystem.listenForClick()
I don't think there is an issue which how you are calling resolve(data) within the ajax success callback. There may be an issue with the data being sent to your API such that the error callback is called, which in turn calls reject and causes the callback passed to .catch to be called instead of the intended callback passed to .then.

Accessing json object values in JavaScript

I am trying to build a WebApp which consumes REST API's with Flask.
I am getting my JSON object back successfully from my API but I am unable to display it in the HTML UI.
Consider I am trying to print userid from the JSON file, I am getting the error part only.
Can someone please point me out what is going wrong :
Here is my JSON Object which returns:
Here is my JS file:
$(document).ready(function() {
console.log("ready!");
$('#try-again').hide();
// on form submission ...
$('form').on('submit', function() {
console.log("the form has beeen submitted");
// grab values
valueOne = $('input[name="location"]').val();
console.log(valueOne)
$.ajax({
type: "POST",
url: "/",
data : { 'first': valueOne},
success: function(result) {
if (!$.isEmptyObject({result})) {
$('input').hide();
$('#try-again').show();
$('#result').html(result.userid[0])
$(document).ready(function() {
console.log("ready!");
$('#try-again').hide();
// on form submission ...
$('form').on('submit', function() {
console.log("the form has beeen submitted");
// grab values
valueOne = $('input[name="location"]').val();
console.log(valueOne)
$.ajax({
type: "POST",
url: "/",
data : { 'first': valueOne},
success: function(result) {
if (!$.isEmptyObject({result})) {
$('input').hide();
$('#try-again').show();
$('#result').html(result.userid)
$('#result').html('result.userid')
} else {
$('#result').html('Something went terribly wrong! Please try again.')
}
},
error: function(error) {
console.log(error)
}
});
});
$('#try-again').on('click', function(){
$('input').val('').show();
$('#try-again').hide();
$('#result').html('');
});
});
} else {
$('#result').html('Something went terribly wrong! Please try again.')
}
},
error: function(error) {
console.log(error)
}
});
});
$('#try-again').on('click', function(){
$('input').val('').show();
$('#try-again').hide();
$('#result').html('');
});
});
My JSON DATA:
[{"case": 2005608875,
"filepath": "/x/eng/cs-data/latx/dev/20150510_uploads/wilp/perfstat_20150415_001256/node/10.95.172.19/output.data",
"datatype": "perf8",
"perfdateend": "2015-04-15T02:15:37-04:00",
"userid": "wilp",
"filename": "perfstat_20150415_001256.zip",
"version": "v8.1 ",
"perfdate": "2015-04-15T01:14:24-04:00"}]
There are a couple of issues here, and none of them have anything to do with Flask.
You check the length of the returned JSON object. However, in JS objects do not have a length property, so result.length returns undefined which is not greater than 0.
Since you are using jQuery, you can use its isEmptyObject function to check that your object is not empty.
Also, inside that if statement you are inserting the literal string 'result.userid' into your HTML, instead of the actual userid value of the returned JSON.
if (!$.isEmptyObject(result)) {
...
$('#result').html(result.userid)
}

Using custom function as parameter for another

I'm currently dealing with refactoring my code, and trying to automate AJAX requests as follows:
The goal is to have a context-independent function to launch AJAX requests. The data gathered is handled differently based on the context.
This is my function:
function ajaxParameter(routeName, method, array, callback){
//Ajax request on silex route
var URL = routeName;
$.ajax({
type: method,
url: URL,
beforeSend: function(){
DOM.spinner.fadeIn('fast');
},
})
.done(function(response) {
DOM.spinner.fadeOut('fast');
callback(response);
})
.fail(function(error){
var response = [];
response.status = 0;
response.message = "Request failed, error : "+error;
callback(response);
})
}
My problem essentially comes from the fact that my callback function is not defined.
I would like to call the function as such (example)
ajaxParameter(URL_base, 'POST', dataBase, function(response){
if(response.status == 1 ){
console.log('Request succeeded');
}
showMessage(response);
});
I thought of returning response to a variable and deal with it later, but if the request fails or is slow, this won't work (because response will not have been set).
That version would allow me to benefit the .done() and .fail().
EDIT : So there is no mistake, I changed my code a bit. The goal is to be able to deal with a callback function used in both .done() and .fail() context (two separate functions would also work in my case though).
As far as I can see there really is nothing wrong with your script. I've neatened it up a bit here, but it's essentially what you had before:
function ajaxParameter (url, method, data, callback) {
$.ajax({
type: method,
url: url,
data: data,
beforeSend: function(){
DOM.spinner.fadeIn('fast');
}
})
.done( function (response) {
DOM.spinner.fadeOut('fast');
if (callback)
callback(response);
})
.fail( function (error){
var response = [];
response.status = 0;
response.message = "Request failed, error : " + error;
if (callback)
callback(response);
});
}
And now let's go and test it here on JSFiddle.
As you can see (using the JSFiddle AJAX API), it works. So the issue is probably with something else in your script. Are you sure the script you've posted here is the same one you are using in your development environment?
In regards to your error; be absolutely sure that you are passing in the right arguments in the right order to your ajaxParameter function. Here's what I am passing in the fiddle:
the url endpoint (e.g http://example.com/)
the method (e.g 'post')
some data (e.g {foo:'bar'})
the callback (e.g function(response){ };)
Do you mean something like this, passing the success and fail callbacks:
function ajaxParameter(routeName, method, array, success, failure) {
//Ajax request on silex route
var URL = routeName;
$.ajax({
type: method,
url: URL,
beforeSend: function () {
DOM.spinner.fadeIn('fast');
}
}).done(function (response) {
DOM.spinner.fadeOut('fast');
success(response);
}).fail(function (error) {
var response = [];
response.status = 0;
response.message = "Request failed, error : " + error;
failure(response);
})
}
Called like:
ajaxParameter(
URL_base,
'POST',
dataBase,
function(response){
//success function
},
function(response){
// fail function
}
);

How to capture the 500 error message using jquery?

How can i capture the 500 error message using jquery? I want to keep on checking for the 500 error message for sometime until it changes and time out after 50 sec.
I used the code below to try to capture and check the 500 error message but it doesnt seem to catch the 500 error message. I can see it in the firebug
$.ajax({
statusCode: {
500: function() {
alert(" 500 data still loading");
console.log('500 ');
}
}
});
Dispite the accepted answer mentioned by #Danny, you can also do this in newer versions of jQuery.
var xhr = $.ajax({
url: "somewhere"
});
xhr.fail(function(xhr, textStatus, error) {
// Error handling stuff here ...
});
See Deferred Object.
Are you missing url in $.ajax like the one below
$.ajax({
url: "/path to page",
statusCode: {
500: function() {
alert(" 500 data still loading");
console.log('500 ');
}
}
});
You can check the status in error of ajax post please check the below code.
$.ajax({
.....
success: function (data) {
},
complete: function (XMLHttpRequest, textStatus) {
},
error: function (e, status) {
if (e.status == 404)
alert("404 error");
}
});
Thanks

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?

Categories

Resources