Need Javascript to locate individual divs looped by PHP - javascript

I managed to create a PHP loop that takes an array and create multiple copies of the same button while the buttons each have their own idenfication ("adiv_1" , "adiv_2", "adiv_3", etc). I have a javascript function that is able to take a single button "before it was called just 'adiv'" and change the text of the button if one clicks on it.
However due to the PHP loop which named it "adiv_1 or adiv_2 or adiv_3", I don't know how to create a javascript function that can take one of the buttons looped with a different identification div tag and get javascript to identify each one if one click on a certain button in that group. Can anyone help?
PHP loop that create the group of buttons
<?php
$array_query = mysql_query("SELECT * FROM person_finder_info");
$i = 0;
while($search_row = mysql_fetch_array($array_query)){
?>
<p><button type="button" onclick='load()'><div id='adiv_<?php echo $i?>'>Add this person</div></button></p>
<?php
$i++;
}
?>
Javascipt / AJAX function that changes button text (by getting echoed information in PHP file)
//Changes button text to "You added him!"
function load(){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("adiv_1").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET','include.inc.php', true);
xmlhttp.send();

This is rudimentary, but I think you're trying to do something like this, just loop inside of the onreadystatechange function like you did in the other one to display what you want in there to handle all of the buttons.:
<?php
for($i = 0; $i < count($array); $i++)
{
?>
<p><button type="button" onclick='load()'><div id='adiv_<?php echo $i;?>'>Add this person</div></button></p>
<?php
}
?>
<script>
//Changes button text to "You added him!"
function load(){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
<?php
echo "var divArray = {";
for($i = 0; $i < count($array); $i++)
{
echo "'adiv_".$i."'".($i < $count-1 ? "," : "");
}
echo "};" /// after the loop this will output like var divArray = {'adiv_1','adiv_2', ... };
?>
for (var i = 0; i < divArray.length; i++) {
document.getElementById(divArray[i]).innerHtml(dataFromResponse[i]); // assuming you've processed the response from AJAX into an array
}
}
}
xmlhttp.open('GET','include.inc.php', true);
xmlhttp.send();
</script>
I can't help you with setting up all of the button innerHTML though since I don't know what kind of response you're getting from AJAX. This is just to lead you in the right direction.

Related

Why won't my innerHTML change upon PHP echo?

I have a program that gets an input from an HTML input field
<form method>
<input name="filmslike" id="input">
</form>
Then it goes through a javascript file that gets an ajax response from a PHP file
let div2Change = document.getElementById("div2Change");
let input = document.getElementById("input");
input.addEventListener("change", getTable);
function getTable(){
let ajax = new XMLHttpRequest();
ajax.open("GET", "filmslike.php");
ajax.send();
ajax.onreadystatechange = function(){
if (ajax.readyState == 4 && ajax.status == 200){
alert("in if");
array = JSON.parse(ajax.responseText);
str = "<table class='table'>";
for (i = 0; i < array.length; i++){
str += "<tr><td>" + array[i] + "</td></tr>";
}
str += "<table>";
div2Change.innerHTML = str;
}
}
}
the PHP file gives back an array from a database
require "DatabaseAdaptor.php"; // This includes class DatabaseAdaptor as if it where above this code.
$theDBA = new DatabaseAdaptor(); // constructor a DatabaseAdaptor object.
$moviesLike = $_GET['filmslike'];
$array = $theDBA->getAllMoviesLike($moviesLike);
echo json_encode($array);
and the database function returns items that are similar to $part
public function getAllMoviesLike($part) {
$stmt = $this->DB->prepare("SELECT * FROM movies WHERE name like '%" . $part . "%'");
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
I don't understand why I'm not getting any change to my innerHTML. The alert says that it goes into the if statement (though it only activates inconsistently). I tried to use POST instead of GET, and it didn't work. What is wrong?
You don't send anything to the server for searching from AJAX. You need to add input value to the request:
ajax.open("GET", "filmslike.php?filmslike="+document.getElementById("input").value);
ajax.send();

Repeat PHP function every 2 seconds

So I have a code, where a number is retrieved from a text file and is displayed through HTML.
The thing is that it only retrieves the number when I refresh the page. If I change the number on other page, it doesn't change on the other page.
I've seen similar questions before, most of them said to use AJAX, but I don't understand much about AJAX and I only need it for this bit of code, it's not like I'm going to constantly use it. I would like to know if there is any other besides AJAX and if there is only AJAX, please present examples of code.
PHP code:
<?php
$file = "num.txt"; //Path to your *.txt file
$contents = file($file);
$num = implode($contents);
?>
JavaScript code. Basically it gets the PHP value and outputs to the html.
document.getElementById("num").innerHTML = '<?php echo $num; ?>';
Keep in mind, I don't want to refresh the page. Just the variable.
EDIT: PHP code - Getting an error - Notice: Undefined index: keynum in C:\xampp\htdocs\num.php on line 3
Here is the code of the PHP
<?php
$keynum = $_POST['keynum'];
$post = "INSERT INTO post (keynum) VALUES ($keynum)";
$fileLocation = getenv("DOCUMENT_ROOT") . "/num.txt";
$file = fopen($fileLocation,"w");
$content = $keynum;
fwrite($file,$content);
fclose($file);
echo 'Response';
die();
?>
You can achieve what you want using XMLHttpRequest, like this:
function updateData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('num').innerHTML = this.responseText;
}
};
xhttp.open('GET', '/num.php', true);
xhttp.send();
}
setInterval(updateData, 2000);
If you want to refresh the variable without refreshing the page, then you need to use an asynchronous request. It doesn't need to be AJAX, you can use the native XMLHttpRequest() function.
If you want more info: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
or with jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
setInterval(function(){
$.ajax({url:"num.php", success:function(result){
$("#num").html(result);
}});
}, 3000);
</script>
<textarea id="num"></textarea>
get_nbr.php
<?php
$file = "num.txt"; //Path to your *.txt file
$contents = file($file);
$num = implode($contents);
echo $num;
?>
index.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!---trigger get_nbr() on page load on an infinite loop every two seconds -->
<body onload="setInterval(get_nbr, 2000)">
<script>
function get_nbr() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("num").innerHTML = this.responseText;
}
};
xhttp.open("GET", "get_nbr.php", true);
xhttp.send();
}
</script>
<p id="num"></p>
like this.
let url = ""; //whatever url your requesting.
setInterval(function(){
var x = new XMLHttpRequest();
x.open("GET" , url , true);
x.onreadystatechange = function(){
if(x.readyState == 4 && x.status == 200)
{
document.getElementById("num").innerHTML = x.responseText;
}
}
x.send();
} , 2000);
-- UPDATE , added post --
setInterval(function(){
var x = new XMLHttpRequest();
x.open("POST" , url , true);
x.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
x.onreadystatechange = function(){
if(x.readyState == 4 && x.status == 200)
{
document.getElementById("num").innerHTML = x.responseText;
}
}
x.send("postVar1=123");
} , 2000);

Javascript code not working on PHP include

So I have a main page which have buttons, each buttons contain names, when I click that button I want to pop up div which shows information of that person, I used ajax to retrieve info from php,
var strURL="searchSender.php?ID="+ID;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
outMsg=req.responseText;
var prevWin = document.getElementById("senderInfo");
prevWin.innerHTML = outMsg;
prevWin.style.top = 50+"px";
prevWin.style.right = 80+"px";
prevWin.style.visibility = "visible";
} else {
alert("Problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
searchSender.php basically redeem info of that specific person from the database, that returns these codes (i didn't include here the code that retrieves data from database)
<label>Name: <?php echo $row['Name'];?> </label></br>
<label>Address: <?php echo $row['Address'];?></label></br>
<label>Contact: <?php echo $row['ContactNumber'];?></label></br>
<div id="divSenderMap">
<?php
$url = "mapSender.html";
$_SESSION['SenderID'] = $row['ID'];
include $url ?>
</div>
<input type="button" id="btnSendReply" value="SEND"/>
<input type="button" id="btnCloseDiv" value="X" onclick="closeDiv()"/>
mapSender.html is supposed to return a map where the person is, the code is working on any other file/page, but it does not do it here. It is returning php and html codes but not javascript codes. What could be wrong?
As #MichaelLonghurst told it seems your file is named mapSender.html. So the server does not call PHP before return the HTML.
You should rename mapSender.html into mapSender.php.

Live Search Using Ajax and PHP mysql

I created a Live Search using AJAX,PHP and mysql.here when I click on search result ,redirecting me to a particular page it works perfectly. Now I need a small change.
All I need is:
When I click on the search result, that particular result should be display in the input field.
Here is my AJAX code:
<script type="text/javascript">
END OF AJAX CODE
PHP CODE
<?php
ob_start();
session_start();
include("Base.php");
$dbase=new Base();
#$userID=$_SESSION['userID'];
$createdDate=date("Y-m-d");
$createdTime=date("h:i:s A");
$partialStates=mysql_escape_string($_REQUEST['q']);
$qryy="SELECT * from `gon_pro` WHERE `pro_name` LIKE
'%$partialStates%' ";
$pser=$dbase->execute($qryy);
$ser_nums=mysqli_num_rows($pser);
while($co[]=mysqli_fetch_array($pser)){
}
?>
<?php
foreach ($co as $key => $namo) {
$cv=$namo['pro_name'];
$cv_id=$namo['id'];
$cv_p=$namo['price'];
?>
<a href="pro_det.php?prolod=<?php echo $cv_id; ?>"><p class="res
col-md-6"><?php echo $cv; ?></p></a>
<?php
}
?>
END OF PHP CODE
function getStates(str) {
if (str.length == 0) {
document.getElementById("row").innerHTML = "";
document.getElementById("results").innerHTML =""
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("results").innerHTML =
xmlhttp.responseText;
}
};
xmlhttp.open("GET", "support/getStates.php?q=" + str, true);
xmlhttp.send();
}
}
</script>

redirect location after execution is wrong

I have been mulling over this for hours, to the point of myopia looking at this screen and I can't figure out what is causing the problem.
I can a script which redirects to a unique page (defined in variables) after execution. The script works fine but the location it redirects to is wrong every time.
For example. A user has 4 links to check, lets say they are new comments on his/her page. When he/she clicks the link it directs to the oldest one every time. Not the one they clicked on.
I have 2 parts of code:
<?
$result_s = mysql_query("SELECT * FROM pins a LEFT JOIN comments b ON a.id = b.pin_id WHERE b.to_id = '$myid' AND b.status = '0' ORDER BY date DESC");
$rows = array();
while ($row = mysql_fetch_assoc($result_s)) {
$jS = '"'.$row[id].'"';
$boardid = $row['board_id']; // collection id
$postid = $row['pin_id']; // post id
$posturl = $row['pin_url']; // post id
echo "<table width='100%'><tr>";
echo "<td align='center'><a href='javascript:setActive(".$jS.")'><img src='".$posturl."' height='100'><br>".$boardid."/".$postid."</a></td>";
echo "</tr></table>";
}
?>
and
<script type="text/javascript">
function setActive(ObjID) {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
//Return Value. Handle as you wish. Display or ignore.
var x = xmlhttp.responseText;
if (document.getElementById(ObjID).style.color == 'black') document.getElementById(ObjID).style.color='red';
else document.getElementById(ObjID).style.color='black';
document.getElementById(ObjID).innerHTML = '<center><font face="Century Gothic">' + x + '</font></center>';
}
}
var p_str = "a="+ObjID;
xmlhttp.open("POST","/application/views/setActive.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(p_str);
location.href="/board/pins/<?php echo $boardid; ?>/<?php echo $postid; ?>";
}
</script>
I have tried using different variables in the location part of the script but nothing works. I'm not educated in this so maybe I'm missing something that is glaringly obvious to some programmers out there, which is my reason for asking here.
Can you see what the problem might be?
There are a few issues
The A in Ajax stands for asynchronous. So whatever you do right after the .send is executed BEFORE the Ajax call (The use of XMLHttpRequest is called Ajax)
You call the function with an ObjID which is then acted upon in the RETURN of the Ajax call (whatever is inside the xmlhttp.onreadystatechange) but not known in there since ObjID is not global and not copied to the scope (closure)
Try this
function setActive(ObjID) {
var xmlhttp = window.XMLHttpRequest?new XMLHttpRequest():
new ActiveXObject("Microsoft.XMLHTTP");
var ID = ObjID
xmlhttp.onreadystatechange = function(id) {
return function() {
if (this.readyState != 4) return;
if (this.status == 200) {
var obj = document.getElementById(id); // id is passed now
var style = obj.style; // but please use CSS intead
style.color = style.color == 'black'?'red':'black';
style.fontFamily = "Century Gothic";
style.textAlign="center";
obj.innerHTML = xmlhttp.responseText;
setTimeout(function() {
location.href="/board/pins/<?php echo $boardid; ?>/<?php echo $postid; ?>"
},3000); // assuming this is what you want
};
}(ID); // passing the ObjID
}
var p_str = "a="+ObjID;
xmlhttp.open("POST","/application/views/setActive.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(p_str);
}

Categories