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();
}
Related
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").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("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
}
</script>
Code is working 100% but my problem is in script in place of getuser.php i want to use action for example "action=records" . what should i change
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'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>
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.
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.