AJAX page load returns [object object] - javascript

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

Related

Laravel Bootstrap Tabs Pagination using AJAX

I am new to laravel, I have got a task of inserting pagination in bootstrap tabs. There are 2 tabs both tabs contain data which are different from each other. There may be 100 records in 1 tab and 10 in other, so it does not match.
I have been searching on the net to find an example which helps to crack this issue of paging. I inserted pagination but when I click on paging link other tab also gets affected and also it reloads the main page rather than the particular tab.
Please help me in solving this issue. Thanks in advance.
HomeController Code
View Code
Ajax code for pagination is below
$(window).on('hashchange', function() {
if (window.location.hash) {
var page = window.location.hash.replace('#', '');
if (page == Number.NaN || page <= 0) {
return false;
}else{
getData(page);
}
}
});
$(document).ready(function()
{
$(document).on('click', '.pagination a',function(event)
{
$('li').removeClass('active');
$(this).parent('li').addClass('active');
event.preventDefault();
var myurl = $(this).attr('href');
var page=$(this).attr('href').split('page=')[1];
getData(page);
});
});
function getData(page){
$.ajax(
{
url: '?page1=' + page1,
type: "get",
datatype: "html",
})
$.ajax(
{
url: 'dashboard',
type: "get",
datatype: "html",
data:{name:'newLeads'},
})
.done(function(data)
{
$("#item-lists").empty().html(data);
location.hash = page;
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
}
enter code here

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.

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

Click event for button on 2nd page of multi-page jquerymobile document does not fire

My simple mobile app has 3 pages all demarcated with divs/ data-role="page" and within the same document (.html). The pages load up perfectly but if I navigate to the 2nd page, a very simple click event on a button does not work.
In the I have the following within script tags:
$('#igetdetails').click(function () {
alert("hello");
})
igetdetails being the id of the button. The alert never pops up.
When I place this code within the pageinit event of that page however, it pops up immediately the page is loaded.
This tells me there must be something very simple I'm missing out but after 8 hours of strain and pain I'm reaching out for help.
Here's the full head section:
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>
</title>
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.1.1/jquery.mobile-1.1.1.min.css"
/>
<link rel="stylesheet" href="my.css" />
<style>
/* App custom styles */
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.1.1/jquery.mobile-1.1.1.min.js">
</script>
<script src="my.js">
</script>
<script>
// Invoice = new Object();
$( '#page1' ).live( 'pageinit',function(event){
//alert( 'This page was just enhanced by jQuery Mobile!' );
// Ajax Called When Page is Load/Ready (Load Customers)
jQuery.ajax({
url: 'list_customers.php',
global: false,
type: "POST",
dataType: "xml",
async: false,
success: populateCustomers
});
jQuery.ajax({
url: 'list_salesmen.php',
global: false,
type: "POST",
dataType: "xml",
async: false,
success: populateSalesmen
});
$("#iinv_customer").bind( "change", function(event, ui) {
Invoice.CustomerID = $('#iinv_customer').val();
});
$("#iinv_salesman").bind( "change", function(event, ui) {
Invoice.SalesmanID = $('#iinv_salesman').val();
});
$("#iinv_date").bind( "change", function(event, ui) {
Invoice.Date = $('#iinv_date').val();
});
$("#iinv_no").bind( "change", function(event, ui) {
Invoice.invno = $('#iinv_no').val();
});
$("#iinv_add").bind( "click", function(event, ui) {
$('#iinv_customer').selectmenu('disable');
$('#iinv_salesman').selectmenu('disable');
$('#iinv_no').textinput('disable');
$('#iinv_date').textinput('disable');
$.mobile.changePage("#page4");
});
$("#iinv_cancel").bind( "click", function(event, ui) {
$('#iinv_customer').selectmenu('disable');
$('#iinv_salesman').selectmenu('disable');
$('#iinv_no').textinput('disable');
$('#iinv_date').textinput('disable');
//$('#page1').reset();
location.reload();
});
});
$( '#page4' ).live( 'pageinit',function(event){
//alert( 'This page was just enhanced by jQuery Mobile!' );
//$('#iSelectedCustomer').html($('#iinv_customer').val());
$('#iSelectedCustomer').html($("#iinv_customer option[value='" + $('#iinv_customer').val() +"']").text());
// document.getElementById("iSelectedCustomer").innerHTML = $('#iSelectedCustomer').html();
//var element = document.getElementById('iSelectedCustomer');
//alert(element.value);
//element.value = $('#iinv_customer').value;
//alert(element.value);
// var selected = $(#iinv_customer).val;
// $('#iSelectedCustomer').val(selected);
jQuery.ajax({
url: 'list_products.php',
global: false,
type: "POST",
dataType: "xml",
async: false,
success: populateProducts
});
});
$('#igetdetails').click(function ()
{
alert("hello");
//$("#ili_prod").bind( "change", function(event, ui) {
//var data = { prod: 12};
var data = { prod: $("#ili_prod").val()};
// prodid = $(this).attr('value');
jQuery.ajax({
url: 'get_products_details.php',
type: "POST",
dataType: "xml",
data:data,
async: false,
success: populateProductsDetails
});
alert($("#ili_prod").val());
alert("hello");
});
</script>
</head>
You are running the JS code before the DOM element exists. Since you are using a multi-page template you can just place the code in your question inside a document.ready event handler (be aware that when using single-page-templates this is not a good idea, you should instead use delegated page events).
Just wrap your code like this:
$(function () {
...
$('#igetdetails').click(function () {
...
});
Old question but the preferred way to do this now is with
http://api.jquery.com/on/
$(document).on('click', '#igetdetails', function(event) {
alert('hello')
});​
This will bind the event for the document and listen for future matching selectors to bind to.

Categories