Cannot change CSS from within ajax .done or .fail - javascript

I want to use a jQuery ajax call and change some CSS properties of an element if the ajax call succeeds or fails. My broswer is Chrome (latest version) on Windows 7 professional.
$.ajax({
url: "mytesturl",
dataType: 'json',
timeout: 3000 // 3 second timeout
}).done(
function(json) {
var el = $('#myDiv');
el.css('color', '#00FF00'); // green
}).fail(
function(jqXHR, textStatus){
var el = $('#myDiv');
el.css('color', '#FF0000'); // red
});
If I try this and start / stop the webserver to simulate a success and fail the color does not change at all. :-(.
If I debug I see that the code inside .done and .fail is executed, but the color does not change. The debugger is executing the line el.css('color', '#FF0000');. But the browser does not change the color!?!
I checked 'el' returns a valid element but for some reason the browser does not change the color. Also other changes like el.html('test'); do not work.
If I change the color using a button then the color is changed.
It seems that out of the functions .done / .fail it is not working.
Is there any issue with the scope?
What can it be?

try this:
$.ajax({
url: "mytesturl",
dataType: 'json',
timeout: 3000, // 3 second timeout
success: function(json) {
var el = $('#myDiv');
el.css('color', '#00FF00'); // green
},
error: function(jqXHR, textStatus){
var el = $('#myDiv');
el.css('color', '#FF0000'); // red
}
});
ALSO: if you are trying to set the color for a div, color isn't the right option to set, you should set the background like this:
$.ajax({
url: "mytesturl",
dataType: 'json',
timeout: 3000, // 3 second timeout
success: function(json) {
var el = $('#myDiv');
el.css('background', '#00FF00'); // green
},
error: function(jqXHR, textStatus){
var el = $('#myDiv');
el.css('background', '#FF0000'); // red
}
});

jQuery.ajax({
type:"post",
timeout: 3000,
dataType:"json",
url: "mytesturl",
success: function(json) {
var el = $('#myDiv');
el.css('color', '#FF0000');
},
error: function(data) {
var el = $('#myDiv');
el.css('color', '#000000');
},
});

Related

Track click over iframe by Javascript / Jquery

how can we track clicks on iframe (like any advt.) and record that event in my own database (with ajax) according to website users respectively with advt id and user id
i have tried onclick (like below) event on parent div but not working -
$('div.ad').on('click', function(){
$.ajax({
url: 'clickevent.php',
type: 'POST',
data: {
'id': adId
},
dataType: 'json',
success: function(data){
// show success msg to user
},
error: function(){
// show failure msg
}
});
});
i tried focus and blur while cursor is over that iframe
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
jQuery(function( $ ){
var isOverAd = false;
$( "iframe[ id *= google ]" )
.mouseover(function(){
isOverAd = true;
})
.mouseout(function(){
isOverAd = false;
});
$( window ).blur(
function(){
if (isOverAd){
$.ajax({
url: 'clickevent.php',
type: 'POST',
data: {
'id': adId
},
dataType: 'json',
success: function(data){
//show success msg
},
error: function(){
//show failure msg
}
});
}
}).focus();
});
i have also tried for when window loss blur while mouse on that iframe
i have mapped pixels ($0 values) it is also not working.
but nothing is working ......i will be very thankfull if you help me
To access an frame in page you can do this:
var frame = window.frames['FRAME-ID'];
$(frame).load(function ()
{
$(frame).contents().find('ELEMENT-IN-FRAME');
//To manage click on element body ( or any elements):
$(frame).contents().find('body').on('click', function(){alert('k')});

How to append a div with also the script appended

So I have a piece of code that appends some things to a webpage, those elements are called from a JSON file (JSONP).
This is the code that calls the JSON file:
<script>
$(document).ready(function() {
(function($) {
var key= "12345";
var url = 'http://www.example.com/json.php?callback=?&auth=' + key + '';
var that = $(this);
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
$( "head" ).append(json.csBlock[0].pre);
$( "head" ).append(json.csBlock[0].markup);
$( "body" ).append(json.csBlock[0].div);
$( "body" ).append(json.csBlock[0].script);
$( "body" ).append(json.csBlock[0].frame);
},
error: function(e) {
console.log(e.message);
}
});
})(jQuery);
});
</script>
The thing is.. When I use this it will say: Uncaught TypeError: Cannot read property 'click' of null
This is because I call $( "body" ).append(json.csBlock[0].script);. Which contains the following code in the JSON file:
"script": "<script>$('.wblongbar').click(function(e) { if($('.wbiFrame').hasClass('slide-up')) {$('.wbiFrame').addClass('slide-down', 200); $('.wblongbar').addClass('slide-downlongbar', 200); $('.wbiFrame').removeClass('slide-up'); $('.wblongbar').removeClass('slide-uplongbar'); } else {$('.wbiFrame').removeClass('slide-down'); $('.wblongbar').removeClass('slide-downlongbar'); $('.wbiFrame').addClass('slide-up', 200); $('.wblongbar').addClass('slide-uplongbar', 200); }});</script>",
As you can see, I use .wblongbar, which is contained in the $( "body" ).append(json.csBlock[0].div);
The script can't "find" the .wblongbar div
So, in what way do I append this script, without it not finding .wblongbar?
I've tried to change the order of the code but did nothing.
Remove all the spaces in script or any element you want to append. Append all the data as a single string.

jQuery not deleting record from table

I want to create a new function that when I press a little trashcan icon, a record in MYSQL will be deleted.
The following is my js codeļ¼š
$("table").find("img[class='icon_garbage']").click(function(){
var delnum = $(this).parents("tr").find("td[class='so']").text();
var string='delete_num='+delnum;
$.ajax({
url:"../src/delete.php",
type:"post",
data:string,
success: function(){
var tr = $(this).parents("tr");
tr.fadeOut('slow', function(){
$(this).remove();
});
}
})
});
and it's not working.
the record do delete, but the record does't fadeout.
but if I fix the code as following:
$("table").find("img[class='icon_garbage']").click(function(){
var delnum = $(this).parents("tr").find("td[class='so']").text();
var string='delete_num='+delnum;
var tr = $(this).parents("tr");
tr.fadeOut('slow', function(){
$(this).remove();
});
$.ajax({
url:"../src/delete.php",
type:"post",
data:string,
success: function(){
// var tr = $(this).parents("tr");
// tr.fadeOut('slow', function(){
// $(this).remove();
// });
}
})
});
and it's will working ......
I don't know why , can somebody tell me ?
My OS is MAC OSX 10.8.5,and I use MacVim to be my editor.
Set the context in the ajax call to this. Without setting the context, this does not refer to your element in the success event.
$.ajax({
url:"../src/delete.php",
type:"post",
data:string,
context: this, // <----------------- here
success: function(){
var tr = $(this).parents("tr");
tr.fadeOut('slow', function(){
$(this).remove();
});
}
});

When this ajax jquery trigger I want a image that loads for 1 second

I have this code
<script type="text/javascript">
$(function () {
$(".a").live("click", function () {
var $this = $(this),
ProductImageId = $this.data('ProductImageId');
$.ajax({
url: '/Home/AddToCart',
type: "post",
cache: false,
data: { ProductImageId: ProductImageId },
success: function (data) {
data = eval(data);
$this.addClass('productSelected');
},
error: function (result) {
$(".validation-summary-errors").append("<li>Error connecting to server.</li>");
}
});
});
Every time someone click on this button I want a image to load for like 1 sec
so the user knows that something happened..
any kind of help is appreciated
Something like:
var $loader = $('<img src="loader.gif">').appendTo(document.body);
And then
success: function (data) {
setTimeout(function() {
$loader.remove();
data = eval(data);
$this.addClass('productSelected');
},1000);
}
It will show the image for 1sec + the ajax loading time. Although, as a visitor of your site I would probably prefer to skip the 1sec delay...
Add before send like this :
beforeSend: function(){
$("some element").append("<img src='url' id='one_sec_img' />");
SetTimeout(1000, function(){
$("#one_sec_img").hide();
})
}
But, I think your requirement is something normal :
Here, bcoz of the before send, as soon as you click button that triggers ajax, the image will be loaded, and on success, the image can be hidden . This is the usual process, in this case,setTimeout is not needed . But, if your requirement is something like, the image should appear only one sec, you can use set timeout. Otherwise, below code is enough.
beforeSend: function(){
$("some element").append("<img src='url' id='one_sec_img' />");
},
success: function(res){
$("#one_sec_img").hide();
}
<script type="text/javascript">
$(function () {
$(".a").live("click", function () {
var html=$(this).html();
$(this).html('loading');//<img src="" />
var $this = $(this),
ProductImageId = $this.data('ProductImageId');
$.ajax({
url: '/Home/AddToCart',
type: "post",
cache: false,
data: { ProductImageId: ProductImageId },
success: function (data) {
$(".a").html(html);
data = eval(data);
$this.addClass('productSelected');
},
error: function (result) {
$(".validation-summary-errors").append("<li>Error connecting to server.</li>");
}
});
});
try this.
Use jQuery BlockUI Plugin to show the image, may be it solve your problem.
Try:
$(".a").click( function( ) {
$("#idOfImage").show().delay( 1000 ).hide();
// ajax call
});
else if you only want the image to disappear only after the ajax call
$(".a").click( function( ) {
$("#idOfImage").show();
$.ajax({
// parameters
}).done( function( ) {
$("#idOfImage").hide( );
});
});

Apply animate to new elements that have been added dynamically

The code i current have is this.
function update (){
latest_id = $('#image:first').data('position'); /* == 12 */
$.ajax({
type: "POST",
url: "../web/update/" + latest_id + "",
success: function(data) {
$('#my_like').after(data);
$('.newly-added').animate({"margin-left": "+=66px"}, "fast");
},
error: function(response) {
alert("failed");
},
});
}
setInterval(function() {
update();
}, 4000);
But because the element has been newly added it doesn't receive the new animate part. I done some research and found .live but that needs something to start it, e.g a click.
Fixed, there was a issue with jquery I was including.

Categories