I keep getting an unexpected character error in the console for the line
var a = JSON.parse(xmlhttp.responseText);
and I'm not sure why. Could this be why my textboxes aren't populating with the parsed data?
Main page code:
function loadDoc()
{
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var doc = window.document.createElement("doc");
var a = JSON.parse(xmlhttp.responseText);
document.getElementById("textbox").innerHTML=a.first;
document.getElementById("textbox2").innerHTML=a.second;
}
}
xmlhttp.open("GET","loadTextBox.php?id=4",true);
xmlhttp.send();
}
loadTextBox.php code:
<?php
---Placeholder for correct DB login info---
$result = $mysql->query(---Placeholder for correct SQL query---);
while ($row = $result->fetch_object())
{
$queryResult[] = $row->present_tense;
}
$textboxValue = $queryResult[0];
$textboxValue2 = $queryResult[2];
echo json_encode(array('first'=>$textboxValue,'second'=>$textboxValue2));
?>
Your loadTextBox.php file should not contain any HTML because the JSON.parse method expects only JSON:
<?php
header("Content-type: application/json");
$db_username = placeholder;
$db_password = placeholder;
$db_host = placeholder;
$result = $mysql->query(---Placeholder for correct SQL query---);
while ($row = $result->fetch_object())
{
$queryResult[] = $row->present_tense;
}
$textboxValue = $queryResult[0];
$textboxValue2 = $queryResult[2];
echo json_encode(array('first'=>$textboxValue,'second'=>$textboxValue2));
?>
If your DB login info is in a separate file, then there should be no HTML or BODY tags only the PHP tags.
Related
I have a problem with my code.
case like this:
I have a dropdown, if selected "personal" it appeared the new dropdown that contains the data that is retrieved from a database query, if selected "public", then the dropdown disappear.
HTML code like this:
<select name="use" class="dropdown" id="sender" onChange='changeSend()'>
<option value=1>Public</option>
<option value=0>Personal</option>
</select>
<div id='send2'></div>
Query like this:
<?php
$query = mysql_query("select * from data where id_user = '$id_user' order by date asc");
$i = 0;
$id = array();
$name = array();
while($data = mysql_fetch_array($query)){
//id from result database query
$id[$i] = $data['id'];
//name from result database query
$name[$i] = $data['name'];
$i++;
}
?>
JavaScript code like this:
function changeSend() {
var selectBox = document.getElementById("sender");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
if (selectedValue==0) {
$('#send2').html("<select class='dropdown'><option value='-id from result database-'>-name from result database query-</option></select>");
} else {
$('#send2').html('');
}
}
I dont know how to send value/result ($id[0],$name[0],$id[1],$name[1], etc..) to javascript code(value and name in select options).
In javascript you have to make an ajax call to your php file:
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("send2").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","yourFile.php",true);
xmlhttp.send();
And in your php file you have to echo your data in JSON format:
echo json_encode(array('id'=>$id,'name'=>$name));
UPDATE
in your case use the following code:
(not tested)
php code:
<?php
$query = mysql_query("select * from data where id_user = '$id_user' order by date asc");
$i = 0;
$options = array();
while($data = mysql_fetch_array($query)){
$options[$data['id']] = $data['name'];
}
echo json_encode($options);
?>
javascript code:
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 response = JSON.parse(xmlhttp.responseText);
var select = '<select class='dropdown'>';
for( var index in response ){
select = select + "<option value='"+ index +"'>"+response[index]+"</option>";
}
select += "</select>";
document.getElementById("send2").innerHTML= select;
}
}
function changeSend() {
var selectBox = document.getElementById("sender");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
if (selectedValue==0) {
xmlhttp.open("GET","yourFile.php",true);
xmlhttp.send();
}
else {
$('#send2').html('');
}
}
USING jQuery
javascript code:
function changeSend() {
var selectBox = document.getElementById("sender");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
if (selectedValue==0) {
$.get("yourFile.php", function(data){
var response = JSON.parse(data);
var select = '<select class='dropdown'>';
for( var index in response ){
select = select + "<option value='"+ index +"'>"+response[index]+"</option>";
}
select += "</select>";
$("#send2").html(select);
});
}
else {
$('#send2').html('');
}
}
The best way would probably be with an ajax call, anyway if you are declaring the script in the same page with the php, you can json encode the array with the options so that you will be able to access it into the javascript, like this:
var optionIds = <php echo json_encode($id); ?>
var optionNames = <php echo json_encode($name); ?>
instead of populating the "tempDiv" in html, the print.php is loaded showing the content. The same code is working for other files and javascript functions. :/
HTML:
<li><a class="button black" href="#searchbox" onclick="viewall()" >View All</a></li>
<li><button class="button black" type="submit" form="selectcol" onclick="printDiv()"></button></li>
<div id="searchresults" style="padding-top:30px; padding-bottom:10px; max-height:280px; ">
The results will show up here..!!
</div>
<div id="tempDiv"></div>
The viewall() function :
function viewall(){
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("searchresults").innerHTML=xmlhttp.responseText;
}
}*/
xmlhttp.open("POST", "viewall.php", true); // set the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // adds a header to tell the PHP script to recognize the data as is sent via POST
xmlhttp.send(); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
document.getElementById("searchresults").innerHTML = xmlhttp.responseText;
}
}
}
The printDiv() function called to print the selected columns:
function printDiv()
{
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("searchresults").innerHTML=xmlhttp.responseText;
}
}*/
xmlhttp.open("POST", "print.php", true); // set the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // adds a header to tell the PHP script to recognize the data as is sent via POST
xmlhttp.send(); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
document.getElementById("tempDiv").innerHTML = xmlhttp.responseText;
}
}
}
PHP :
<?php
$col = $_POST['print'];
$flds = "";
foreach($col as $value){
if(isset($col)){
if($flds !="")
$flds .= ",";
$flds .= $value;
}
}
$sql = "SELECT ". $flds." from student";
$con = mysqli_connect("localhost", "root", "","university") or die("could not connect". mysqli_error($con));
$rs = mysqli_query($con, $sql);
echo "<table border='1'";
while($r = mysql_fetch_array($rs)){
echo "<tr>";
echo "<td class='searchtabledata'>".$r[0]."</td>";
echo "<td class='searchtabledata'>".$r[1]."</td>";
echo "</tr>";
}
?>
the result i get on clicking the submit button
Shouldn't you define the readystate function before sending the request?
part 2. It looks like your printdiv function submits a form. You should be able to remove the form tags if you are using a strictly AJAX procedure. You'll need to adjust a few other things to make that work.
UPDATE... this is the code I've implemented from the tutorial, within chrome dev tools in network i can see in header the variable is being sent and in preview i can see the drop down menu however it is not inserted into the loaded webpage
<script type="text/javascript">
$(document).ready(function() {
$('#selectEvidence').change(function(){
alert($(this).val());
});
});
function evidencesearch(str)
{
if (str=="")
{
document.getElementById("case").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("case").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","searchfunction.php?variable="+str,true);
xmlhttp.send();
}
</script>
<?php
$variable = $_GET['variable']; //used for second drop down menu
//echo "test test test $variable";
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'fid';
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
if (!$conn)
die('Could not connect: ' . mysql_error());
mysql_select_db($db);
echo '<label class="input" for="case" type="input">Specify: </label><select id="case" name="case"><option=value"null"></option>'; //Insert to loaded page
$resource = mysql_query("SELECT $variable FROM `evidence`");
if($resource && mysql_num_rows($resource)) {
while ($row = mysql_fetch_assoc($resource)){
echo '<option value="'.$row[$variable].'">'.$row[$variable].'</option></select>';//Insert to loaded page
}
}
mysql_close($conn)
?>
I think your problem sticks within POST/GET functions; try to call them synchronously and paste please the w3schools tutorial's link you mentioned. Maybe I can help you then by writing more detailed answer.
Cheers.
For some reason \u009a is being sent to the xmlhttp.responseText and not \u0161, and I'm not sure why. I want ลก to be displayed in the textbox, but, instead, the single character introducer is being sent instead. Any ideas how I can fix this?
Main page code:
function loadDoc()
{
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
var a = JSON.parse(xmlhttp.responseText);
document.getElementById("textbox").value=a.first;
document.getElementById("textbox2").value=a.second;
document.getElementById("textbox3").value=a.third;
document.getElementById("textbox4").value=a.fourth;
document.getElementById("textbox5").value=a.fifth;
document.getElementById("textbox6").value=a.sixth;
}
}
xmlhttp.open("GET","loadTextBox.php?id=4",true);
xmlhttp.send();
}
loadTextBox.php code:
<?php
header("Content-type: application/json");
---Placeholder for correct DB login info---
$result = $mysql->query(---Placeholder for correct SQL query---);
while ($row = $result->fetch_object())
{
$queryResult[] = $row->present_tense;
}
$textboxValue = $queryResult[0];
$textboxValue2 = $queryResult[1];
$textboxValue3 = $queryResult[2];
$textboxValue4 = $queryResult[3];
$textboxValue5 = $queryResult[4];
$textboxValue6 = $queryResult[5];
echo json_encode(array('first'=>utf8_encode($textboxValue),'second'=>
utf8_encode($textboxValue2),'third'=>utf8_encode($textboxValue3),'fourth'=>
utf8_encode($textboxValue4),'fifth'=>utf8_encode($textboxValue5),'sixth'=>
utf8_encode($textboxValue6)));
?>
Adding in the line $mysql->query("SET CHARACTER SET 'utf8'"); inside loadTextBox.php after connecting to the DB and before the SQL query and removing the lines with utf8_encode fixed it.
I am using an Ajax call to a PHP file to get data from MySQL database and populate select options in HTML. The problem is that duplicate items in the options and I don't know why. I tried the query in workbench and it brings back what I need.
PHP file:
<?php
$q=$_GET["q"];
// open db connection code
$query = "select * from r2rtool.materialtype where type = 'FE' and tools like '%".$q."%'";
$result = mysql_query($query);
$option = "";
while($row = mysql_fetch_array($result))
{
$mat = $row["Material"];
$option.="<option value=\"$mat\">".$mat."</option>";
echo $option;
}
// close db connection
?>
Ajax function:
function populatematerial(str)
{
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{
// 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","phpfile.php?q="+str,true);
xmlhttp.send();
}
while($row = mysql_fetch_assoc($result))
{
$option .= "<option value=\"{$row[Material]}\">{$row[Material]}</option>";
}
echo $option;
All you need to do is to move the echo $option; out of the while loop, like so:
while($row = mysql_fetch_array($result))
{
$mat = $row["Material"];
$option.="<option value=\"$mat\">".$mat."</option>";
}
echo $option;
You should output the HTML after you built it, not while you build it.
use mysql_fetch_assoc instead of mysql_fetch_array because array returns value in numbers and name both format, so it will twice data,
where mysql_fetch_assoc returns array as only name element of array ..
for more understanding
try
<?php
$query = mysql_query("some query ");
$row = mysql_fetch_array($row);
$assoc = mysql_fetch_array($row);
print_r ($row);
echo "<br>";
print_r ($assoc);
echo "<br>";
?>