I want a javascript script to be echoed when a condition is true,
the file where this script is on is called through ajax by another page
and for some reason it wont echo the <script>...</script> part.
If i put a regular string there it works but it just wont echo javascript.
$max = $int + 10;
if($max >= $num_rows){
$end = "<script>var end=1</script>";
} else {
$end = "<script>var end=0</script>";
}
echo $end;
ajax:
function onScroll(event) {
// Check if we're within 100 pixels of the bottom edge of the broser window.
var closeToBottom = ($(window).scrollTop() + $(window).height() > $(document).height() - 100);
if(closeToBottom) {
if(end==0){
// GET THE 10 NEXT ITEMS;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//document.getElementById("tiles").innerHTML=xmlhttp.responseText;
$('#tiles').append(innerHTML=xmlhttp.responseText);
int = int+10;
// Clear our previous layout handler.
if(handler) handler.wookmarkClear();
// Create a new layout handler.
handler = $('#tiles li');
handler.wookmark(options);
$(function() {
// Select all links whose attribute rel starts with lightbox
$('a[rel^=lightbox]').lightBox();
});
FB.XFBML.parse();
}
}
}
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});
var request = $.getUrlVar('item');
if(request!=null){
var allR = "?int="+int+"&item="+request;
} else {
var allR = "?int="+int;
}
xmlhttp.open("GET","tiles.php"+allR,true);
xmlhttp.send();
}
};
Can anyone solve this?
Thx in advance.
The thing is you have to go through the DOM tree of the document bit you download through Ajax and manually evaluate it using eval, because for security reasons browsers do not automatically parse and run the JavaScript code embedded through remote calls for you.
You can do something like this:
var scripts = domElement.getElementsByTagName("script");
for (var i = 0; i < scripts; i ++) {
eval(scripts[i].text);
}
Use the eval() in the javascript to load the javascript. Just checkout the below example
var div = document.getElementById("tiles");
div.innerHTML =xmlhttp.responseText;
var x = div.getElementsByTagName("script");
for(var i=0;i<x.length;i++)
{
eval(x[i].text);
}
This is a small fragment code you should inject in the place where you have received the response. Hope this helps.
Related
I currently have a table of email templates. The user is able to click the template, and populate the email template field pending on the td that gets clicked. I have a JS script that works fine in FF, but not in IE.
The following is JUST pseudocode of my php for timesake.
$somevar = mysql_query("...");
while (($anothervar = mysql_fetch_assoc($somevar))) {
echo '<tr><td class="test">'.$email['email_name'].'</td><tr>';
}
Here is the current JS I have that only works in FF.
function getName(e) {
$('input[name="Clear Button"]').click(function () {
$('span').text('');
});
var cell = e.target;
cell = cell.innerHTML;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("test").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/includes/adminPages/Update_Email.inc.php?selection_id=" + cell, true);
xmlhttp.send();
}
window.onload = function () {
var cells = document.getElementsByClassName("test");
for (var i = 0, len = cells.length; i < len; i++) {
cells[i].onclick = getName;
}
};
Just for the record, I did take a look at the following example, but that did not solve my problem.
window.onload = new function() { alert('hello');};
I see you're using jQuery, so maybe let's rewrite it
$(window).on('load', function() {
$('.test').on('click', function() {
var id = $(this).html();
$.get("/includes/adminPages/Update_Email.inc.php?selection_id=" + id, function(data) {
$('#test').html(data);
});
});
});
I'm using the following to update a DIV called 'output'. This works fine with one exception, I would like echo entries to update the parent page.
<script type="text/javascript">
<!--
var divid = 'output';
var loadingmessage = '<img src="working.gif">';
function AJAX(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;
}
catch (e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
}
function formget(f, url) {
var poststr = getFormValues(f);
postData(url, poststr);
}
function postData(url, parameters){
var xmlHttp = AJAX();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState > 0 && xmlHttp.readyState < 4){
document.getElementById(divid).innerHTML=loadingmessage;
}
if (xmlHttp.readyState == 4) {
document.getElementById(divid).innerHTML=xmlHttp.responseText;
}
}
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameters.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(parameters);
}
function getFormValues(fobj)
{
var str = "";
var valueArr = null;
var val = "";
var cmd = "";
for(var i = 0;i < fobj.elements.length;i++)
{
switch(fobj.elements[i].type)
{
case "select-one":
str += fobj.elements[i].name +
"=" + fobj.elements[i].options[fobj.elements[i].selectedIndex].value + "&";
break;
}
}
str = str.substr(0,(str.length - 1));
return str;
}
//--></script>
This is called using :
<input type='button' name='Send' value='submit' onclick="javascript: formget(this.form, 'foo.php');">
The issue I have is foo.php runs a series of exec() commands, between each command is an echo statement that I would like to be displayed in the output div.
So it will do something like:
echo "archive files";
exec ("tar -cvf bar.tar bar.txt foo.txt");
echo "backing up /user";
exec ("tar -cvf /user.tar /user/*");
I would like the user to see the working.gif, but under it each echo statement from foo.php
Can that be done and how ?
Thanks
I can't say I've ever tried sending back chunks of data at separate times with a single AJAX request, so I'm not sure it's possible. What happens currently? Do you only get first echoed message, or do only get the entire response at the end?
Two things that I know will work:
Break your PHP script into multiple scripts and execute them in order with separate AJAX requests. This will only work if the separated scripts don't depend on each other or you find some other way to persist the state across the separated scripts.
Create an iframe and load the PHP script into it instead of using an AJAX request. Flushing the output of the PHP script should then work. (If you have ever used Wordpress, I believe they use this technique to show the progress of plugin updates.)
I adapted this script from the wookmark plugin to load more items from a db when the users scrolls to the bottom of the page.
Initially it pre loads the images and then creates the layout, however when the users scrolls to the bottom, the new items are loaded thru ajax but the images all overlap each other.
I'm using the imagesloaded jquery plugin to get the images to display correctly when the page loads the first time but i cant get it to work when new items are added when the users scrolls to the bottom.
here's my code:
$(document).imagesLoaded(function() {
$(document).ready(new function() {
// Prepare layout options.
var options = {
autoResize: true, // This will auto-update the layout when the browser window is resized.
container: $('#main'), // Optional, used for some extra CSS styling
offset: 10, // Optional, the distance between grid items
itemWidth: 320 // Optional, the width of a grid item
};
// Get a reference to your grid items.
var handler = $('#tiles li');
// Call the layout function.
handler.wookmark(options);
// When scrolled all the way to the bottom, add more tiles.
var int = 10;
function onScroll(event) {
// Check if we're within 100 pixels of the bottom edge of the broser window.
var closeToBottom = ($(window).scrollTop() + $(window).height() > $(document).height() - 100);
if(closeToBottom) {
// GET THE 10 NEXT ITEMS;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//document.getElementById("tiles").innerHTML=xmlhttp.responseText;
$('#tiles').append(innerHTML=xmlhttp.responseText);
int = int+10;
// Clear our previous layout handler.
if(handler) handler.wookmarkClear();
// Create a new layout handler.
handler = $('#tiles li');
handler.wookmark(options);
}
}
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});
var request = $.getUrlVar('item');
if(request!=null){
var allR = "?int="+int+"&item="+request;
} else {
var allR = "?int="+int;
}
xmlhttp.open("GET","tiles.php"+allR,true);
xmlhttp.send();
}
};
$(document).ready(new function() {
// Capture scroll event.
$(document).bind('scroll', onScroll);
// Call the layout function.
handler = $('#tiles li');
handler.wookmark(options);
});
});
});
Thanks in advance.
In the end i forgot to try the simplest thing, wrap the handler.wookmark in imagesLoaded:
$(document).imagesLoaded(function() {
handler.wookmark(options);
});
Full code:
$(document).imagesLoaded(function() {
$(document).ready(new function() {
// Prepare layout options.
var options = {
autoResize: true, // This will auto-update the layout when the browser window is resized.
container: $('#main'), // Optional, used for some extra CSS styling
offset: 10, // Optional, the distance between grid items
itemWidth: 320 // Optional, the width of a grid item
};
// Get a reference to your grid items.
var handler = $('#tiles li');
// Call the layout function.
handler.wookmark(options);
// When scrolled all the way to the bottom, add more tiles.
var int = 10;
function onScroll(event) {
// Check if we're within 100 pixels of the bottom edge of the broser window.
var closeToBottom = ($(window).scrollTop() + $(window).height() > $(document).height() - 100);
if(closeToBottom) {
// GET THE 10 NEXT ITEMS;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//document.getElementById("tiles").innerHTML=xmlhttp.responseText;
$('#tiles').append(innerHTML=xmlhttp.responseText);
int = int+10;
// Clear our previous layout handler.
if(handler) handler.wookmarkClear();
// Create a new layout handler.
handler = $('#tiles li');
$(document).imagesLoaded(function() {
handler.wookmark(options);
});
$(function() {
// Select all links whose attribute rel starts with lightbox
$('a[rel^=lightbox]').lightBox();
});
var scripts = domElement.getElementsByTagName("script");
for (var i = 0; i < scripts; i ++) {
eval(scripts[i].text);
}
}
}
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});
var request = $.getUrlVar('item');
if(request!=null){
var allR = "?int="+int+"&item="+request;
} else {
var allR = "?int="+int;
}
if(end==0){
xmlhttp.open("GET","tiles.php"+allR,true);
xmlhttp.send();
}
}
};
$(document).ready(new function() {
// Capture scroll event.
$(document).bind('scroll', onScroll);
// Call the layout function.
handler = $('#tiles li');
handler.wookmark(options);
});
});
});
I suggest you to use a jquery ajax function like getJson, getAjax.
I'm trying to find the answer somewhere around but i can't,
So i'm having a .bind() event and I want when's triggered to make a get query from a php file with JSON like AJAX does.
I have tried the following which doesn't work:
$(document).ready(function() {
$("#adivhere").bind("valuesChanged", function(){
// Some variables here
var max2 = 10
var min2 = 5
//The classic AJAX Request
function afunc(max2,min2){
var xmlhttp;
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
//The classic AJAX onreadystatechange function
xmlhttp.onreadystatechange=function()
{ if (xmlhttp.readyState==4 && xmlhttp.status==200){
//The code triggered
var fets = jQuery.parseJSON( xmlhttp.responseText );
var t = fets.date.split(/[-]/);
var d = new Date(t[0], t[1], t[2]);
alert(d);
}}
//The XHR request with the .php file and the
// two values that sends
xmlhttp.open("GET","getdates.php?max2="+max2+"&min2="+min2,true);
xmlhttp.send();
};
});
It looks like you're using jQuery, so this should work:
$(function(){
$('#adivhere').bind('valuesChanged',function(){
var max2 = 10;
var min2 = 5;
$.getJSON('getdates.php?callback=?', {max2: max2, min2: min2}, function(json){
alert(json);
var t = json.date.split(/[-]/);
if (t && t.length) {
var d = new Date(t[0], t[1], t[2]);
alert(d);
}
});
});
});
There's already an awesome $.getJSON method in jQuery that will do all of the heavy lifting for you, including return your results as JSON.
You'll need to make your getdates.php script echo the callback and wrap your results in parentheses so it returns as actual jQuery.
There are several "errors" in your script:
"afunc" is never called, so why should it be executed?
the parenthesis are not closed properly; at the end there are two missing: )}
I am trying to fill in a form using Javascript/ajax/php but the problem is that my function only fills in one of the needed forms and stops even tho I have gotten the second response from the server.
Code:
The function that starts filling stuff
function luePankkiviivakoodi(str) {
if (str==null) { //are we NOT injecting variables directly into the code, if not - Prompt for the barcode, and set the variable
var str = prompt("Valmis vastaanottamaan", "");
}
if (str==null) { //someone pressed abort on the prompt, we return
return;
}
newstr = str.split(' ').join(''); // remove spaces
if (str=="") { //is the string empty? -> return
return;
}
if (window.XMLHttpRequest) { //AJAX code
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
eval(xmlhttp.responseText);
//we set some fields, no problem
document.getElementById('P_VII').value = viite;
document.getElementById('IBAN').value = saajatili;
document.getElementById('laskun_summa').value = summa;
document.getElementById('eräpäivä').value = eräpäivä;
//trigger other functions
getKassasumma(summa); //AJAX for accesing the database and calculating the sale price
DevideIntoCells(); //AJAX for accessing the database and dividing a sum into different cells
validateSumma(); //Validates the sum, and tells the user if it's OK
}
}
xmlhttp.open("GET","dataminer.php?question=pankkiviivakoodi&q="+newstr,true);//open AJAX connecttion
xmlhttp.send();//send stuff by AJAX
}
getKassasumma:
function getKassasumma(str) {
if (str=="") {
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
eval(xmlhttp.responseText);
}
}
kale = document.getElementById("TOS_K_ale").value;
xmlhttp.open("GET","dataminer.php?question=kassasumma&q="+str+"&kale="+kale.replace("%", "p")+"&nro="+document.getElementById("S_NRO").value,true);
xmlhttp.send();
}
DevideIntoCells:
function DevideIntoCells() {
str = document.getElementById('tiliöintitapa').value;
if (str==null) {
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
document.getElementById("spinwheel3").style.visibility = "visible";
}
xmlhttp.onreadystatechange=function() {
//alert('OK! val= '+xmlhttp.readyState);
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
//alert('OK!');
eval(xmlhttp.responseText);
//alert('OK2!');
document.getElementById("spinwheel3").style.visibility = "hidden";
//alert('OK3!');
calculateSumma();
}
}
xmlhttp.open("GET","dataminer.php?question=percentages&q="+str+"&nro="+document.getElementById('S_NRO').value,true);
xmlhttp.send();
}
validateSumma (just some math):
function validateSumma() {
float = document.getElementById('summabox').value;
float = float.replace(",",".");
summa = parseFloat(float);
if (summa < 0) {
summa = 0
};
kassasummaunp = document.getElementById('laskun_summa').value;
kassasummafloat = kassasummaunp.replace(",",".");
kassasumma = parseFloat(kassasummafloat);
if (kassasumma < 0) {
kassasumma = 0
};
if (kassasumma == 0 || summa == 0) {
prosentti = "0%";
}
else {
prosentti = summa / kassasumma * 100;
prosentti = Math.round(prosentti*Math.pow(10,2))/Math.pow(10,2);
prosentti = prosentti+"%";
};
if (prosentti == "100%") {
is100 = 1;
}else {
is100 = 0;
}
document.getElementById('prosentti').innerHTML = prosentti;
if (is100 == 1) {
document.getElementById('prosentti').setAttribute("style", "color:green");
} else {
document.getElementById('prosentti').setAttribute("style", "color:red");
}
puuttuvaEuro();
}
The problem code here is getKassasumma(summa); and DevideIntoCells();. I disable one of them, and the other one works, I enable both of them, DevideIntoCells stops somewhere before document.getElementById("spinwheel3").style.visibility = "hidden";, probably at the eval(response) because getKassasumma already finished the ajax request and killed this one. same the other way around.
AJAX answers: DevideIntoCells:
var KP_osuus = parseFloat('40');
laskunsumma = parseFloat(document.getElementById('laskun_summa').value);
onepercent = laskunsumma/100;
newvalue = onepercent*KP_osuus;
document.getElementById('box1.5').value = newvalue;
var KP_osuus = parseFloat('60');
laskunsumma = parseFloat(document.getElementById('laskun_summa').value);
onepercent = laskunsumma/100;
newvalue = onepercent*KP_osuus;
document.getElementById('box2.5').value = newvalue;
AJAX answer: getKassasumma
var kassasumma = '477.99€';
document.getElementById('kassasumma').value = kassasumma;
Please ask if you need clarification!
EDIT: Just to be clear, this is NOT an AJAX problem, rather javascript.
I think you are 'swimming in it', how we say. If you begin with AJAX, I'd recommend you use a framework like jQuery and it's $.get() or $.post() functions. It will accomplish all the needed AJAX logic for you.
Try to make xmlhttp local, i.e.
var xmlhttp;
Because you are overwriting you xmlhttp you refer to in the event listeners, so when the listeners get called, they both see the same response.
at the beginning of every of your functions. For compatibility, also use send(null) instead of send().