Generated anchor links in ajax not working - javascript

Problem:
I have a which is filled via Ajax. There are some local anchors which are created in this table. When an anchor is clicked, it is supposed to turn a which is hidden to visible and scroll to it automatically. All of this is working when I am filling my by hand (visibility + scroll), but not at all when the is filled via Ajax.
I have the following structure in my index.php file:
<section id="section1">
<table></table>
</section>
<section id="section2>
(this section is hidden via CSS)
</section>
<!-- When the link "More infos" is clicked -->
<script>
$('.moreInfos').click(function() {
if ($('#section2').is(':hidden')) {
$('#section2').slideDown('slow');
}
});
</script>
<!-- Ajax call -->
<script language="JavaScript">
function createInstance()
{
var req = null;
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e)
{
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e)
{
alert("XHR not created");
}
}
}
return req;
};
function storing(data)
{
var element = document.getElementById('banques');
element.innerHTML = data;
}
function submitForm()
{
var req = createInstance();
var montant = document.getElementById("montant").value;
var mois = document.getElementById("selectMois").value;
var taux = '<?php echo $taux; ?>' ;
var data = "taux=" + taux + "&montant=" + montant+ "&mois=" + mois+"&tag=" + 1;
req.onreadystatechange = function()
{
if(req.readyState == 4)
{
if(req.status == 200)
{
storing(req.responseText);
}
else
{
alert("Error: returned status code " + req.status + " " + req.statusText);
}
}
};
req.open("POST", "fonction/table.php", true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(data);
}
</script>
The "Simulate" link calls a php file in ajax which will load the table.
Here is the php file called in Ajax :
<?php
include('BDD.php');
echo' <tr>
<th></th>
<th>Banque</th>
<th>Taux</th>
<th>Frais</th>
<th>Mensualité</th>
<th>Plus d\'infos</th>
</tr>';
$tag=1;
$sql="select * from banque where BAN_change=0 and BAN_tag=".$_POST['tag']." ORDER BY BAN_Ordre";
$select=$bdd->query($sql);
$result=$select->fetchAll();
$nb=count($result);
if ($nb!=0){
foreach($result as $value){
$taux=$_POST['taux']+$value['BAN_Taux_Credit'];
$mensu=$_POST['montant']/$_POST['mois'];
$mensu+=$mensu*$taux/100;
echo'<tr>';
echo'<td><img width="50" height="20" src="img/'.$value['BAN_Id'].'/img.jpg" /></td>';
echo'<td>'.$value['BAN_Nom'].'</td>';
echo'<td>'.$taux.'</td>';
echo'<td>'.$value['BAN_Frais'].'</td>';
echo'<td>'.$mensu.'</td>';
echo('<td>More infos</td>');
echo'</tr>';
}
}
?>
Summary: When the user clicks on "More infos", the #section2 is supposed to appear and the browser window scrolls to it. Now this is working perfectly when I fill the by hand. Then the #section2 is showing and the browser is scrolling to the #section2. When I am doing it via Ajax, the anchors are not working anymore.
Thanks

Because events do not magically get attached when you add new ones
$('.moreInfos').click(function() {
if ($('#section2').is(':hidden')) {
$('#section2').slideDown('slow');
}
});
Your code needs to use event delegation
$(document).on("click", '.moreInfos', function() {
if ($('#section2').is(':hidden')) {
$('#section2').slideDown('slow');
}
});

This maybe due to the HTML not being loaded into the DOM. Please try using:
$(document).on('click', '.selector', function() {
alert("Working");
});
"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page."
If this works then you can fine tune it afterwards.
Regards,

Related

Get HTML id with JQuery through AJAX

I'm stuck..I have made a system which gets all colleges from a specific subject, and I want javascript to select the college the user has selected when he clicks on one so the presence of that class can be shown, just a summary: the user selects a subject, an AJAX request gets all colleges from that subject and another AJAX request has to get that specific college and use it to display the data.
This specific function gets the data from the subjects and displays them in a div with the id 'colleges'
function showAanwezigheid(str) {
if (str == "") {
document.getElementById("colleges").innerHTML = "";
return;
} else {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("colleges").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","../controller/docentController.php?action=getColleges&vak="+str,true);
xmlhttp.send();
}
}
Here is the controller which calls the query and displays the result:
$vak = $_GET['vak'];
$colleges = $q->getColleges($vak);
echo "<select id='college'>";
echo "<option>Selecteer een college:</option>";
foreach($colleges as $college){
echo "<option value='".$college->getCollege()."'>College ".$college->getCollege()."</option>";
}
echo "</select>";
}
This is the id where the result is being displayed
<span id="colleges"></span>
And this function should select the 'select' tag with the id 'college' to get that value on change
$(document).ready(function(){
$('#vak').on('change', function() {
var vak = this.value;
alert(vak);
$('#college').on('change', function() {
var college = this.value;
alert(college);
});
});
});
I feel like there would be such an easy fix but I just can't seen to make it work...
Change jQuery code like below:-
$(document).on('change','#vak',function() {
var vak = $(this).val();
alert(vak);
});
$(document).on('change','#college',function() {
var college = $(this).val();
alert(college);
});
Note:- Make sure that jQuery library added before your script code. Otherwise you will get $ is undefined error
This is called Event Delegation
IF you want to get the value of the #college select on change then this would be simpler:
$(document).ready(function(){
$('#vak').on('change', function() {
var vak = $(this).val();
alert(vak);
});
$('#college').on('change', function() {
var college = $(this).val();
alert(college);
});
});
IF you noticed, The onchange of the #vak and the #college is separated

Refresh the result of OnKeyUp Search Filter

I have the onkeyup search function its working fine without any issue.
I want that when I will write in a textbox and there is a part of result I want to keep updating without reloading full page.
I have used the below code for refresh automatically after xxx seconds, it is refreshing the part of div using the below code of refresh but on key change, not automatically. I need it to be refreshing automatically after xxx seconds.
In the result there is close and open button if office time is still valid or closed. if i searched with OnKeyUp and it showed me the result with TRAVEL office is open and after 5 seconds its timing will finish for that i need to keep that refresh code to work on that time when the time will finish and will refresh it.
help is needed in this, please if somebody can adjust it.
Code for refresh:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#pen').load('sample.php');
}, 1000); // the "3000"
});
HTML
<form class="well-home span6 form-horizontal">
<input type="text" id="book" onKeyUp="book_suggestion()">
</form>
<!-- Display Result of onkeyup Search -->
<div class="check" id="suggestion">
<!-- Refresh here -->
<div class="row check" id="pen">
</div>
</div>
JS of onkeyup
function book_suggestion() {
var book = document.getElementById("book").value;
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "textboxSearch=" + book;
xhr.open("POST", "sample.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
document.getElementById("suggestion").innerHTML = xhr.responseText;
document.getElementById("suggestion").load = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
This is a typicall example, how to confuse yourself by mixing the jQuery with vanilla javascript and on..... event on an element. Once, you use jQuery, let use it's advantages.
First of all, organize your things, and use only jQuery, remove the onKeyUp from element.
//Setinterval
var timer = setInterval(function () {
$('#pen').load('sample.php');
}, 1000);
$('#book').on('keyup', function() {
$('#suggestion').load('sample.php', {action: 'onkeyup', textboxSearch: $(this).val()}, function(response) {
console.log('Response of sample: ' + response + ' if you need');
});
});
But, your main problem is that you update $('#pen') in your timer, what is ok, but when you execute the keyup it is update the whole #suggestion so the $('#pen') will loss.

How to make sure that I can scroll up in AJAX chat

I am building a vanilla JS, AJAX chat (so no jQuery or other toolkits). The messages are loaded via AJAX and put in a div that uses overflow-y: scroll; so you can scroll through all the messages.
Because the latest messages appear at the bottom I have a scrollDown() function that scrolls to the end of the div:
function scrollDown()
{
var objDiv = document.getElementById("chatbox");
}
The problem is that I can't scroll up. If I do that I will get to the bottom again. This is because on every ajax call I scroll down. But how can I make sure that if an user is scrolled up in the div (so he/she is reading past messages) that it doesnt scroll down when AJAX gets updated.
I already tried some things with div.scrollHeight, div.scrollTop but unfortunately it didn't work. I also did a lot of Google searches but no luck either and most them were jQuery though. Here is my code;
<script type="text/javascript">
getBerichten();
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}
function doWork(id, user_id) {
nieuwbericht = getHTTPObject();
if (nieuwbericht != null) {
if( document.getElementById('bericht').value != "")
{
nieuwbericht.open("GET", "ajaxberichten.php?id=" + id + "&user_id=" + user_id + "&bericht="
+ document.getElementById('bericht').value, true);
nieuwbericht.send(null);
document.getElementById("bericht").value = "";
}
}
}
function setOutput()
{
if(httpObject.readyState == 4){
document.getElementById('berichten').innerHTML = httpObject.responseText;
bericht = document.getElementById('chatbox');
scrollDown();
setInterval(getBerichten(),1000);
}
}
function getBerichten()
{
httpObject = getHTTPObject();
if (httpObject != null)
{
httpObject.open("GET", "ajaxgetberichten.php?id=<?php echo $_GET['id'] ?>", true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput;
}
}
function scrollDown()
{
var objDiv = document.getElementById("chatbox");
objDiv.scrollTop = objDiv.scrollHeight;
}
</script>
<div class="postbox">
<div class="post">
<div class="chatbox" id="chatbox">
<div id="berichten"></div>
</div>
<form method="post" action="">
<textarea name="bericht" id="bericht"rows="20" cols="85"> </textarea>
<input name="verstuur" type="button" onclick="doWork(<?php echo $_GET["id"] ?>, <?php echo $user_id ?>);" value="Verstuur"/>
</form>
</div>
</div>
Could somebody please tell me how to fix this without a JS toolkit like jQuery?
Thanks

Is there any way to run a php script by clicking on a li tag using ajax?

So I am trying to create an addFriend() function that only activates when an li tag within the HTML is clicked. This is my very simple HTML block that is relevant to the question:
<li id="add_friend" onclick="addFriend();">Add friend</li>
This is my javascript function that is called when the li tag is clicked. I am using a get request for the ajax response.
function addFriend() {
document.getElementById("add_friend").innerHTML = "please wait...";
//ajax
var ajax = new XMLHttpRequest();
ajax.open("GET", "php/friend.php", true);
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
document.getElementById("add_friend").innerHTML = ajax.responseText;
}
};
ajax.send();
}//END addFriend
This is what friends.php looks like. It just a temporarily test function
<?php
echo "This is a test";
?>
I just threw an echo within the php script to check if there was a response. However every time I click on the li tag I receive a 500 error on the ajax.send(); line of code in the javascript. What am I doing wrong?

onkeyup function only firing once

I need the onkeyup to fire more than once, but it seems to be only firing once!
When I enter something into the input box, it searches, but then whenever I backspace and search something else, the div stay's the same..
Here is my code:
<script type="text/javascript">
function suggest1() {
var dam_text = document.getElementById('dam').value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('MicrosoftXMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
}
}
var target = 'dam_search.php?dam_text=' + dam_text;
xmlhttp.open('GET', target, true);
xmlhttp.send();
}
</script>
<input type="text" name="dam" id="dam" onkeyup="suggest1();"><br />
<div id="myDiv"></div>
Here is dam_search.php
<?php
//connect to db stuff here
if (isset($_GET['dam_text'])) {
$dam = $_GET['dam_text'];
getSuggest($text);
}
function getSuggest($text) {
$sqlCommand = "SELECT `name` FROM `table1` WHERE `name` LIKE '%$dam_text%'";
$query = mysql_query($sqlCommand);
$result_count = mysql_num_rows($query);
while ($row = mysql_fetch_assoc($query)) {
echo $row['name'].'<br />';
}
}
?>
ALSO: I am wondering how I can put the return of the name's it has searched into a dropdown from the input box instead of into the div, so when I click on one of the names, it auto fills the input box.
Thank you!
Still not sure about your issue with the keyup only firing once per page-load. That's very hard to speculate reasonably on without seeing more code. Never-the-less, here's an example I just threw together of how you can present the returned data in a more useful way.
The code requires that you download the AjaxRequest library I mentioned in an earlier comment.
(http://ajaxtoolbox.com/request/)
Here, I demo a few principles.
Arranging the data into a php class
constructing an array of instances of this class
returning this array as JSON
catching the JSON text and turning it back into an object in JS
Processing the data
I've given 2 very simple example - the first simply loads all filenames in the current directory (that holds jsonDir.php) into a select element. Choosing a filename results in it being copied into a text input next to the button.
The second, only retrieves names of png files. It chucks them all into a select element too. This time however, when an item is selected it is used as the src for an image. In each case the filenames are only grabbed if/when the corresponding button is pressed. There's a bit of redundant/otherwise crappy code I could have done better, but after 20 hours awake, I'm ready for bed!
Hope it's useful for you. Any questions, just ask. :)
1. jsonDir.php
<?php
class mFile
{
public $name, $time, $size;
}
if (!isset($_GET['wildcard']))
$wildCard = "*.*";
else
$wildCard = $_GET['wildcard'];
foreach (glob($wildCard) as $curFilename)
{
$curFileObj = new mFile;
$curFileObj->name = $curFilename;
$curFileObj->time = date("d/m/Y - H:i", filectime($curFilename));
$curFileObj->size = filesize($curFilename);
$fileArray[] = $curFileObj;
}
printf("%s", json_encode($fileArray));
?>
2. readDir.html
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='script/ajaxRequestCompressed.js'></script>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function myGetAjaxResponseWithCallback(url, target, callbackFunc)
{
AjaxRequest.get(
{
'url':url,
'onSuccess':function(req){ callbackFunc(req.responseText, target); }
}
);
}
function getResults1()
{
var url = "jsonDir.php";
var target = byId('resultsDiv');
myGetAjaxResponseWithCallback(url, target, jsonDataReceived1);
}
function getResults2()
{
var url = "jsonDir.php?wildcard=*.png";
var target = byId('resultsDiv2');
myGetAjaxResponseWithCallback(url, target, jsonDataReceived2);
}
function jsonDataReceived1(responseText, targetContainer)
{
var resultObject = JSON.parse(responseText);
targetContainer.innerHTML = "";
var mStr = "There were " + resultObject.length + " records returned" + "<br>";
var mSel = newEl("select");
mSel.addEventListener('change', doAutofill, false);
var i, n = resultObject.length;
for (i=0; i<n; i++)
{
var curRecordOption = new Option(resultObject[i].name, i);
mSel.appendChild(curRecordOption);
}
targetContainer.innerHTML = mStr;
targetContainer.appendChild(mSel);
}
function jsonDataReceived2(responseText, targetContainer)
{
var resultObject = JSON.parse(responseText);
targetContainer.innerHTML = "";
var mSel = newEl("select");
mSel.addEventListener('change', showSelectedImg, false);
var i, n = resultObject.length;
for (i=0; i<n; i++)
{
var curRecordOption = new Option(resultObject[i].name, i);
mSel.appendChild(curRecordOption);
}
targetContainer.innerHTML = '';
targetContainer.appendChild(mSel);
}
function doAutofill(e)
{
var curSelIndex = this.value;
var curText = this.options[curSelIndex].label;
byId('autofillMe').value = curText;
}
function showSelectedImg(e)
{
byId('previewImg').src = this.options[this.value].label;
}
</script>
<style>
img
{
border: solid 2px #333;
}
</style>
</head>
<body>
<button onclick='getResults1()'>Get *.* dir listing</button> <input id='autofillMe'/>
<div id='resultsDiv'></div>
<hr>
<button onclick='getResults2()'>Get *.png dir listing</button> <img id='previewImg' width='100' height='100'/>
<div id='resultsDiv2'></div>
</body>
</html>
Found out my problem. The query wasn't correctly being processed!
I had the variable $dam_text as the LIKE statement, when it should have been $dam:
<?php
//connect to db stuff here
if (isset($_GET['dam_text'])) {
$dam = $_GET['dam_text'];
getSuggest($text);
}
function getSuggest($text) {
$sqlCommand = "SELECT `name` FROM `table1` WHERE `name` LIKE '%$dam_text%'";
$query = mysql_query($sqlCommand);
$result_count = mysql_num_rows($query);
while ($row = mysql_fetch_assoc($query)) {
echo $row['name'].'<br />';
}
}
?>
Also, the variable $dam wasn't being submitted inide the function, so I moved it from the 'if' statement, into the function:
<?php
//connect to db stuff here
if (isset($_GET['dam_text'])) {
getSuggest($text);
}
function getSuggest($text) {
$dam = $_GET['dam_text'];
$sqlCommand = "SELECT `name` FROM `table1` WHERE `name` LIKE '%$dam%'";
$query = mysql_query($sqlCommand);
$result_count = mysql_num_rows($query);
while ($row = mysql_fetch_assoc($query)) {
echo $row['name'].'<br />';
}
}
?>
The above code works perfectly! Turns out it wasn't onkeyup after all! Thanks for all your help!
OnKeyUp will only fire once per event. pressing 'A' 'B' and 'C' will result in three calls to suggest1();
To make sure your browser is working correctly try this
<script type="text/javascript">
function suggest1() {
document.getElementById('myDiv').innerHTML = document.getElementById('dam').value;
}
</script>
<input type="text" name="dam" id="dam" onkeyup="suggest1();"><br />
<div id="myDiv"></div>
You should see the div change for every keystroke that occurs in the input.
There is two many unknowns for me to directly point at your actual issue.
Your PHP will output nothing for a zero entry query, and will only output 1 item if you query LIKE only matches one thing. I think your problem lies elsewhere, an not with onkeyup
T test to onkeyup on your system/browser:
Try adding some debug header like echo strlen($text).'<br />'; to your PHP file. You should see the number change with out relying on your SQL query for every key press that adds or deletes text (that includes the backspace key).
Your code looks fine. And runs fine for me using the public HTTP GET echo service at http://ivanzuzak.info/urlecho/
Swapping out your PHP for the echo service works fine (with a bit of a typing delay)
<script type="text/javascript">
function suggest1() {
var dam_text = document.getElementById('dam').value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('MicrosoftXMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
}
}
var target = 'http://urlecho.appspot.com/echo?body=' + dam_text;
xmlhttp.open('GET', target, true);
xmlhttp.send();
}
</script>
<input type="text" name="dam" id="dam" onkeyup="suggest1();"><br />
<div id="myDiv"></div>

Categories