How to append a div with also the script appended - javascript

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.

Related

AJAX page load returns [object object]

I'm currently trying to do a simple AJAX page transition in my local host.
Here is the tag on my home.html
go to blank
Should take me to the blank.html page.
Here is my AJAX:
$(function(){
jQuery(function ($) {
$(document).on('click', "a", function (event) {
event.preventDefault();
$.when($("body").fadeOut(1000).promise(), $.ajax({
url: this.href,
type: 'get',
dataType: 'html'
})).done(function (html) {
var newDoc = document.open("text/html", "replace");
newDoc.write(html);
newDoc.close();
$("body").fadeIn(1000);
});
});
});
});
Without the javascript my redirect works fine, but with the javascript, after the fadeOut it returns [object Object] on the page (and does not redirect)
I have looked around for a solution but cannot seem to find one.
Any help or advice is appreciated, thank you in advance!
EDIT:
console.log(html); returns:
Try this:
$(function(){
jQuery(function ($) {
$(document).on('click', "a", function (event) {
event.preventDefault();
$("body").fadeOut(1000);
$.ajax({
url: this.href,
type: 'get',
dataType: 'html',
success: function(html){
var newDoc = document.open("text/html", "replace");
newDoc.write(html);
newDoc.close();
$("body").fadeIn(1000);
}
})
});
});
});

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')});

After running an AJAX call, jquery code does not execute

I have a website which uses pagination, and some filtering with jQuery and AJAX. All works well up until the point I changed my links to Javascript links.
Being on the homepage and not having used any filtering or pagination all works as expected. After I have used pagination or a filtering (effectively using an AJAX call for both) my JavaScript links do not work anymore.
The JavaScript for the link is:
$(function(){
$( ".artikel_box_lk .button" ).click(function( e ) {
window.open( "/lk/" + $( this ).attr("rel"), "_blank");
});
});
And the code for the pagination:
function loadData(page){
loading_show();
$.ajax
({
type: "POST",
url: "php/load_data.php",
data: dataToSend,
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
My guess is that the javascript does not get reloaded on the AJAX call as only part of the page is reloaded, but I am unsure if this is the case and on how to fix this.
Seems your javascript is not loaded after postback. Try adding your function inside pageLoad on Webpage like :
function pageLoad()
{
$( ".artikel_box_lk .button" ).click(function( e ) {
window.open( "/lk/" + $( this ).attr("rel"), "_blank");
});
}
Do event delegation
$( "#container" ).on ("click",".artikel_box_lk .button" ,function( e ) {
window.open( "/lk/" + $( this ).attr("rel"), "_blank");
});

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( );
});
});

jQuery, Shadowbox and AJAX

I would like to load some content using AJAX and Shadowbox
Basically I would like the user to goto a page in case javascript is off. So this is what I want to do :-
1) Cancel the click event i.e the User must not go to a different page.
2) Load content using ajax function in jQuery
3) Show the content inside a shadow box
My code works ok until loading content using ajax but the shadowbox is not displayed and the URL is gettin refreshed i guess, everything goes blank.
jQuery(document).ready(function($){
// rounded corners
$('img').addClass('corner iradius16');
DD_roundies.addRule('#nav li a',4,true);
DD_roundies.addRule('.grid',6,true);
$('h2 a').bind('click', function() {
var id = $(this).attr('id');
$.ajax({
url: "/ajax-post.php?p="+id,
success: function(data){
Shadowbox.open({
content: data,
player: "html",
height: 350,
width: 350
});
}
});
return false;
});
UPDATE 1
tried this code, and as soon as the shadowbox loads, the document gets reloaded and white.
Shadowbox.init({
skipSetup: true,
players: ["html"]
});
// LOAD
jQuery(document).ready(function($){
// rounded corners
$('img').addClass('corner iradius16');
DD_roundies.addRule('#nav li a',4,true);
DD_roundies.addRule('.grid',6,true);
$('.post h2 a').bind('click', function() {
var id = $(this).attr('id');
$.ajax({
url: "<?php bloginfo( 'template_directory'); ?>/ajax-post.php?p="+id,
success: function(data){
show_box(data);
}
});
return false;
});
});
//shadowbox
function show_box(html) {
Shadowbox.open({
content: html,
player: "html",
height: 350,
width: 350
});
}
UPDATE 2
Okay got the prbolem, the html that I am getting via ajax has some javascript in it and that is the reason for the page reload.
Why is this happening ? Any ideas ?
Since you're not getting any JavaScript errors try debugging by breaking it down:
Ensure that the binding to and overriding of the click event is functioning properly:
$('h2 a').bind('click', function() {
alert('click even fired');
return false;
});
If that works, check the data that your ajax request is returning:
$('h2 a').bind('click', function() {
var id = $(this).attr('id');
$.ajax({
url: "ajax-post.php?p="+id,
success: function(data){
alert(data);
}
});
return false;
});
The code looks like it should work, so I'm guessing there's either something wrong elsewhere (in which case the first test will likely fail) or you're getting some really odd data returned.
Need to run
Shadowbox.setup('h2 a');
This will reinitialise and bind it to any ajax loaded content

Categories