Check if image exists, if not load it - ajax

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

Related

Generating File with Ajax Fileupload

My app is an MVC .NET 4.0 application.
My application is fairly straightforward. I open an text file and uploaded it to be processed and returned as an excel file. This works as expected.
The excel file is returned via an actionresult controller. There are no errors. It works the way I want it to.
The problem is that when I call ajaxStart with blockUI it works. However, upon returning the file, the ajaxStop or ajaxSuccess is never fired to turn off the spinner after the file result is displayed with a message - do you want to open the file or save it or cancel.
I'm using jquery fileupload, blockUI and jquery 1.9.1.
$('#fileupload').fileupload({
dataType: 'json',
type: 'POST',
url: fileuploadpath,
autoUpload: true,
beforeSend: function () {
$.blockUI({
timeout: 0,
message: '<h1><img src="../images/ajax-loader.gif" /> Processing...</h1>'
});
},
complete: function() {
//$.unblockUI();
},
done: function (e, data) {
//$('.file_name').html(data.result.message.Name);
//$('.file_type').html(data.result.message.Type);
//$('.file_size').html(data.result.message.Length);
$('.file_msg').html(data.result.message.Error);
},
success: function (data) {
$.unblockUI();
$('.file_msg').html(data.result.message.Error);
}
});
and here is the basics of the file return in the action controller:
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
return File(fileoutput, "application/vnd.ms-excel");
Everything works just great. The area I'm scratching over my head is - why isn't the spinner being turned off after the file return? Am I missing something? I've tried binding ajaxStop and ajaxStart to the document but that does not work. ajaxStart gets fired but upon the file return, ajaxStop is being ignored.
Remove the 'done' and 'complete' event and use this format for your ajax call:
$(document).ready(function() {
$('#fileupload').fileupload({
dataType: 'json',
type: 'POST',
url: fileuploadpath,
autoUpload: true,
timeout:60000,
beforeSend: function () {
$('#loader').show()
},
success: function (data) {
$('#loader').hide()
//$('.file_name').html(data.result.message.Name);
//$('.file_type').html(data.result.message.Type);
//$('.file_size').html(data.result.message.Length);
$('.file_msg').html(data.result.message.Error); //??? you are passing the error here
},
error: function(jqXHR, textStatus, errorThrown) {
$('#loader').hide()
if(textStatus==="timeout") {
alert("A timeout occurred");
} else {
alert("This is an other error");
}
}
});
});
NOTE: seen you have trouble with the blockUi, I have here used a other approach.
TIMEOUT:
I have set an extra parameter 'timeout' and set this to 60 sec. You coul set this to '0' which will be unlimited but it will be better practice to give it a limited value.
Place this in your HTML and give it a style of 'display:none' and an id.
<h1><img id="loader" src="../images/ajax-loader.gif" style="display:none"/> Processing...</h1>'

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...");

406 Error when returning JSON object – Unexpected content

A few colleagues and I have a problem whereby the response from an ajax call returns some unexpected content. Rather than getting a simple JSON object back with various properties, the value of result.responseText is the HTML markup of a generic 406 status error page, saying the MIME type is not accepted by the browser.
The call is made like so:
$.ajax({
url: '/promociones/cincogratis/canjear-codigo-promocional',
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('.promotion_banner .loader').hide();
$('.promotion_banner').html(result);
},
error: function (result) {
var obj = result.responseText;
if (obj.isRedirect) {
document.location = obj.redirectUrl;
}
else {
$('.promotion_banner .loader').hide();
$(".error-wrapper").removeClass("hidden");
var generic_error = document.getElementById('generic_error').value;
$(".error-wrapper p").html(generic_error);
}
},
beforeSend: function() {
$('.promotion_banner .loader').show();
}
});
The controller response to the call is like so:
Response.StatusCode = (int)HttpStatusCode.NotAcceptable; // 406
return Json(new { errorMessage = LocalErrorMessages.Website_Promotions_FreeFiver_General_Problem, isRedirect = false } );
We would expect result.responseText to contain key values for errorMessage and isRedirect, but they’re not there.
It’s worth pointing out that this code is multi-tenanted, shared by the current application and another one, where it works absolutely fine.
We’ve tried:
- Configuring IIS to show detailed error responses rather than a custom page for more detail – gives us nothing extra towards solving the problem.
- Allowing all response content types to the call
- Changing the culture of our site (which is currently es-ES)
- Various web.config tweaks
Has anyone ever had this problem?
Simplify your request. Maybe something like:
$.ajax({
url: '/promociones/cincogratis/canjear-codigo-promocional',
type: 'GET',
data: {foo:'bar', one:'two'},
dataType: 'json',
success: function (result) {
console.dir(result);
},
error: function (xhr) {
console.dir(xhr)
}
});
And post the response from the server. This kind of error seems a request problem rather than server configuration issue

Jquery: probleme with $.ajax (json datatype)

I have a problem to refresh a bloc in my page.
Here is the request:
> $("#pwd_lost_link").click(function(){
alert('1');
$.ajax({
type : 'POST',
url: 'test.php',
dataType: 'json',
data :{"nom" : "akbar"},
success : function(data){
$("#main_bloc").append(data.msg);
alert('2');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
alert(errorThrown); }
}); })
and here is the php file
<?php
$return['nom'] = "ffrfrfrfr";
echo json_encode($return)
?>
It doesn't work. It give me a status error ( 0 ) and the page is automatically reloaded
Thanks
Michaël
Confusing question Michael, not sure what you mean by "the page is automatically reloaded" but you should do 2 things:
In the $.ajax() method, make sure your success called back is handling the data correctly. You are looking for data.msg but I don't see where .msg comes from.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
url: url,
success: function(data) {
// parse data object so you can see what's being returned ex. alert(data) or alert(data[0]) or alert(data.nom)
},
error: function (xhr, status, error) {
// XHR DOM reference: http://www.w3schools.com/dom/dom_http.asp
// check for errors ex. alert(xhr.statusText);
}
});
On the PHP side, you may want to debug there to see what is being received and what you are sending back.
Aside from that using an XHR viewer like Firebug or Chrome's built-in utility (CTRL+SHIFT+I) can be very helpful.
And on a final note, if pwd_lost_link is a link elment a id="pwd_lost_link" href="..." then you will have to stop the browser from following the link before you process the AJAX.
$("#pwd_lost_link").click(function(e) {
e.preventDefault();
alert('1');
$.ajax({
...
});
If you aren't seeing the '1' being alerted then that is definitely your first problem.
You're trying to access data.msg, but your PHP script is only creating data.nom. So data.msg doesn't exist. Try changing data.msg to data.nom and see if this does what you want.

Returning Json from controller, never a success

I'm successfully posting to my controller with the following code, however, success is never being hit only error. What am I doing wrong?
JS:
$.ajax({
url: '/Home/Subscribe',
type: 'POST',
dataType: 'json',
data: { email: $('#sube').val() },
success: function (data) {
// get the result and do some magic with it
alert(data.foo);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
Controller:
[HttpPost]
public JsonResult Subscribe(string email)
{
return Json(new { foo = "bar", baz = "Blech" });
}
In IE, press F12 to open developer tools. Go to Network tab and click on Start Profiler. Send a request to your Subscribe action - in a list below you will see details of sent request and returned status code. Double click on request to see details - you can then see body of your response. If the request failed with a server error, you will see that error in a body of your response.
One wrong thing I see with your code is that you have hardcoded the url:
url: '/Home/Subscribe'
You should never do this. You should always use url helpers when generating urls in an ASP.NET MVC application:
url: '#Url.Action("Subscribe", "Home")'
Also you are saying that the error callback is always hit but you didn't say what you observed in FireBug or Chrome Developer toolbar when you tried to analyze the AJAX request. If you had done this you would have seen the exact cause of failure for the request because you would have seen what request is sent to the server and what response does the server sends back to the client.
The following is my jQuery ajax snippet that works. Your controller looks right. I assume you have verified it is actually getting called by using a breakpoint.
var p = {
email: $('#sube').val()
};
$.ajax({
url: '#Url.Action("Subscribe", "Home")'
type: 'POST',
data: JSON.stringify(p),
dataType: "text json",
contentType: "application/json",
success: function (data) {
// get the result and do some magic with it
alert(data.foo);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});

Resources