Why does $.ajax() cause the wep page to postback twice? - javascript

Can anyone tell me why does this $.ajax() cause the webpage to do a postback twice? Isn't it suppose to fire only once?
This is what I saw when debugging in Visual Studio and it is causing the server-side script to run twice. I'm using JQuery version 2.0.0 .
The ThrobblerAnimationBegin() function is what show the processing icon animation to let the end-user know the webpage is busy executing the script. The #{} bracket is the server-side script, this is how I was able to tell when a postback was made to the server-side backend, by using debugging breakpoint.
Thanks...
#{
string foo = "Me Me Me";
foo += ", fee fee fee";
}<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>BookItOut - A New Dawn In Auto Pricing"</title>
<script type="text/javascript" src="~/Member/Scripts/jquery-v2.0.3/jquery-v2.0.3.min.js"></script>
<script type="text/javascript">
function ThrobblerAnimationBegin() {
return $.ajax();
}
function ThrobblerAnimationEnd() {
}
$(document).ready(function () {
function DrawVehicleCostPerDays() {
var $deferred = $.Deferred(); //$.Deferred.done() --> to allow ayschronous sleep/delay until this current function() is finish before running done() afterward to continue. [[http://stackoverflow.com/questions/12116505/wait-till-a-function-is-finished-until-running-another-function]]...
$deferred.resolve();
return $deferred;
}
//Load the script...
ThrobblerAnimationBegin().done(function () {
//alert("done");
DrawVehicleCostPerDays(
).done(function () { ThrobblerAnimationEnd(); /*alert('success');*/ }
).fail(function () { ThrobblerAnimationEnd(); /*alert('failed');*/ });
});
});
</script>
</head>
<body>
</body>
</html>
EDIT as per request Here's the snapshot from Firefox's Firebug.

Your ajax is not firing twice. Instead, what you are seeing is the initial page load (what you are counting as the first ajax request) and then the ajax request (what you were counting as the second). Since you did not specify a URL in the .ajax() call, it made a request to the same page, which is likely what confused you.
You should probably read the .ajax() documentation for simple examples of how to use it.

Related

Get a javascript derived dom-tree element

My aim is to get an element <div id="calender"> and all what is in the element shown in a browser. The point is that normal get-html-source won't do the thing. The element what I am looking for does not exists in the html output of php-function file_get_contents.
I have tried to get the source by php with xpath byt the help of http://us3.php.net/manual/en/class.domxpath.php which inludes a nice tool to get what is in any tag in the html page. But the problem here might be that the element (a calender) is formed to the loaded page by javascript and cannot be caught by server side php. So, is there a way I can catch such element (div) by javascript instead.
There are script examples of javascript for this kind of problem (if I have understood them correctly) but currently I cannot get a simple javascript to work. An example below shows how I have tried to built up a code. $ajax thing here is just one path I have tried to solve the problem but don't know how to use it. More here I cannot figure out why the simple javascript functions do not work (just test purposes).
<!doctype html>
<html lang="fi">
<head>
<meta charset="utf-8">
<title>load demo</title>
<style>
body {
font-size: 12px;
font-family: Arial;
}
</style>
<script type="text/javascript">
function ok {
alert "OK";
}
function get_html (my_html){
alert "OK";
var l = document.getElementById('my_link').value;
alert l;
alert my_html;
var url = my_html;
$.ajax({
url: url,
dataType: 'html'
success: function(data){
//do something with data, which is the page 1.html
var f = fs.open("testi_kalenteri.html", "w");
f.write(data);
f.close();
alert "data saved";
}
});
}
</script>
</head>
<body>
<p id ='my_link' onclick='get_html("lomarengas.fi/en/cottages/kuusamo-rukasaukko-9192")'>html-link</p>
<p id ='ok' onclick='ok()'>show ok</p>
</body>
</html>
Briefly, I have a link to a web page, which shows up a (booking) calendar in it but this calendar is missing in the "normal" source code, by file_get_contents (php). If I browse the html source with Chromes tools (F12) I can find the calendar there. T want that information get by javascript or by php or such.
If you read the source code of the page you point to (http://www.yllaksenonkalot.fi/booking/varaukset_akas.php), you notice that the calendar is loaded via an iframe.
And that iframe points to that location :
http://www.nettimokki.com/bookingCalendar.php?id_cottage=3629&utm_source=widget&utm_medium=widget&utm_campaign=widget
Which is in fact the real source of the calendar...
EDIT following your comment on this answer
Considering the real link : http://www.lomarengas.fi/en/cottages/kuusamo-rukasaukko-9192
If the calendar is not part of the generated html, it is surely asynchronously generated (in javascript, client side).
From this asumption, I inspected the source code (again).
In the developper tools of my browser, in the Network section, where you can monitor what files are loaded, I looked for
calls to server (everything but calls to resources : images, stylesheets...).
I then noticed calls to several urls with json file extensions like http://www.lomarengas.fi/api-ib/search/availability_data.json?serviceNumber=9192&currentMonthFirstDate=&duration=7.
I felt I was on the right track (asynchronous javscript calls to generate html with json datas), I looked for javascript code or files that was not the usual libraries files (jquery, bootstrap and such).
I stumbled upon that file : http://www.lomarengas.fi/resources_responsive/js/destination.js.
It contains the code that generates asynchronously the calendar.
tl;dr
The calendar is indeed generated asynchronously.
You can't get the full html with a curl or file_get_content in PHP and
you can't access it with ajax code (due to Same-origin policy).
By the way, you should contact the site to see if you can access their api via PHP with their consent.
Hope it helped you understand the whole thing...
To get <div id="calender"> you can use next code (jquery):
<div id="calender"></div>
<script>
$("#calendar").click(function(){
alert('calendar was clicked');
});
</script>
If I understand you correctly. I think you need appropriate php respond with some correct code inside php file:
// json_handler.php
<?php
if (is_ajax()) {
$return = $_POST;
$return["ok"]="ok";
$return["json"] = json_encode($return);
echo json_encode($return);
}
function is_ajax()
{
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
and this is script wich is inside html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<a id="click">click</a>
<script>
$("document").ready(function(){
$("#click").click(function(){
var data = {
"request": "request"
};
data=$.param(data);
// alert(data);
$.ajax({
type: "POST",
dataType: "json",
url: "json_handler.php",
data: data,
success: function(data) {
// here you will see echo respond from your php json_handler.php
// also you can add here more javascript (jquery code) to change your page after respond
alert();
}
});
return false;
});
});
</script>
<body>
<html>
http://www.w3schools.com/jquery/jquery_ajax_intro.asp

JS/JQuery: Call parents function if child.html() is changed to ""

In my parent.htm there's a dropdown list, which is filled dynamically from the database using a JQuery function updateMyList() in parent.js.
If the user wants to add another option to the list, the form child.htm is loaded inside <div id="overlay"> of the parent.htm. To insert new data an AJAX request is called from child.js, which is included in child.htm.
If the request was successful, child.htm is unloaded via $("#overlay").html("") from child.js. When this happens, i'd like to call parent.js's updateMyList(), but i can't find a way to trigger it.
Using opener from inside child.js didn't work (TypeError: opener is null) and i can't find a way to tell if $("#overlay").html() has been changed back to "".
Any help would be greatly appreciated!
Sorry if this is a double post, i'm running out of ideas for search terms...
edit: here's a simplified code:
parent.htm:
<head>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="parent.js"></script>
<script>
$(document).ready(function () {
$('#new-option').click(function(){
$("#overlay").load("child.htm");
});
});
</script>
</head>
parent.js:
$(document).ready(function(){
function updateMyList(){
//send AJAX and write options
});
// and do much more...
});
child.htm:
<head>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="js/child.js"></script>
</head>
child.js:
$(document).ready(function(){
// do more stuff
$('#save-option').click(function(){
$.post("./inc/savenewoption.php", {
//save user entries
}, function(data){
alert(data);
})
.done(function() {
updateMyList(); // <- this won't work
$("#overlay").html("");
});
});
});
It doesn't work because updateMyList() is inside a different function (one of your $(document).ready() ones). In my experience the only reason you put code into a $(document).ready() function is because Javascript can fire before the document has completely loaded. Trying to fire Javascript on elements before they are in the document will cause errors.
The updateMyList() function doesn't fire until the ajax request is complete, so it should be safe to have it located outside $(document).ready().

Javascript: My setTimeout function not working because of 3rd party

I have intergrated a third party code into my website, and suddenly the setTimeout and setInterval stopped working: Before the third party is loaded, everything works fine. setTimeout and setInterval that were scheduled to run after the third party is loaded, do not dun at all.
After removing the 3rd party code snippet they supplied, everything work.
My question is - how can it be? what can the third pary do that can stop my schedules?
I renamed any pointers to the returned value of the setTimeout function; I tried to play with the place where I put the snippet and / or the setTimeout code.
Nothing work.
It doesn't make any sense. and I don't know how to start debugging it.
Here is a simplified html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My Demo</title>
<link rel="shortcut icon" type="image/x-icon" href="img/favicon.ico"/>
<!--<link href="css/style.css" rel="stylesheet" type="text/css">-->
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<script>
<!-- the alert pops up only when I remove the 3rd party snippet -->
setTimeout(function(){
alert("done");
}, 5000);
</script>
<!-- This is the 3rd party code -->
<script type="text/javascript">
var $P; var prefix = ('https:' == document.location.protocol ? 'https://' : 'http://'); var _P = _P || [];
_P.push(['setId', '123']);
var PPP = document.createElement('script');
PPP.type = 'text/javascript'; PPP.src = prefix + 'thethirdpartyIuse.com/functions.js';
var s = document.getElementsByTagName('script');
var lastScriptTag = s[s.length - 1];
lastScriptTag.parentNode.insertBefore(PPP, lastScriptTag);
</script>
</body>
</html>
Any help & guideness is appriciated!
Are you sure? It works fine in liveweave: http://liveweave.com/OKMyjs
And indeed you should wrap your code in:
window.onload = function() {
//your stuff
}
May be the external code redefines alert as something else. To see if this is the issue try changing your code to:
(function(myalert){
setTimeout(function(){
myalert("done");
}, 5000);
})(alert);
If this doesn't work the only reason I can think to is that the external script goes into an infinite loop. Functions registered with setTimeout will be executed once the Javascript event loop starts after the synchronous execution of script tags in the page and this may never happen if any toplevel stript hangs.
You should however see in this case the loading is taking forever (loading animation in the browser) and after long enough the browser should signal that there is a problem loading the page.
Something redefines your alert function.
Possible solutions:
wrap your code in (function(alert) { /* your code */ }(alert))
Object.defineProperty(window, 'alert', { configurable: false, enumerable: true, value: alert, writable: false }); to protect your alert from redefining.
do not rely on alert (in 99% of cases modal or console.log are superior solutions - alert, prompt and confirm are three functions blocking code execution in JavaScript).
After a lot of debugging, I found the probelm:
The 3rd party did setTimeout(true)for some reason (I assume by mistake).
In chrome, it cancel all schedules (setTimeout & setInterva).
I report the problem.

Execute php file with javascript function

I want to execute php file in javascript function. Code is as shown below:
<a id="cancel" href="./?&_action=list" onclick="javascript:clearRecord();return rcm.command('list','',this,event)">Cancel</a>
<script language="javascript" type="text/javascript">
var u1='michael';
function clearRecord() {
$(function() {
location.href = 'clear.php?h='+u1;
});
}
</script>
But when I click to cancel button, clear.php not executed. How I should come out from this?
full & working answer to your question:
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script language="javascript">
function cancelClicked() {
// function below will run clear.php?h=michael
$.ajax({
type: "GET",
url: "clear.php" ,
data: { h: "michael" },
success : function() {
// here is the code that will run on client side after running clear.php on server
// function below reloads current page
location.reload();
}
});
}
</script>
</head>
<body>
<a id="cancel" href="#" onclick="cancelClicked()">Cancel</a>
</body>
</html>
if you want to just execute some php and leave current page to the one generated by this php script. then you got it almost right.
I do not see that you are using jquery - so skip this "$(function(){})" part, and i don't see what u1 is added for but this will work:
function clearRecord() { location.href = 'clear.php'; }
and this will do the same:
Cancel
BUT if you want only to run "clear.php" and then reload current page.
One way of doing it can be putting at the end of your "clear.php" file something like:
header("Location:/");
(it will work only if clear.php does't write anything in response).
But you can do it other ways:
- using AJAX - call clear.php with jQuery.get() and call location.reload() on success;
- using IFRAME - set iframe's location to clear.php and then call window.location.reload();
- using IMG - set img.src to clear.php ...
...and possibly many other ways :)

JavaScript load order and anonymous function

In my html file, I am loading two external javascript files that does some dom manipulation, the first one simply prepares the page (injecting some div and contents) in the html. And the second one locates those divs that were just injected and then try and does some stuffs with it.
var app = {
init: function () {
// event handler goes here
app.alertMe('Hello');
app.loadContent();
app.insertDiv();
},
loadContent: function() {
$('#div1').load('../html/demo_test.html');
},
insertDiv: function() {
$('#div2').append('<strong>YEEEEEEAP</strong>');
},
alertMe: function(a) {
alert(a);
}
};
$(function () {
app.init();
})
The second one is this bootstrap library. My html file is as follows
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>A</title>
<script type="text/javascript" src="page_prep.js">
</script>
</head>
<body>
body
</body>
<script type="text/javascript" src="bootstap_lib.js">
</html>
Although I have the load order in the right order, the library seem to be loading before my custom.js this end up causing the actions not to work because the divs that need be present are not found. Careful debugging has proven that the divs were getting injected afterwards.
Any reason why that might be the case?
You are deferring the injection until the page has completed loading, where the bootstrap script runs as soon as the browser downloads it.
Move your script file to just above yout bootstrap script, and change this:
$(function () { //This defers execution
app.init();
})
to this:
app.init(); //This executes immediately

Categories