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);
});
});
});
Related
I successfully added a video to a playlist but it is added multiple times (sometimes twice and sometimes more). Can anybody help?
$resourceId = new Google_Service_YouTube_ResourceId();
$resourceId->setVideoId($videoID);
$resourceId->setKind('youtube#video');
$playlistItemSnippet = new Google_Service_YouTube_PlaylistItemSnippet();
$playlistItemSnippet->setPlaylistId($playlistId);
$playlistItemSnippet->setResourceId($resourceId);
$playlistItem = new Google_Service_YouTube_PlaylistItem();
$playlistItem->setSnippet($playlistItemSnippet);
$playlistItemResponse = $youtube->playlistItems->insert('snippet,contentDetails', $playlistItem, array());
Solved it myself and I'm pretty proud of it :)
I realised that the ajax was triggering the above php script on mouseover. So every time I hovered away from the checkbox element the php script triggered multiple times.
I changed the mouseover code with the following:
$(function() {
$('input.Chilltrap').on('click', function(e) {
var chilltrap = this.id;
if( $("input[name=" + chilltrap + "]").prop('checked') ) {
checkboxstatusCt = "Yes";
}
else {
checkboxstatusCt = "No";
}
var url = "url.php";
var params = "c="+checkboxstatusCt+"&s="+chilltrap;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
$("#error").html(xmlhttp.responseText);
$("#error"). fadeIn('fast');
setTimeout(function(){
$("#error"). fadeOut('slow');
},2000);
}
};
xmlhttp.open("GET", url+"?"+params,true);
xmlhttp.send();
});
});
Hi everybody!
I have a problem and I have no idea how to fix it!
I have a simple HTML page with a button:
<input type = "submit" value = "ok" onclick="f1()"/>
I also have a script on this page:
<script>
function f2()
{
var firstBtn = document.createElement("button");
firstBtn.appendChild(document.createTextNode("firstBtn"));
document.body.appendChild(firstBtn);
var xmlhttp = CreateRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var response = xmlhttp.responseText;
document.body.innerHTML += response;
}
}
firstBtn.onclick = function()
{
alert("inside f2 onclick");
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
}
function f3()
{
var secondBtn = document.createElement("button");
secondBtn.appendChild(document.createTextNode("secondBtn"));
document.body.appendChild(secondBtn);
var xmlhttp = CreateRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var response = xmlhttp.responseText;
document.body.innerHTML += response;
}
}
secondBtn.onclick = function()
{
alert("inside f3 onclick");
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
}
function f1()
{
f2();
f3();
}
function CreateRequest()
{
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();// code for IE7+, Firefox, Chrome, Opera, Safari
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");// code for IE6, IE5
return xmlhttp;
}
</script>
So now, when I click one of the buttons (firstBtn or secondBtn), another one is not responding to the click event! Does anybody know why?
As #vishwanath said (see comments to this question), when I doing
document.body.innerHTML += response;
I'm destroying and recreating all the content of my page therefore I'm losing my events.
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.
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 have this function below and I call that function in a loop I get the alert n times but only n-1 or sometimes n-2 responses
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)
{
alert(xmlhttp.responseText);
//document.getElementById("warnings_panel").innerHTML+=xmlhttp.responseText;
}
}
alert("in ajax)
xmlhttp.open("GET","getresponse.php?start="+ start + "&end=" + end,true);
xmlhttp.send();
I have made a class (that you can modify easily) for calling a function in loop and it calls the functions correctly. Maybe this could apply to your need.
(Also if anyone sees something wrong it's good to hear from others)
test.htm
<html>
<head>
<script type="text/javascript">
function myXmlHttp() {
/*constructor simulator*/
this.setPersitent=
function (file, onReadyFunc,params,loop)
{
myXmlHttpObj.loop = loop;
myXmlHttpObj.file=file;
myXmlHttpObj.onReadyFunc='myXmlHttpObj.'+onReadyFunc;
myXmlHttpObj.params=params;
myXmlHttpObj.mySetRequest();
}
this.setParams=
function ( params )
{
myXmlHttpObj.params=params;
}
<!--Standard initial code-->
this.mySetRequest =
function ()
{
request = false;
try { request = new XMLHttpRequest(); }
catch (trymicrosoft) {
try { request = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (othermicrosoft) {
try {request = new ActiveXObject("Microsoft.XMLHTTP");}
catch (failed) {request = false;}/*catch3*/}/*catch2*/}/*catch1*/
if (!request)
alert("Error initializing XMLHttpRequest!");
} /*func*/
this.mySendReq=
function()
{
var url = myXmlHttpObj.file;
request.open("POST", url, true);
//Some http headers must be set along with any POST request.
request.setRequestHeader
("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
request.setRequestHeader("Content-length", myXmlHttpObj.params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = eval(myXmlHttpObj.onReadyFunc);
request.send(myXmlHttpObj.params);
}
this.listenPHP =
function ( ) {
if ( request.readyState == 4) {
if ( request.status == 200)
{
alert(request.responseText);
myXmlHttpObj.loop--;
if(myXmlHttpObj.loop>0)
{
myXmlHttpObj.setParams("js_rand="+Math.random()+"");
myXmlHttpObj.mySendReq();
}
}//inner if
else{alert("status is " + request.status);}
}//outer iff
}//function
}//END
myXmlHttpObj = new myXmlHttp();
myXmlHttpObj.setPersitent
('getresponse.php', 'listenPHP',"js_rand="+Math.random()+"",3) ;
myXmlHttpObj.mySendReq();
</script>
</head>
<body >
</body>
</html>
and getresponse.php
<?PHP
echo 'I recived this random from js:',$_POST['js_rand'],'
this rand is from php:',rand(1,9999);
?>
onreadystatechange gets terminated when your function ends because the xmlhttp object gets removed as it is not a global variable. Am I right?
Better would be to put only the AJAX request in a function, so that the xmlhttp object is only created once (I used a shorter version to create the xmlhttp object in this example).
var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
function request() {
xmlhttp.open('GET', 'getresponse.php?start=' + start + '&end=' + end, true);
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.send(null);
}
Generally, this should work, but we need more information about how you actually run that loop to know what might be wrong.
I also added encodeURIComponent and changed the condition inside the callback function, because status isn't always 200 when readyState reaches 4.
function request(start, end) {
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open('GET', 'getresponse.php?start=' + encodeURIComponent(start) + '&end=' + encodeURIComponent(end), true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4)
if (xmlhttp.status == 200) {
alert(xmlhttp.responseText);
} else {
// status ≠ 200, output useful error message
}
};
xmlhttp.send();
}