How to mute Ajax 404 Errors? - ajax

My script attempts to load an image URL with ajax. If they image is not found ajax throws an 404 error. The script then loads a fallback image. This is intended, but I don't like that the browser console shows the 404 error of the image that was not found. Is that a way to mute the error? Or am I approaching this the wrong way?
$.ajax({
type: "post",
url: try_img_url,
success: function(response){
//if finds the image, use it.
},
error: function(response){
//if does not find the image, use fall back image.
}
});
My other idea, was to check if the image url exists before making the ajax call, that way I would not have to make the call at all if the image doesn't exist. However, I am not sure how to do that.

I'm not sure if this is possible with JS but I would approach this by adding a small PHP script like eg getimage.php then use that to check if the file exists.
PHP:
<?php
if (isset($_GET['image']) && is_file($_GET['image'])) {
echo sprintf("<img src='%s' />", $_GET['image']);
} else {
echo "<img src='fallback.jpg' />";
}
?>
JavaScript:
$(function () {
$.get('getimage.php', function (data) {
$("body").html($("body").html() + data);
});
});

Related

Using content of a variable for js function calls?

after a ajax call of a php - file i want to take a part of the feedback-result for add additional javascript code. The php file returns the code. Now i dont know how i can include it in the right way?
For better understanding
the php file returns the $result[script] = 'alert("my functions");'
the file wich controls the ajax calls looks something like that
url: fileurl,
type: "post",
data: formDetails.serialize(),
error: function(jqXHR, textStatus, errorThrown)
{
displayAjaxMessage("Sorry, there was an error");
},
success: function (result) {
var res = $.parseJSON(result);
//Here should be the scriptcode from the variable
$res.script;
}
I want to do it, beacause i think i have to redeclare some function for example plugins like bootstrap-switch, datepicker etc.
They wont work after submit the form, so i think i must inlcude the JS-Code again?
With
eval(res.script);
It works.

redirect after process php

well after reading all the related topics still no success,
I have 4 files index.php with a simple form, after submit I use process.php to send back (ajax) errors to index.php using external script.js file and also send mail to the owner of this site,all i need is that the user will also be redirected to a thank-you.html page (if there are no errors of course) but no luck ,I have tried all the combinations suggested:
header("Location: http://www.mywebsite.com/thank-you.html");
header("Location:thank-you.html");
if (success).....
echo
<script type="text/javascript">
<!--
window.location = "http://www.website.com/thank-you.html";
//-->
</script>
I have tried to put it in the bottom of the process,php ,also in the top of the page also tried to put in the script.js-inside $ajax function but nothing:(((
Can anyone tell me what to do?
solved:
thank you all so much:))))) it should be inside the ajax function in the script , right after success: function(data){ I have placed it in the bottom of the script and it didnt work before but now its perfect!
If you're doing this inside of a jQuery $.ajax() call, use the "success" method instead.
$.ajax({
type: "post",
//etc...
success: function(){
window.location.href="thank-you.html"
}
});
The correct usage in JS is "window.location.href".
Also, a PHP file with "header" being set during an AJAX call won't redirect the client browser.
If I understand correctly you will need to handle the redirect once you get the response from process.php IE: in the success callback.
$.ajax({
success: function () {
window.location.href = 'thank-you.html';
}
});
echo '
<script type="text/javascript">
<!--
window.location = "http://www.website.com/thank-you.html";
//-->
</script>';
assuming that is from php you were missing quotes.
I handled it a little differently as I handled something similar recently. I have the PHP page echo back "true" (this could also just be an INT) and then run if/else statements in the ajax.
$.ajax({
url : "process.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
if (data == "true")
{
window.location = "http://www.website.com/thank-you.html";}
}

Using form data to dynamically construct url using ajax

I have the following ajax code that takes in 3 variables and passes them to a php file, and this is all fine and dandy. I want to do a redirect using the value stored in one of these variables. I figured I could just do window.location.href = within the success in the ajax call, but for some reason, it doesn't seem to respond to the click, and simply does nothing.
Here is the ajax function, hope y'all can help!
$("#findItem").click(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
$.ajax({
type: 'get',
url: 'http://plato.cs.virginia.edu/~aam3xd/cabbage/closestBuildingWeb.php',
data: {
foodItemId: $('#foodItem').val(),
sentLongitude: position.coords.longitude,
sentLatitude: position.coords.latitude
},
success: function(data){
//$('#answer').html(data);
//the following line doesn't seem to be executing....
window.location.href = foodItemId+"/"+sentLatitude+"/"+sentLongitude;
}
});
});
I think you should use your url into that window.location
window.location.href = "www.example.com/"+foodItemId+"/"+sentLatitude+"/"+sentLongitude;

load mypage.php via ajax into a div in wordpress

i have an ajax load request working in wordpress, but i would like to load the content from another page into the container div. at the moment it just passes the url in $dataToSend as a string?
jQuery(document).ready(function(){
var $dataToSend = "my-page.php";
var $testBtn = jQuery('#text-ajax-btn');
var $holdingCtn = jQuery('#my-holding-ctn');
$testBtn.click(function(){
jQuery.ajax({
type:'POST',
url: myAjax.ajaxurl,
data:{
action:'myAjax',
dataToSend:$dataToSend,
},
success: function(data,textStatus,XMLHttpRequest){
$holdingCtn.html("");
$holdingCtn.append(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
how can i pass an entire .php page through as the $dataTosend?
I do this all the time for wordpress, give me a sec to access my repository and I will show you example code.
I think problem is your my-page.php! I imagine you custom coded it. So it doesn't have necessary functions loaded.
put following code at the top of your my-page.php (this will help with 500 error you are getting)
require('../../../wp-load.php');
ajax part should look something like this:
//start ajax
$.ajax({
url: "http://localhost/wp-content/themes/theme/my-page.php",
type: "POST",
data: data,
cache: false,
success: function (data) {
console.dir(data);
}
})
If you want to load content from my-page.php file then you can load from the server side using
$data = file_get_contents('path/to/file/my-page.php'); // pass right path/url
Then, just echo the content from your function (registered ajax handler in WordPress using add_action) and in this case it should be
echo $data;
die(); // terminate the further execution
So, it should look something like
add_action( 'wp_ajax_myAjax', 'yourAjaxHandler' );
add_action( 'wp_ajax_nopriv_myAjax', 'yourAjaxHandler' );
function yourAjaxHandler(){
$data = file_get_contents('path/to/file/my-page.php');
die($data); // echo out the string and terminates execution
}
In your success callback, you can use
success: function(data){
jQuery('#my-holding-ctn').html(data);
}
Not sure if this is fully applicable, but the super easy way is just
$("#myDiv").load("myFile.php?foo=1&bar=2...");

Check if image exists, if not load it

I need to load an image if if hasn't been loaded yet.
For this i'm using the error function like this:
$.ajax({
type: "POST",
url: "inc/functions.php",
data: { productID: productIDVal, action: "addToCart"},
success: function(theResponse) {
busy=false;
$('#buyButton')
.error(function(){
var t = $("<img id='buyButton' src='images/checkout.png' />");
$.append(t);
});
}
});
But it is not working. Am i doing something wrong here?
Thanks in advance.
You need to specify where to append the image:
$('#buyButton').append(t); // NOT $.append(t);
// OR $(this).append(t);
More info here
Some general tips on debugging javascript.
Quick and dirty: Put an alert message on the first line of the error function like alert('inside error'). Then load the page and see if the alert message shows up. You can put variables inside the alert message to see what their values are. If you don't see an alert message it means that the code is not even being loaded for some reason, so you have to put an alert message at an earlier point. (This can get very tedious).
Better way: Start using Firebug or Safari's Web Inspector to debug the javascript. Just put debugger anywhere in your code and when the browser gets to that line of code, it will stop and give you a console with access to all variables and functions available at that point in the code.
The problem may be with the AJAX request. See what it is returning by trying this code:
$.ajax({
type: "POST",
url: "inc/functions.php",
data: { productID: productIDVal, action: "addToCart"},
success: function(data){ alert('success!'); },
error: function(XMLHttpRequest, textStatus, errorThrown){ alert(errorThrown) ;}
})
You can replace the alert messages with debugger to do further inspection of what is going on with Firebug.
you should move the code to error block
remove from the success block
error: function(request,error) {
var t = $("<img id='buyButton' src='images/checkout.png' />");
$(this).append(t);
}
the skeleton goes like this
$.ajax({
},
beforeSend: function() {
},
error: function(request,error) {
var t = $("<img id='buyButton' src='images/checkout.png' />");
$(this).append(t);
},
success: function(request) {
} // End success
}); // End ajax method

Resources