I'm having problems getting my request filled with the data from a json file... Data is pulled from Mysql DB and formatted in a JSON file in the scripts dir...
Could there be a problem with the GET request ? I just want the json file returned so i could work with the key/val pairs inside of it ...
Any suggestions would be appreciated.
function fetchData($str){
$queryAll = "select name,value,date from chart where id <= (select max(id) from chart) limit 50";
$dateValue = mysql_query($queryAll);
$pushed = array();
while($row = mysql_fetch_array($dateValue,MYSQL_ASSOC)){
$key = array_shift($row);
$value = array_shift($row);
$date = array_shift($row);
if(strcmp("$str",$key) == 0){
$myArray = array($key, $value, $date);
array_push($pushed,$myArray);
}
}
$jsonFile = json_encode($pushed);
$jsonOpenFile = fopen("../scripts/$str.json","w+") or exit("Unable to open file!");
$jsonWriteOut = fwrite($jsonOpenFile,$jsonFile);
}
fetchData("blabla");
?>
<script>
function Graph(JsonVal){
var xmlhttp = new ajaxRequest();
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 jsondata=eval("("+xmlhttp.responseText+")");
var returned = jsondata.items
var output;
for(var i=0; i<returned.length;i++){
output += "<p>";
output += returned[i];
output += "</p>";
}
document.getElementById("MyGraph").innerHTML=output
}
}
xmlhttp.open("GET","../scripts/"+JsonVal+".json",true);
xmlhttp.send(null);
}
</script>
<div id="MyGraph" onload="Graph();"></div>
Related
I am trying to create a ajax function to just reload a <div> and not the entire page.
What is working:
-during writing in the input field the div is reloaded after every character correctly.
What is not working:
-when the input field is complete empty again, it is not showing the whole entries I have in the database.
this is what I have in the php file where the div is:
function showGames(str) {
if (str == "") {
document.getElementById("searchgame").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("show").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","searchgame.php?game="+str,true);
xmlhttp.send();
} }
this is what I have in the search.php
<?php
include 'test/database.php';
$pdo = Database::connect();
if($_GET['game'] == "") {
$sql="SELECT * FROM games WHERE active=1";
echo "<script type='text/javascript'>alert('Should be empty')</script>";
} else {
$q = $_GET['game'];
$sql="SELECT * FROM games WHERE gamenamelong LIKE '%".$q."%'";
}
$stmt = $pdo->prepare($sql);
$stmt->execute();
$gameResults = $stmt->fetchAll(PDO::FETCH_ASSOC);
$rowCount1 = count($gameResults);
Is anybody able to help me?
Thank you!
since we don't know how your form looks like, and what calls the function showGames how, I can only give a vague answer. But your main problem/misstake should be solved with that:
In your function showGames you never hit the ajax if the search string is empty, so you can't get back all results.
So I suggest to change that function like so:
function showGames(str) {
if (str == "") {
document.getElementById("searchgame").innerHTML = "";
//remove that: return;
}
// remove the 'else { '
// now you allways hit the ajax
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("show").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","searchgame.php?game="+str,true);
xmlhttp.send();
// remove closing bracket of if-else: '}'
}
I have a radio button that has an array as value like this,
$sql = "SELECT * FROM os";
$result = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($result)) {
$row['client'];
//Radio button code
echo "<li><div class = 'list'><a href = 'searchos.php'><div class = 'toggle-btn-grp cssonly'>
<div><form><input type = 'radio' name = 'os' value = " . $row['client'] . " id = 'myRadio1 onchange='showUser(this.value)' >
<label class='toggle-btn'>" . $row['client'] . "</label></form></div></div><div></a></li>";
}
The radio button is working, but for some reason it keeps ignoring the space between the strings in the array. And it only gives me the value of the first string.
When I hard code the a string with space in the value i.e "Production Cost", it gives me the correct output, so the issue must be with the array then, any ideas on how I Could solve this?
Here is the ajax function for getting the value
function showUser(str)
{
var xmlhttp;
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", "getUser.php?q=" + str, true);
xmlhttp.send();
}
I have this sortable list which makes it possible for the user to sort things by dragging them in the particular place they want it to be. The place the item is dragged to, is then put into a database so that it remembers the exact location the next time the user logs in. For that I have this:
$item_number = 0;
$rowsize = 12;
$itemArray = array();
$finalArray = array();
$results = 0;
for ($i = 0; $i < $rowsize; $i++) {
$stmt = $mysqli->stmt_init();
$stmt->prepare('SELECT z, 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, $name);
while ($stmt->fetch()) {
$results = 1;
$itemArray['number'] = $item_number;
$itemArray['name'] = $name;
$itemArray['ref_id'] = $z;
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" src="images/house/other/settings.jpg" onclick="rotateObject()"></li>';
}
}
// 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;
}
As you can see, there is also a button that you can press on, which has to send some data to the database by the use of ajax. The function is named rotateObject() and that ajax call is here:
function rotateObject()
{
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)
{
document.getElementById("item").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","database/update_settings_rotate.php",true);
xmlhttp.send();
}
And after that call has been made, the database has to insert the arr['item_number'] value from the code inside a database:
require ('../includes/db_connect.php');
/* Register a prepared statement */
if ($stmt = $mysqli->prepare('UPDATE house_room1 SET rotation = ? WHERE ref_id = ?')) {
/* Bind parametres */
$stmt->bind_param('ii', $i, $item_number);
$i = 5;
$item_number = 3;
/* Execute the query */
$stmt->execute();
/* Close statement */
$stmt->close();
}
else {
/* Something went wrong */
echo 'Something went terribly wrong' . $mysqli->error;
}
Right now, the item_numer is set equal to 3, for some testing. It works as it should, but this variable should be equal to the element the user presses on, on the sorted list. Which is arr['number']. The problem is that this array doesn't seem to hold any values any longer. I don't know how I can parse that value so the correct element gets changed in the database. Uhm hope I made everything clear, feel free to ask for more information, thanks in advance.
From what I understand, you need to send the item_number of the element clicked.
For that, we need to send the item_number as a parameter in the AJAX call.
The below modification to your <img> element allows you to get the item_number in the rotateObject() function.
<img class="rotate" id="img_'.$arr['number'].'" src="images/house/other/settings.jpg" onclick="rotateObject(this)">
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Modified here ^^^^ and here
Now the rotateObject() function can access the item_number and can send it to the server.
Here I have sent the item_number as a value to the key "item_id"-
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)
{
document.getElementById("item").innerHTML=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));
}
So in your update_settings_rotate.php, item_number is obtained -
if(isset($_POST['item_id'])){
$item_number = $_POST['item_id'];
//Rest of your code...
}
Hopefully, this helped.
by using javascript ajax i have passed the values to php page...
display the values after retrieving from database and print in ajax page...it displaying in alert page...but i need to display in ajax page....
ajax coding
<script>
function optionsAlert()
{
alert("call");
var xmlhttp;
var qw=document.getElementById('c').value;
var qw1=document.getElementById('c1').value;
var qw2=document.getElementById('unit33').value;
var qw3=document.getElementById('dept').value;
var qw4=document.getElementById('class').value;
alert(qw);
alert(qw1);
alert(qw2);
alert(qw3);
alert(qw4);
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);
if(xmlhttp.responseText==1){
alert("name already Exists" );
return false;
}
else if(xmlhttp.responseText==0)
{
alert("name available");
document.login.submit();
}
}
}
var queryString = "?q=" + qw + "&q1=" + qw1 + "&q2=" + qw2 + "&q3=" + qw3 + "&q4=" + qw4;
xmlhttp.open("get",'ques.php' + queryString,true);
xmlhttp.send();
}
php page
<?php
include('connection.php');
if(($_GET['q']!='') && ($_GET['q1']!='') && ($_GET['q2']!='') && ($_GET['q3']!='') && ($_GET['q4']!=''))
{
$a= mysql_query("select * from unit1 where unit='".$_GET['q']."' and stopic='".$_GET['q1']."' and qtype='".$_GET['q2']."' and dept='".$_GET['q3']."' and class='".$_GET['q4']."'");
//$a= mysql_query("select * from unit1 where unit='unit1' and stopic='Subtopic1' and qtype='normal questions'");
if(mysql_num_rows($a)>0)
{
while($row=mysql_fetch_array($a))
{
$a1=$row['qno'];
$a2=$row['ques'];
$a3=$row['ch1'];
$a4=$row['ch2'];
$a5=$row['ch3'];
$a6=$row['ch4'];
$a7=$row['ans'];
echo $a1."<br>";echo $a2."<br>";echo $a3."<br>";echo $a4."<br>";echo $a5."<br>";echo $a6."<br>";echo $a7."<br>";
echo 1;
}
}
else
{
echo 0;
}
}
?>
Below the ajax coding create div element with id
in your ajax method
if(xmlhttp.responseText==1){
document.getElementById("id").innerHTML = "name already Exists";
return false;
}
else if(xmlhttp.responseText==0)
{
document.getElementById("id").innerHTML="name available";
document.login.submit();
}
"id" your own div id
I have the following code which works great:-
$('.ajax a').click(function() {
getpageajax(this.href);
return false;
});
function getpageajax(getpage) {
if(getpage == "") {
//SET ERROR?
document.getElementById("main").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("main").innerHTML = xmlhttp.responseText;
}
}
var urlarray = getpage.split('/');
location.hash = urlarray[urlarray.length-1];
xmlhttp.open("GET", "includes/AJAXgetpage.php?getpage=" + getpage, true);
xmlhttp.send();
};
Only problem is that I have no idea how to get then read the anchor links I create (e.g. #contact-us) to create bookmarkable pages.
I tried to do a solution based around the following but it seems less than ideal
<script>
var query = location.href.split('#');
document.cookies = 'anchor=' + query[1];
<?php if (!$_COOKIE['anchor']) : ?>
window.location.reload();
<?php endif; ?>
<?php
echo $_COOKIE['anchor'];
?>
To get the hash, other than your initial example, you can use window.location.hash
// example url - http://www.mysite.com/blog/post#comments
var hash = window.location.hash; // = "#comments"
You can use replace to get rid of the leading # if required.