jquery xml exists - javascript

I want to use javascript / jquery to determine if an xml file exists.
I don't need to process it; I just need to know whether it's available or not,but I can't seem to find a simple check.
Here is what I've tried:
jQuery.noConflict();
jQuery(document).ready(function(){
var photo = '223';
var exists = false;
jQuery.load('/'+photo+'.xml', function (response, status, req) {
if (status == "success") {
exists = true;
}
});
});

Assuming you are talking about an xml file on the server, you could do a ajax request and then write a custom error handler to check the error response message. You'll need to know what the exact error message code is for a missing file (usually 404). You can use Firebug Console to check what the exact error message and code is.
$.ajax({
type: "GET",
url: "text.xml",
dataType: "xml",
success: function(xml) {
alert("great success");
},
error: function(xhr, status, error) {
if(xhr.status == 404)
{
alert("xml file not found");
} else {
//some other error occured, statusText will give you the error message
alert("error: " + xhr.statusText);
}
} //end error
}); //close $.ajax(

Your question isn't clear to me. If I understand, you want to verify whether a file (the XML) is present or not in the HTTP server.
That's correct? If so, you can just do:
$.get('url-to-file.xml', function(response, status, req) {
if (status == 'success') {
alert('exists');
}
});
EDITED: As pointed by #lzyy on comments, .get() only calls the callback upon success. However, I'd stick to the .load() using $(document) as selector. See:
$(document).load('url-to-file.xml', function(response, status, req) {
if (status == 'success') {
alert('exists');
} else if (status == 'error') {
alert('doesnt exist');
}
});

Related

jquery ajax post sends me to action page and wont show result data

I have the following script for making Ajax/Jquery post request.
The script works (I get correct response on back-end).
But I cant seem to make any alerts, so I think there is some problem with the success function.
Do you guys see any obvious mistakes?
The browser gets the correct responses (Inspect webpage in chrome).
<script>
$(document).ready(function() {
var frm = $('#registerform');
frm.submit(function(x) {
x.preventDefault();
$.ajax({
type: 'POST',
url: 'http://localhost:8080/api/v1/register',
data: frm.serialize(),
crossDomain: true,
success: function(data){
if(data == 200){
alert("successfully registered");
$('#alert').append("successfully registered");
}
if (data == 400){
alert("email or password empty");
}
if(data == 403){
alert("passwords do not match");
}
}
});
});
});
</script>
You are trying to compare your data that you are getting back from your request with HTTP status codes. So, what you need do is put in some additional parameters in your success function. Here is a nice Fiddle that I seen on another stackoverflow question that might help you out. http://jsfiddle.net/magicaj/55HQq/3/.
$.ajax({
url: "/echo/xml/",
type: "POST",
data: {
//Set an empty response to see the error
xml: "<response></response>"
},
dataType:"text xml",
success: function(xml, textStatus, xhr) {
console.log(arguments);
console.log(xhr.status);
}
});
The xhr.status is what you will need to compare against instead of your data.
When playing with console.log i found out that sending res.sendStatus(200) from the backend results in the client (browser) getting the response "OK". So when changing to res.json on the server it works...

PHP directing to error 404 not working

I have 2 files time.html and time.php. I am trying to show server date and users date(I use JS for this) in time.html. In php I create random number from 1 to 5 and if number is equal or greater than 3, php should wait 5s then show error 404.
NOTE: if random is smaller than 3 everything works perfectly
PHP:
<?php
$rnd = rand(1, 5);
if ($rnd >= 3) {
sleep(5);
header("HTTP/1.0 404 Not Found");
}
if ($rnd < 3) {
sleep(3);
$tz = date_default_timezone_get();
date_default_timezone_set($tz);
$time = date('d.m.Y H:i:s');
echo "Timezone: " . $tz . ". On date: " . $time;
}
?>
jQuery:
$(document).ready(function () {
$("button").click(function () {
$.ajax({
type: 'POST',
url: 'time.php',
success: function (data) {
$("span").text(data);
}
});
document.getElementById("jsTime").innerHTML += Date();
});
});
That is because when server responds with an error, jquery.ajax runs the error function, which means your success function does not run. See error on api.jquery.com/jquery.ajax/#jQuery-ajax-settings
$(document).ready(function () {
$("button").click(function () {
$.ajax({
type: 'POST',
url: 'time.php',
success: function (data) {
$("span").text(data);
},
error: function(jqxhr){
//redirect to 404 page on 404 error
if(jqxhr.status == 404){
window.location.href="HTTP/1.0 404 Not Found";
}
}
});
document.getElementById("jsTime").innerHTML += Date();
});
});
As said, when the server returns an error and the request fails, Jquery Ajax let you handle this error with the error function;
Try to add a couple of options more in the settings:
add the error function.
add the statusCode object and play with it; This lets you have more structured control over the error handling.
So:
$("button").click(function () {
$.ajax({
type: 'POST',
url: 'time.php',
success: function (data) {
console.info('success');
$("span").text(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.info(jqXHR.responseText);
console.info(jqXHR.status);
console.info(textStatus);
console.info(errorThrown);
$("span").text(jqXHR.responseText);
},
statusCode: {
404: function() {
alert( "page not found" );
}
}
});
document.getElementById("jsTime").innerHTML += Date();
});
and modify the if inside the php file:
if ($rnd >= 3) {
sleep(1);
echo "my response text";
header("HTTP/1.0 404 Damn, Not Found"); //just for playing, then keep with HTTP standard description
}
Quoting the jQuery.ajax documentation:
error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown ) A
function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a
string describing the type of error that occurred and an optional
exception object, if one occurred. Possible values for the second
argument (besides null) are "timeout", "error", "abort", and
"parsererror". When an HTTP error occurs, errorThrown receives the
textual portion of the HTTP status, such as "Not Found" or "Internal
Server Error." As of jQuery 1.5, the error setting can accept an array
of functions. Each function will be called in turn.
Note: This handler
is not called for cross-domain script and cross-domain JSONP requests.
Try to return the data to jquery in array like
$str[0]=true/false;
$str[1]="HTTP/1.0 404 Not Found"/"Timezone: " .$tz . ". On date: ".$time
In success check the condition
success: function (data) {
if(data[0]==true){
$("span").text(data[1]);
}else{
window.location.href="HTTP/1.0 404 Not Found";
}
i think so ajax call must be completed to redirect, above code works in my machine

Error handling for jQuery ajax load()

I am loading ajax load
function ajaxPageFilter(filterDiv, filterLink, filterName, loaderDivId, loaderId) {
jQuery("#" + filterDiv).load(filterLink, {'filterName': filterName}, function(data) {
jQuery("img.lazy").lazyload({effect : "fadeIn"});
jQuery('#'+loaderDivId).remove();
jQuery('#'+loaderId).remove();
});
}
Is there a way to do error handling for ajax load, in case if it fails.
thanks
You can capture the status argument in your callback, and have a condition to check if there is an error.
jQuery("#" + filterDiv).load(filterLink, {'filterName': filterName}, function(data, status) {
if(status == "error"){
// do something
} else {
jQuery("img.lazy").lazyload({effect : "fadeIn"});
jQuery('#'+loaderDivId).remove();
jQuery('#'+loaderId).remove();
}
});

$.ajax not working first time

I have a button in html page.
<input type="image" src="images/login_button.png" id="imageButton" onclick="LoginButtonClick();" />
I am calling this method on button click:
LoginButtonClick = function() {
alert ("Button click event raised"); // this alert msg raising every time when onclick event occurs.
$.ajax({
alert ("Inside Ajax."); // This alert not executing first 1 or 2 times.
type: 'GET',
url: 'http://URL/Service.svc/LoginValidation',
dataType: 'json',
error: pmamml.ajaxError,
success: function(response, status, xhr) {
if (response != "") {
alert ("Response receive ");
}
else {
alert("Invalid Data.");
}
}
});
}
As I mentioned above $.ajax not working first 2 , 3 button click attempts.
In mozilla it throws an error "[Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: JQuery.js :: :: line 20" data: no]"
Is there any way to fix this issues..
I'm not sure why it is executing later. But here's the deal--you're placing the alert in the object literal that defines the parameters for the .ajax method. It doesn't belong there. Try putting the alert in your success and/or error handlers.
UPDATE
How long are you waiting? When you initiate an ajax request, it isn't going to hang the UI. It could be that you're seeing the result of the first click on your 3rd or 4th attempt and think that you're triggering it on that 3rd or 4th attempt.
The $.ajax() function receives as a parameter a set of key/value pairs that configure the Ajax request. I don't think that the syntax will be correct by placing the alert() in there.
Note - entering an absolute path isnt going to work if the domain is not the current one - it is against the Same Origin Policy that browsers adhere too - this might explain why nothing happens when its executed - i suggest you look in your browser debugger to verify.
You should be binding the click event like this :
$(document).ready(function() {
$('#imageButton').click(function() {
// code here
});
});
so your complete code will look like this :
HTML
<input type="image" src="images/login_button.png" id="imageButton" />
JavaScript
$(document).ready(function () {
$('#imageButton').click(function () {
alert("Button click event raised"); // this alert msg raising every time when onclick event occurs.
$.ajax({
type: 'GET',
url: 'http://URL/Service.svc/LoginValidation',
dataType: 'json',
error: pmamml.ajaxError,
success: function (response, status, xhr) {
if (response != "") {
alert("Response receive ");
} else {
alert("Invalid Data.");
}
}
});
});
});
I have removed the alert ("Inside Ajax."); line as this will not be executed - you pass an object {} of parameters not code to execute. If you want to execute before the ajax request is sent do this :
$.ajax({
beforeSend: function() {
alert('inside ajax');
}
// other options here
});
Docs for the $.ajax() function are here
I agree that you have the second alert in the wrong place, and dont know what pmamml.ajaxError function is but may be your call returns with error and therefore your success alerts are not firing. You can check with error and complete functions as follows:
LoginButtonClick = function() {
alert ("Button click event raised"); // this alert msg raising every time when onclick event occurs.
$.ajax({
type: 'GET',
url: 'http://URL/Service.svc/LoginValidation',
dataType: 'json',
error: function(jqXHR, textStatus, errorThrown){
alert ("ajax call returns error: " + errorThrown);
},
success: function(response, status, xhr) {
if (response != "") {
alert ("Response receive ");
}
else {
alert("Invalid Data.");
}
},
complete:function(jqXHR, textStatus){
alert('completed with either success or fail');
}
});
}
You can test with Google Chrome's Developer tools -> Network tab, if a request is made and returned (https://developers.google.com/chrome-developer-tools/docs/network)

AJAX request confusion in jQuery

I am unable to understand that why the jquery AJAX is not fetching data from the ajax page.
Can someone please help.
<script type="text/javascript">
$(function() {
$('#lms_id').change(function(){
if ($(this).val() != "") {
// alert("1");
} else {
// alert("0");
}
});
$('#lms_user_role_id').change(function(){
if (($(this).val() == "7" || $(this).val() == "8")) {
$('#t_lms_dealers').show();
} else {
$('#t_lms_dealers').hide();
}
});
});
function loadAjax(message)
{
//alert(message);
//$.get("<?php echo $App['wwwroot'].'er.php' ?>?activity="+message);
$.get("http://www.abc.loc/er.php");
}
</script>
In loadAjax function, alert is alerting fine, but only the AJAX part is not working.
How do you know it is "not working"?
$.get("http://www.abc.loc/lmsapi/LMS_L2/templates/admin/user/tpl.user_dealer.php");
Even if it did, this statement would accomplish nothing. You need to put a handler in there:
$.get(
"http://www.abc.loc/lmsapi/LMS_L2/templates/admin/user/tpl.user_dealer.php",
function (data) {
alert("Retrieved :"+data);
}
);
You should also use some kind of in browser developer tool (eg, firebug) that will allow you to trace the request in real time. Finally, the plain jquery get lacks an error handler; you might want to instead use:
$.ajax ({
url: "http://www.abc.loc/lmsapi/LMS_L2/templates/admin/user/tpl.user_dealer.php",
success: function (data) {
alert(data);
},
error: function (xhr, err, code) {
alert("Error: "+err);
}
});
And read the query documentation:
http://api.jquery.com/category/ajax/
if i am not wrong 2nd possibility is may be you are trying "cross domain ajax call", if yes then you have to set header "Access-Control-Allow-Origin" and "crossDomain: true" for $.ajax call.

Categories