I have the following code wherein I'm trying to get values of the xml element 'point' from an RSS feed using PHP. When I display the value of point using 'echo', it gives me the correct data. However, when I pass the same parameter to a javascript function, it calls the function very randomly. The alert in the javascript function gives me the sum of the points of either 2 or 3 point values from each iteration. How do I resolve this problem?
<!DOCTYPE html>
<html>
<head>
<title>Natural Disasters</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js? sensor=false&libraries=places"></script>
<script type="text/javascript">
var i=0;
function getPoint(point) {
alert("Value of i : "+i+" Value of point : "+point);
++i;
}
</script>
<script>
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 (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
document.getElementById("rssOutput").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "getrss.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
$xml2 = ("http://www.volcano.si.edu/news/WeeklyVolcanoRSS.xml?");
$xmlDoc2 = new DOMDocument();
$xmlDoc2->load($xml2);
$x2 = $xmlDoc2->getElementsByTagName('item');
$i2 = 0;
foreach ($x2 as $y) {
$geo_rss = $y->getElementsByTagNameNS("http://www.georss.org/georss", 'point');
$title = $y->getElementsByTagName('title')->item(0)->nodeValue;
$point = $geo_rss->item(0)->nodeValue;
echo ("<h3>" . $title . "</h3>" );
echo ($point);
echo '<script type="text/javascript">'
, 'getPoint(' . $point . ');'
, '</script>'
;
++$i2;
}
?>
</body>
</html>
P.S. :I have followed the same procedure for another set of parameters, and it works perfectly fine. I do not know why this one is not working.
Change your php code to write script as below :
echo '<script type="text/javascript"> getPoint("' . $point . '");</script>';
You just need to wrap $point into double quotes.
Related
And my other question is that, is the code correct, will my AJAX request get to my controller ?
Here is the relevant parts on the code:
My view (I have this on a POST form cause I want to send the data on another table) :
<script> var base_url = <?php echo base_url(); ?> </script>
<label for="exampleInputEmail1">Apartament</label>
<select onchange="showUser(this.value)" name ="txtApartament1" class="form-control">
<?php foreach($getEntry as $value) { ?>
<option><?php echo $value->apartament ?></option>
<?php }?>
</select>
In the same view this is my AJAX part:
function showUser(str) {
if (str == "") {
document.getElementById("txtApartament1").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("txtApartament1").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", base_url + "usercontroller/ajaxp?q="+str,true);
xmlhttp.send();
}
}
And this is my controller - usercontroller.php function:
public function ajaxp(){
echo "received";
}
I will get this error:
(index):257 Uncaught ReferenceError: base_url is not defined
at showUser (localhost/adminigniter1/:257:29)
at HTMLSelectElement.onchange (localhost/adminigniter1/:205:89)
My project filename is codeigniter1!
I did not set any config file on codeigniter. should I ? Anything else?
Try like this..
1.Load url helper using $this->load->helper('url') or in applicaiton/config/autoload.php.
2.Set base_url config item in application/config/config.php
$config['base_url'] = 'your_url';
3.In your script.Remove var.Because it creates variable as local.So you can not use inside function.
base_url = <?php echo base_url();
OR put it var base_url = <?php echo base_url(); ?> inside showUser() function.
UPDATE
var url = base_url + "usercontroller/ajaxp?q="+str; //OR var url = <?php base_url();?>+"usercontroller/ajaxp?q="+str;
console.log(url);
xmlhttp.open("GET",url,true);
xmlhttp.send();
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>
I'm trying to write a simple AJAX code to get it to search through a simple array, and output the results to the screen, and it works before I tried to pass the variables through the parameter, but now it isn't passing the variables through the parameters for some reason. Please take a look:
functions.js:
var xmlHttp = createXmlHttpRequestObject();
//****************************************************************AJAX
function createXmlHttpRequestObject() {
var xmlHttp;
if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlHttp = false;
}
} else {
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
xmlHttp = false;
}
}
if (!xmlHttp)
alert("Not xmlHttp!")else
return xmlHttp;
}
//****************************************************************AJAX
function process(IDName, passTo, output) {
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
get = encodeURIComponent(document.getElementById(IDName).value);
xmlHttp.open("GET", passTo + get, true);
xmlHttp.onreadystatechange = handleServerResponse(output);
xmlHttp.send(null);
} else {
setTimeout('process()', 1000);
}
}
//****************************************************************AJAX
function handleServerResponse(output) {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById(output).innerHTML = message;
setTimeout('process()', 1000);
} else {
alert('xmlHttp.status does not equal 200!');
}
}
}
foodstore.php:
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna','bacon','beef','ham');
if(in_array($food,$foodArray))
echo 'We do have '.$food.'!';
elseif ($food=='')
echo 'Enter a food';
else
echo 'Sorry punk we dont sell no '.$food.'!';
echo '</response>';
?>
test5.html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="functions.js"></script>
</head>
<body onload="process('userInput','foodstore.php?food=','underInput')">
<h3>The Chuff Bucker</h3>
Enter the food you would like to order:
<input type="text" id="userInput" />
<div id="underInput" />
</body>
</html>
Try adding console.log(variable) on different stages to check the current state of variables, probably you are having problems with the get variable with the encodeURIComponent or maybe it isn't entering to that if on process function.
Good day this is my code of index
<!DOCTYPE html>
<html>
<body>
<script>
function show_month(var) {
if (windows.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","month.php?q="+var,true);
xmlhttp.send();
}
</script>
<?php
$from = (date('Y'));
$to = 2050;
echo '<form>';
echo '<select name="year" onchange="show_month(this.value)">';
for($y = $from; $y <= $to; $y++) {
echo "<option value=$y>{$y}</option>";
}
echo '</select>';
echo '<form>';
?>
<div id="txtHint"><b>here will be info</b></div>
</body>
</html>
and here is code of my month.php
<!DOCTYPE html>
<html>
<body>
<?php
$q = $_GET['q'];
echo $q;
if ($q == 2015) {
echo "actual year";
}
else {
echo "unactual year";
}
?>
</body>
</html>
As you see I created select tag with php so I can make multiple options of year just by using loop and I want that if I select year 2015 javascript should print message actual year but it isn't working I think that problem is somewhere in select or sending value can someone more intelligent than me look into this code and tell me whats is wrong?
Your js code does not have the response code. Also you have a few other errors in your code which will cause issues for you.
show_month(var) you cannot have var as this specific to JS, change it to something else.
windows.XMLHttpRequest This is window not windows.
In order to show what you need use;
alert(xmlhttp.responseText);
in your response if.
<script>
function show_month(t) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","month.php?q="+t,true);
xmlhttp.send();
}
</script>
and finally you don't need <!DOCTYPE html> in your month.php if you are just returning text (most likely you will never need a reason for it).
Your js code is missing code to handle server response
<script>
function show_month(var) {
if (windows.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","month.php?q="+var,true);
xmlhttp.send();
}
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