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.
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'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>
OK, code returns results normally when there is no ( amp / & / & ) inside query:
example1 => BRAHAM BALDWIN AGRICULTURAL COLLEGE
is converted and query looks like => BRAHAM+BALDWIN+AGRICULTURAL+COLLEGE
Example 1 => works normally and returns => This school is in Alabama
example2 query => BRYANT & STRATTON BUSINESS INSTITUTE - BUFFALO
is converted and query looks like => BRYANT+%26+STRATTON+BUSINESS+INSTITUTE+-+BUFFALO
Example 2 => doesn't return anything, I'm quite sure that's because of %26 (amp / &)...
Code in funcs.php:
require 'dbconnect.php';
$q = $_GET["q"];
$sql = "SELECT * FROM bl_zrify WHERE Name = '".$q."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
if ($row['State'] == '') {
$SchoolState = 'Unknown';
}
else if ($row['State'] == 'AL') {
$SchoolState = 'Alabama';
}
else if ($row['State'] == 'AK') {
$SchoolState = 'Alaska';
}
else if ($row['State'] == 'AZ') {
$SchoolState = 'Arizona';
}
else if ($row['State'] == 'AR') {
$SchoolState = 'Arkansas';
}
print 'This school is in';
print $SchoolState;
}
PHP code get executed when we type text into =>
<input name="SchoolName" type="text" maxlength="50" size="30" id="SchoolName" value="" onfocus="showVal(this.value);" />
And javascript which we use to pass the string to PHP funcs.php:
function showVal(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","funcs.php?q="+str.replace("&", "%26").replace(/ /g, "+"),true);
xmlhttp.send();
}
Here is your code with some slight improvements (in comments).
PHP:
require 'dbconnect.php';
// ESCAPE USER INPUT BEFORE PASSING TO SQL!!!
$sql = "SELECT * FROM bl_zrify WHERE Name = '".mysql_real_escape_string($_GET["q"])."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
// Switch is better for this type of operation
switch ($row['State']) {
case 'AL':
$SchoolState = 'Alabama';
break;
case 'AK':
$SchoolState = 'Alaska';
break;
case 'AR':
$SchoolState = 'Arkansas';
break;
case 'AZ':
$SchoolState = 'Arizona';
break;
default:
$SchoolState = 'Unknown';
}
print "This school is in $SchoolState<br />\n";
}
Javascript
function showVal(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) {
if (xmlhttp.status == 200) { // break this into 2 statements so you can handle HTTP errors
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
} else {
document.getElementById("txtHint").innerHTML = "AJAX Error (HTTP "+xmlhttp.status+")";
}
}
}; // functions declared in this way should be followed by a semi colon, since the function declaration is actually a statement.
// encodeURIComponent() does all the escaping work for you - it is roughly analogous to PHP's urlencode()
xmlhttp.open("GET","funcs.php?q="+encodeURIComponent(str),true);
xmlhttp.send();
}
However, I suspect the actual problem here is that you don't actually have an exact match for the entered string in the database. Consider using a LIKE clause in your SQL instead of an exact comparison. Also ensure the collation of the Name field is case-insensitive.
I have a problem with inner html funcion when updating tag options. In the first select tag I am chosing a country and ajax code must update cities in the other select tag. My code works in all major browsers except IE. Here is the js code for calling php script:
>function show_zones(str)
>{
>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('region_to').innerHTML="";
> jQuery.noConflict();
> (function($) {
> $('#region_to').append(xmlhttp.responseText);
> })(jQuery);
> alert(xmlhttp.responseText);
> }
> }
>xmlhttp.open("GET","ajax/zones.php?country="+str,true);
>xmlhttp.send();
>}
In all browsers alerted code returns appropriate option tags but in IE it returns "Undifined". I am using Jquery to append xmlhttp.responseText because IE does not support innerhtml for select tags. noConflict function is used to avoid conflict between mootolls and jquery libraries. I can`t just place select tag in a div and print it instead of printing just options because I am using custom select which is being created by js code when the window.onload event occurs.
here is the php code:
>require_once("../../connect.php");
>$country_query="SELECT* FROM `tour_countries` WHERE >country_name='".$_GET['country']."'";
>$country_result=mysql_query($country_query);
>$country_row=mysql_fetch_array($country_result);
>$zone_query="SELECT* FROM `tour_zones` WHERE country_ID='".$country_row[0]."'";
>$zone_result=mysql_query($zone_query);
>while($zone_row=mysql_fetch_array($zone_result))
>{
> echo '<option value="'.$zone_row[1].'">'.$zone_row[1].'</option>';
>}
Thanks for replys and sorry for my poor englesh.
I had the same issue with IE and .innerHtml() with ajax calls. I solved it by making the AJAX a POST request and using jQuery .html() instead of .innerHTML(), for some reason IE is pretty glitchy with innerHtml(). Here's the working function I used:
function getCitiesFromState(state, select, spinnerNum)
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var ran = Math.round((new Date()).getTime() / 1000),
terms = "state="+state+'&r='+ran;
xmlhttp.open("POST","ajax5.php",true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
/***********************************************************
* These two lines cause Chrome to throw non-fatal errors.
* Removing them didn't change the functionality of the
* request, but this may end up needing a conditional.
***********************************************************/
//xmlhttp.setRequestHeader('Content-length', terms.length);
//xmlhttp.setRequestHeader('Connection', 'close');
xmlhttp.onreadystatechange = function()
{
$('#spinner'+spinnerNum).fadeIn(300);
if (xmlhttp.readyState == 4
&& xmlhttp.status == 200)
{
$('#spinner'+spinnerNum).fadeOut(100);
$('#'+select).html(xmlhttp.responseText);
}
}
xmlhttp.send(terms);
}
And the ajax5.php file:
<?php
include 'db.class2.php';
$DB = new DB_MySql2;
$DB->connect();
$state = mysql_real_escape_string($_POST['state']);
$q = $DB->query("SELECT DISTINCT `city`, `zip_code`
FROM `usa_master`
WHERE `state` = '".$state."'
GROUP BY `city`
ORDER BY `population` DESC LIMIT 0, 150");
while($r = $DB->fetch_assoc($q)) {
$city[] = $r['city'];
$zips[] = $r['zip_code'];
}
array_multisort($city, $zips);
echo '<option value="" selected="selected">Select City</option>';
$size = sizeof($city);
for ($x = 0; $x < $size; $x++)
{
if (strlen($zips[$x]) == 4)
{
$zips[$x] = '0' . $zips[$x];
}
echo '<option class="city_list" value="'.$zips[$x].'">'.$city[$x].'</option>';
}
?>
Hope this helps.