I have a script that rotates some images from their current position, there are 4 available rotations(positions) of the image and they are present by the values 0,1,2,3. My problem is that I need two variables from the database in my AJAX call to make this happen. I need the rotation and the src. My PHP currently look like this; Please notice the query where I take out rotation and src.
<?php
$item_number = -1; //This value is -1 in order to make the list start on 0
$rowsize = 12;
$itemArray = array();
$finalArray = array();
$results = 0;
for ($i = 0; $i < $rowsize; $i++) {
$stmt = $mysqli->stmt_init();
$stmt->prepare('SELECT z, rotation, src, name FROM house_room1 INNER JOIN objects ON house_room1.object_id=objects.object_id WHERE house_room1.ref_id = ?');
$stmt->bind_param('i', $i
);
if ($stmt->execute()) {
$stmt->bind_result($z, $rotation, $src, $name);
while($stmt->fetch()) {
$results = 1;
$itemArray['number'] = $item_number;
$itemArray['name'] = $name;
$itemArray['ref_id'] = $z;
$itemArray['rotation'] = $rotation;
$itemArray['src'] = $src;
array_push($finalArray, $itemArray);
}
}
else {
echo 'Something went terribly wrong' . $mysqli->error;
}
$stmt->close();
$item_number++;
}
if($results == 1){
aasort($finalArray,"ref_id");
foreach($finalArray as $arr){
echo '<li id="item-' . $arr['number'] . '" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' . $arr['name'] . '
<img class="rotate" id="img_'.$arr['number'].'" src="images/house/other/settings.jpg" onclick="rotateObject(this)" alt="'. $src.'">';
}
}
//create a function for sorting
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
}
?>
It then makes an AJAX call to this file:
function rotateObject(e)
{
//e is handler which contains info about the item clicked. From that we can obtain the image id.
//since the id are of the form img_123(some number), we need to extract only the number.
var img_id = e.id.split("_")[1];
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");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var getEle = document.getElementsByClassName('item' + img_id)[0];
var imagePath ="images/house/objects/stone_chair_1.png"; //This has to be
getEle.src = imagePath + xmlhttp.responseText;
}
}
xmlhttp.open("POST","database/update_settings_rotate.php",true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("item_id="+encodeURIComponent(img_id));
}
This code is then supposed to have the imagePath equal to src. and then the rotation after it, but I don't know how I can get the src for that specific image from the database query made in the PHP file.
Any suggestions or advice on how I can pass that value? Thanks in advance.
One way to pass variables from php to javascript is:
<script>
var myJavascriptVariable = <?php echo $myPhpVariable; ?>
</script>
Hope this help you
Related
so I get the feed after choosing an option but its not "refreshing as new news come".
I have the same problem with openweather.
Is the "GET" my problem or browser or something else? I guess everything is cached but it should not.
Should it be POST and not GET how sould I change that with the current code?
thanks!
<script>
nocache = "&nocache" + Math.random()* 1000000
url = "$q"
out = "";
function showRSS(str) {
if (str.length==0) {
document.getElementById("rssOutput").innerHTML="";
return;
}
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("rssOutput").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getrss.php?q="+str+nocache,true);
xmlhttp.send();
}
</script>
<?php
//get the q parameter from URL
$q = $_GET["q"];
//find out which feed was selected
if($q=="Baden-Württemberg") {
$xml=("https://verkehrsmeldungen.polizei-bw.de/TicRss.ashx?region=BW");
} elseif($q=="Bayern") {
$xml=("http://www.br.de/verkehr-static/verkehrsmeldungen-rss.xml");
}
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);
//get elements from "<channel>"
$channel=$xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title = $channel->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
//output elements from "<channel>"
echo("<p ><a href='" . $channel_link
. "'>" . $channel_title . "</a>");
echo("<br>");
echo($channel_desc . "</p>");
//get and output "<item>" elements
$x=$xmlDoc->getElementsByTagName('item');
for ($i=0; $i<=5; $i++) {
$item_title=$x->item($i)->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$item_link=$x->item($i)->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$item_desc=$x->item($i)->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
echo ("<p ><a href='" . $item_link
. "'>" . $item_title . "</a>");
echo ("<br>");
echo ($item_desc . "</p>");
}
?>
From what you are saying or trying to accomplish, is to either use
polling
event or socket connection (socket.io)
Now with Polling, you set a particular interval to always go and check for new updates. This path is not too efficient as you might go to the server to retrieve new information and there might be none returned as at the time you sent the request.
Sample
var interval = 3000// milliseconds
function fetchFeeds(){
setTimeout(function(){
// goto the server here and manage returned record
}, interval);
}
For Events: you can check up on server side events here but for only HTML5, but nice stuff.
Will advise to go for socket instead, check socket.io
I'm trying to load an xml file using ajax. I tried to modify the example of W3Schools
<html>
<head>
<script>
function showBus(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
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("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getbus.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>Select your bus route:
<select name="NUMBER" onchange="showBus(this.value)">
<option value="">Select a Bus:</option>
<option value="102">102</option>
</select>
<div id="txtHint"><b>Bus info will be listed here...</b>
</div>
</form>
<?php
$q = $_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc->load("routes.xml");
$x = $xmlDoc->getElementsByTagName('NUMBER');
for ($i = 0; $i <= $x->length - 1; $i++) {
//Process only element nodes
if ($x->item($i)->nodeType == 1) {
if ($x->item($i)->childNodes->item(0)->nodeValue == $q) {
$y = ($x->item($i)->parentNode);
}
}
}
$BUS = ($y->childNodes);
for ($i = 0; $i < $BUS->length; $i++) {
//Process only element nodes
if ($BUS->item($i)->nodeType == 1) {
echo("<b>" . $BUS->item($i)->nodeName . ":</b> ");
echo($BUS->item($i)->childNodes->item(0)->nodeValue);
echo("<br>");
}
}
?>
XML File:
<TT>
<BUS>
<NUMBER>102</NUMBER>
<DEPARTING_STOP>102</DEPARTING_STOP>
<DESTINATION>102</DESTINATION>
<TIME>102</TIME>
</BUS>
</TT>
This is what I get when I select the bus number from drop down menu:
Select your bus route:
load("routes.xml"); $x=$xmlDoc->getElementsByTagName('NUMBER'); for ($i=0; $i<=$x->length-1; $i++) { //Process only element nodes if ($x->item($i)->nodeType==1) { if ($x->item($i)->childNodes->item(0)->nodeValue == $q) { $y=($x->item($i)->parentNode); } } } $BUS=($y->childNodes); for ($i=0;$i<$BUS->length;$i++) { //Process only element nodes if ($BUS->item($i)->nodeType==1) { echo("" . $BUS->item($i)->nodeName . ": "); echo($BUS->item($i)->childNodes->item(0)->nodeValue); echo("
"); } } ?>
Open <yourserver>getbus.php?q=102 in your browser. Do you get something like this:
NUMBER: 102
DEPARTING_STOP: 102
DESTINATION: 102
TIME: 102
If you get something like:
load("routes.xml"); $x=$xmlDoc->getElementsByTagName('NUM...
I'd personally think you are not running an http server but are excuting everything locally.
Your getbus.php file is a php sourceode file that needs to be interpreted by a php processor. This is all being done by a webserver (if correctly configured). To get started you can use xampp ( https://www.apachefriends.org/ ) which has all the necessary modules for your sample. It is a preconfigured server to run php.
Then put all your files in the according htdocs folder in your xampp installation and the sample should work.
EDIT:
As it seems the getbus.php most of the time responses with an empty response. The problem apears to be the load(file) method by domdocument. loadXML seems to work better. So this always works for me:
<?php
$q = $_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc->loadXML("<TT>
<BUS>
<NUMBER>102</NUMBER>
<DEPARTING_STOP>102</DEPARTING_STOP>
<DESTINATION>102</DESTINATION>
<TIME>102</TIME>
</BUS>
<BUS>
<NUMBER>103</NUMBER>
<DEPARTING_STOP>104</DEPARTING_STOP>
<DESTINATION>105</DESTINATION>
<TIME>107</TIME>
</BUS>
</TT>");
$x = $xmlDoc->getElementsByTagName('NUMBER');
for ($i = 0; $i <= $x->length - 1; $i++) {
//Process only element nodes
if ($x->item($i)->nodeType == 1) {
if ($x->item($i)->childNodes->item(0)->nodeValue == $q) {
$y = ($x->item($i)->parentNode);
}
}
}
$BUS = ($y->childNodes);
for ($i = 0; $i < $BUS->length; $i++) {
//Process only element nodes
if ($BUS->item($i)->nodeType == 1) {
echo("<b>" . $BUS->item($i)->nodeName . ":</b> ");
echo($BUS->item($i)->childNodes->item(0)->nodeValue);
echo("<br>");
}
}
note that the entire XML file is now inside the PHP file as a string. To make it working the way you want you could try to load the file contents into a string using file() or file_get_contents() in the php file.
I need to write a word in database, and i cant couse i get an error that: ReferenceError: Patikrinta is not defined Here is my ajax script which sends data to php file. Bellow there is php script if you need it. Cant find solution in stackowerflow.
$s .= "\n\t<td>";
$canEdit = getPermission('tasks', 'edit', $a['task_id']);
$canViewLog = getPermission('task_log', 'view', $a['task_id']);
$currentTasken=$a['task_id'];
$currentUser=$AppUI->user_id;
$currentPercent="5";
$currentDescription="Patikrinta";
if ($canEdit) {
$s .= ("\n\t\t".'<a href="#">'
. "\n\t\t\t".'<img src="./images/icons/tick.png" alt="' . $AppUI->_('Check')
. '" border="0" width="12" height="12" onclick="javascript:insertData('. $currentTasken .', '.$currentUser.', '.$currentPercent.', '.$currentDescription.')" />' . "\n\t\t</a>");
}
$s .= "\n\t</td>";
?>
<script type="text/javascript">
// Note that you should use `json_encode` to make sure the data is escaped properly.
var currentTasken = <?php echo json_encode($currentTasken=$a['task_id']); ?>;
var currentUser = <?php echo json_encode($currentUser=$AppUI->user_id); ?>;
function insertData(currentTasken, currentUser, currentPercent, currentDescription)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","modules/tasks/datafile.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// Here, use the JS variables but, likewise, make sure they are escaped properly with `encodeURIComponent`
xmlhttp.send("currentUser=" + encodeURIComponent(currentUser) + "¤tTasken=" + encodeURIComponent(currentTasken) + "¤tPercent=" + encodeURIComponent(currentPercent)+ "¤tDescription=" + encodeURIComponent(currentDescription));
}
</script>
Here is my php script:
<?php
$currentUser = isset($_POST['currentUser']) ? $_POST['currentUser'] : '';
$currentTasken = isset($_POST['currentTasken']) ? $_POST['currentTasken'] : '';
$currentPercent = isset($_POST['currentPercent']) ? $_POST['currentPercent'] : '';
$currentDescription = isset($_POST['currentDescription']) ? $_POST['currentDescription'] : '';
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
if(!$con)
die('Could not connectzzz: ' . mysql_error());
mysql_select_db("foxi" , $con) or die ("could not load the database" . mysql_error());
$check = mysql_query("SELECT * FROM dotp_task_log");
$numrows = mysql_num_rows($check);
if($numrows >= 1)
{
//$pass = md5($pass);
$ins = mysql_query("INSERT INTO dotp_task_log (task_log_creator, task_log_Task, task_log_description) VALUES ('$currentUser' , '$currentTasken', '$currentDescription')" ) ;
if($ins)
{
$check = mysql_query("SELECT * FROM dotp_tasks");
$numrows = mysql_num_rows($check);
if($numrows > 1)
{
//$pass = md5($pass);
$inss = mysql_query("UPDATE dotp_tasks SET task_percent_complete = '$currentPercent' WHERE task_id='$currentTasken'") ;
if($inss)
{
die("Succesfully added Percent!");
}
else
{
die("GERROR");
}
}
else
{
die("Log already exists!");
}
}
else
{
die("ERROR");
}
}
else
{
die("Log already exists!");
}
?>
Have you tried adding quotes around the function arguments which are strings? JS is looking for a reference to 'Patikrinta' because you are not adding quotes around the string. It should be a bit more like this:
javascript:insertData('. $currentTasken .', '.$currentUser.', '.$currentPercent.', \''.$currentDescription.'\')" />' . "\n\t\t</a>");
The other arguments work because they are being passed as numbers and Javascript interprets them as such. The difference here is the value of $currentDescription is Patikrinta which is not a number and so JS looks for a variable or object called that.
As a side note - it's worth switching to use MySQLi if you can. MySQL_* functions are deprecated.
i am trying to change the select query on click or on change of the button,
the table name field names in the table general are equal to the fragment after page = (About, ContactInformation)
i'm not getting any error nor getting any result
index page code
<script>
function selectQuery(str) {
if (str == "") {
document.getElementById("editor").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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("editor").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","queries.php?page="+str,true);
xmlhttp.send();
}
}
</script>
<ul>
<li><i class="fa fa-file-text"></i> About us</li>
<li><i class="fa fa-list-alt"></i> Contact us</li>
</ul>
queries.php page
<?php
$page = intval($_GET['page']);
$result = mysql_query("SELECT general.'".$page."' ".
"FROM general") or trigger_error(mysql_error());
echo $result;
?>
i tried to echo $page in the queries.php file directly but also it is not showing, seems its not even getting here,
so can anyone help pls
You aren't fetching those results. You need to use mysql_fetch_* functions to get those rows. Now the next part is whether you would like to get a JSON response or just output an HTML markup that can be used directly.
Here's what the fetching would look like:
<?php
$page = $_GET['page'];
$data = array();
$result = mysql_query("SELECT general.".$page." FROM general") or trigger_error(mysql_error());
while($row = mysql_fetch_assoc($result)) {
// fetch the results
$data[] = $row;
}
echo json_encode($data);
?>
Obligatory Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Here's a version with mysqli:
<?php
$default_columns = array('About', 'ContactInformation', 'Others', 'Home');
if(isset($_GET['page']) && in_array($_GET['page'], $default_columns)) {
$return_value = array();
$page = $_GET['page'];
$db = new mysqli('localhost', 'username', 'password', 'database');
$sql = "SELECT $page FROM general";
$query = $db->query($sql);
while($row = $query_fetch_assoc()) {
$return_value[] = $row[$page];
}
echo implode(' ', $return_value);
}
?>
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);
}