Preventing script execution on ajax load pages with jQuery - javascript

I'm trying to load a page using the load() function, the problem is that javascript code on that page is being executed when loading. I use this:
$('#itemid').load('thepage.php #selector', function() {
MY CODE HERE
});
how can i prevent the javascript code from being executed and load only the HTML part that i want?

Use .get() or .post() and process what you get back. Pull the script tags out of your returned code before you append it to the page, or just pull out the code you want:
$.post('thepage.php', {
data: myData
}, function(data) {
var myHTML = $(data).not('script');
$('#itemid').html(myHTML);
});
Or:
$.post('thepage.php', {
data: myData
}, function(data) {
var myHTML = $(data).filter('#selector');
$('#itemid').html(myHTML);
});
Demo: http://jsfiddle.net/jtbowden/wpNBM/
Note: As you mentioned, using a selector with load should accomplish the same thing, as you see in the example. So, if it isn't working this way, something else is going on.

Not sure if I have understood the problem correctly, but you could remove the javascript and just have the html. I assume you want to js bindings to happen on the new page though. So when you load the new page, in the callback, you could call a function that applies the needed bindings.
function applyAfterAjax(){
$(this).find('element').click(function(){alert('clicked');});
}
$('#itemid').load('thepage.php #selector',applyAfterAjax);

Related

refer javascript array from html file

I have a question regarding ajax array. I have create two arrays in a javascript file like below.
$(document).ready(function () {
categoryarray = [];
productarray = [];
Then if I want to refer to these arrays from another javascript file with the script inside html follows the script of the javascript file that creates two arrays, but it doesn't show anything, not even console reporting error.
Below is how I refered the array in another javascript file, it didn't work.
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'my_script.js',
success: function(data) {
for(var k=0;k<categoryarray.length;k++){
if(categoryarray[k][0]!==""){
$('.tree').append('<li id="Cate_' + k + '">'+categoryarray[k][1]+'</li>');
for(var l=0;l<productarray.length;l++){
if(categoryarray[k][0]==productarray[l][2]){
$('#Cate_' + k).append('<ul id="Pro_' + l + '"></ul>');
$('#Pro_' + l).append("<li>"+productarray[l][1]+"</li>");
}
}
}
}
},
error: function() {
$('.tree').text('Failed to load the data');
console.log('Error');
}
});
});
Can anyone tell me what I have done wrong and how to fix them? Many thanks!!!
First of all place your code inside a function that you will call on some event. If you want to process your arrays after AJAX call then call that function after AJAX success. Browser render HTML from top to bottom so your script in HTML will run as soon as browser bump into script. On the other hand jQuery on ready will wait until all of the page content is fully loaded (all images, assets etc) - whole DOM, so your arrays will stay undefined.
You can fix it either by moving that code from HTML to jQuery ready function or by moving array declarations in HTML.
Anyway, if that script from HTML should run when document is ready, then it is more reasonable to move javascript code from HTML to jQuery ready function.

$("Div").load() appending html page after completion of $(document).ready() when written inside $(document).ready()

Sorry if this type of question is already been answered.
I am trying to add a page using $("Div").load() inside $(document).ready().
Page is getting loaded but it is not showing anything inside its' variables.
Steps in my code:
Page starts loading
Value come from back-end code (spring java)
Loading a specific page when values are present and show them on page.
If values are null, do not load page.
Jquery version: "2.1.3"
Below is my code:
$(document).ready(
if(condition1){
var var1= data //some json data;
$('#divId').load('url/mypage.jsp');
if(condtition == true){
myFunctionToProcessData(var1);
}
}
)
I have tried ajax call, but its not working.
After completion, I can see my page is loaded and appended in division but not showing on UI and have empty variables.
Please help.
Thank you for your responses. I could not reveal my full code, so made a snippet to give an idea about what i wanted. Issue is fixed now.
Issue was: I wanted to append a JSP on certain condition inside $(document).ready() but the working of $(document).ready() is something like, it ensures executions of methods and conditions written inside it.
Problem was:
Method "myFunctionToProcessData" and "$('#divId').load('url/mypage.jsp');" was called simultaneously , and HTML was not complete at the same time when method called and due to this, my method did not find division to set values and do other validations.
To solve this I have used below approach:
Appended html/jsp page using .load function.
used an ajax method in which i am getting data.
execution steps:
1. Code appended HTML in some time (Using setTimeout function)
2. after execution of all lines in $(document).ready(), ajax function called
3. Now myFunctionToProcessData ca find divisions to set values and proper out put shown on the UI.
code:
$(document).ready(
if(condition1){
var var1= data //some json data;
setTimeout(function() {
$('#divId').load('url/mypage.jsp');
}, 10);
if(condtition == true){
$.ajax({
type : "GET",
contentType : "application/json",
data : "&sid=" + Math.random(),
url : "url", // change to full path of file on server
success : function (data) {
myFunctionToProcessData(var1);
});
}
}
)
This is just a workaround to make sure that myFunctionToProcessData executes only after jsp appended succesfully in it.
now myFunctionToProcessData is executing at the end.

Ajax Call Confusion

before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>

Listening for the addition of certain elements to the DOM by AJAX

I have a web application which uses a lot of AJAX to display pages.
In my javascript I have a feature which gets all the elements that have a certain class (testClass). It does a bunch of stuff with these classes but that's not necessary for my problem.
At the moment my function runs when the DOM is ready and it works great. However, I need my function to run when AJAX returns a new page to the browser as it could contain elements with testClass.
Is there a way I can listen if a certain DOM element is added? I basically need a way to recognise a DOM change, when this change has happen run my function.
Or is there a way I can listen for the addition of elements with class testClass?
If it help here is a snippet of my code:
execute = function () {
var found = false;
$('.testClass').each(function () {
//bunch of code
});
}
$(document).ready(function () {
execute();
});
Try with ajax success method
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});

Load .txt file using JQuery or Ajax

How can I fix the script below so that it will work EVERY TIME! Sometimes it works and sometimes it doesn't. Pro JQuery explains what causes this, but it doesn't talk about how to fix it. I am almost positive it has to do with the ajax ready state but I have no clue how to write it. The web shows about 99 different ways to write ajax and JQuery, its a bit overwhelming.
My goal is to create an HTML shell that can be filled with text from server based text files. For example: Let's say there is a text file on the server named AG and its contents is PF: PF-01, PF-02, PF-03, etc.. I want to pull this information and populate the HTML DOM before it is seen by the user. A was ##!#$*& golden with PHP, then found out my host has fopen() shut off. So here I am.
Thanks for you help.
JS - plantSeed.js
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init:function () {
$.ajax({
url: "./seeds/Ag.txt",
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
HTML - HEAD
<script type="text/javascript">
pageExecute.init();
</script>
HTML - BODY
<script type="text/javascript"> alert(pageExecute.fileContents); </script>
Try this:
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init: function () {
$.ajax({
url: "./seeds/Ag.txt",
async: false,
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
Try this:
HTML:
<div id="target"></div>
JavaScript:
$(function(){
$( "#target" ).load( "pathToYourFile" );
});
In my example, the div will be filled with the file contents. Take a look at jQuery .load() function.
The "pathToYourFile" cand be any resource that contains the data you want to be loaded. Take a look at the load method documentation for more information about how to use it.
Edit: Other examples to get the value to be manipulated
Using $.get() function:
$(function(){
$.get( "pathToYourFile", function( data ) {
var resourceContent = data; // can be a global variable too...
// process the content...
});
});
Using $.ajax() function:
$(function(){
$.ajax({
url: "pathToYourFile",
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
var resourceContent = data; // can be a global variable too...
// process the content...
}
});
});
It is important to note that:
$(function(){
// code...
});
Is the same as:
$(document).ready(function(){
// code
});
And normally you need to use this syntax, since you would want that the DOM is ready to execute your JavaScript code.
Here's your issue:
You've got a script tag in the body, which is asking for the AJAX data.
Even if you were asking it to write the data to your shell, and not just spout it...
...that's your #1 issue.
Here's why:
AJAX is asynchronous.
Okay, we know that already, but what does that mean?
Well, it means that it's going to go to the server and ask for the file.
The server is going to go looking, and send it back. Then your computer is going to download the contents. When the contents are 100% downloaded, they'll be available to use.
...thing is...
Your program isn't waiting for that to happen.
It's telling the server to take its time, and in the meantime it's going to keep doing what it's doing, and it's not going to think about the contents again, until it gets a call from the server.
Well, browsers are really freakin' fast when it comes to rendering HTML.
Servers are really freakin' fast at serving static (plain-text/img/css/js) files, too.
So now you're in a race.
Which will happen first?
Will the server call back with the text, or will the browser hit the script tag that asks for the file contents?
Whichever one wins on that refresh is the one that will happen.
So how do you get around that?
Callbacks.
Callbacks are a different way of thinking.
In JavaScript, you perform a callback by giving the AJAX call a function to use, when the download is complete.
It'd be like calling somebody from a work-line, and saying: dial THIS extension to reach me, when you have an answer for me.
In jQuery, you'll use a parameter called "success" in the AJAX call.
Make success : function (data) { doSomething(data); } a part of that object that you're passing into the AJAX call.
When the file downloads, as soon as it downloads, jQuery will pass the results into the success function you gave it, which will do whatever it's made to do, or call whatever functions it was made to call.
Give it a try. It sure beats racing to see which downloads first.
I recommend not to use url: "./seeds/Ag.txt",, to target a file directly. Instead, use a server side script llike PHP to open the file and return the data, either in plane format or in JSON format.
You may find a tutorial to open files here: http://www.tizag.com/phpT/fileread.php

Categories

Resources