ajax json decode mysql fetch array - php

$result = mysql_query ("SELECT * FROM order_list");
$test = array();
$i=0;
$myjsons = array();
while($row = mysql_fetch_assoc($result)){
echo $myjsons[] = json_encode(array($row));
}
and a AJAX javascript
function ajaxFunction() {
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser is too old to run me!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4) {
document.getElementById("resultTXT").value = eval(" (" + ajaxRequest.responseText + ")");
}
}
ajaxRequest.open("POST", "userfind.php", true);
ajaxRequest.send(null);
}​
the javascript function wont store the array into the textbox
can anyone tell me whats the problem here?
Thanks

try:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo json_encode($myjsons);
instead of
while($row = mysql_fetch_assoc($result)){
echo $myjsons[] = json_encode(array($row));
}
you can use jquery library for tha ajax call http://api.jquery.com/jQuery.post/
$.post('userfind.php', function(data) {
$("#resultTXT").val(data);// ==document.getElementById("resultTXT").value =data;
},'json'
);

JSON output would be invalid in your example, build the array and out put a single json encoded array like so:
$myjsons = array();
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
echo json_encode($myjsons);

Related

AJAX search doesn't work with spaces

I have problem when user types with spaces into live Ajax search it doesn't show any results. When user types only half of word without spaces it works fine. I think its something with Ajax, but can't find any solution here.. Maybe you can suggest something.. Thanks.
Ajax:
function ajaxFunction(str)
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateChanged()
{
if (httpxml.readyState == 4)
{
document.getElementById("displayDiv").innerHTML = httpxml.responseText;
document.getElementById("msg").style.display = 'none';
}
}
var url = "search-ajax.php";
url = url + "?txt=" + str;
url = url + "&sid=" + Math.random();
httpxml.onreadystatechange = stateChanged;
httpxml.open("GET", url, true);
httpxml.send(null);
document.getElementById("msg").innerHTML = "Please Wait ...";
document.getElementById("msg").style.display = 'inline';
}
search-ajax.php:
error_reporting(0);
require "search_con.php";
$in = $_GET['txt'];
if (!ctype_alnum($in)) {
echo "";
exit;
}
$msg = "";
$msg = "<div id=results style=position:absolute;z-index: 10;right:0px;background-color:#302b2b;>";
if (strlen($in) > 0 and strlen($in) < 20) {
$sql = "SELECT * FROM products WHERE name LIKE '%$in%' LIMIT 17";
foreach ($dbo->query($sql) as $nt) {
$name = $nt['name'];
$msg .='<div>' . $name . '<div>';
}
}
$msg .='</div>';
echo $msg;
What could it be? Thanks for all your suggestions :)
The function ctype_alnum will return false if the text contains a space. So maybe your script stops there ?
$in = $_GET['txt'];
//always occurs when a space is in the $in variable.
if (!ctype_alnum($in))
{
echo "";
exit;
}
Make sure you use trim() BEFORE you make that check. That check will also stop any search for a text which as space inside the text like "New year".
You have to remove leading and trailing spaces of txt in your PHP script:
$in = trim($_GET['txt']);
Solved it, I realised that I don't need this block of code.
if (!ctype_alnum($in)) {
echo "";
exit;
}

Alternative to innerHTML for IE select box

I have a problem that is php data not showing in select box. innerhtml not working in Internet Explorer. long_description_detail_list data not showing in select box.please help me
first page:
<div id="long_description_detail_list" style="display:none;">
<option value="0">Select..</option>
<?php
include_once('Model/Language.php');
$r = new Language();
$a = $r->Select();
for($i = 0; $i < count($a); $i++)
{
print '<option value="'.$a[$i][0].'">'.$a[$i][1].'</option>';
}
?>
</div>
<script language="javascript" type="text/javascript">
//Browser Support Code
function create_long_description_detail_div(){
if(count_table_long_description_detail() >=3) {
alert("You can not add more than 3 long_description Details");
}
else {
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var blank_long_description_detail = ajaxRequest.responseText;
document.getElementById('long_description_detail_counter').value ++;
$('#my-all-long_description_details-here').append(blank_long_description_detail);
set_new_height_of_step_2('inc');
var long_description_list_counter = document.getElementById('long_description_detail_counter').value;
var long_description_detail_list = document.getElementById('long_description_detail_list').innerHTML;
document.getElementById('llanguage[' + long_description_list_counter + ']').innerHTML = long_description_detail_list;
}
}
var long_description_detail_counter = document.getElementById('long_description_detail_counter').value;
var queryString = "?long_description_detail_counter=" + long_description_detail_counter;
ajaxRequest.open("GET", "Views/User/long_description/add_long_descriptions_detail.php" + queryString, true);
ajaxRequest.send(null);
}
}
</script>
data not showing here in second page named add_long_descriptions_detail.php:
<select id="llanguage[<?php echo $counter; ?>]" name="llanguage[<?php echo $counter; ?>]" class="txtBox">
<option value="0">Select..</option>
</select>
IE doesn’t support updating the elements of a <select> with innerHTML, but what you can do is use the DOM, which is always the right way to go about things anyways.
Make your server-side script return a JSON array of options; it’ll make everything a lot easier.
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState === 4) {
// Parse the response
var options = eval('(' + ajaxRequest.responseText + ')');
// Get the box; I have no clue what this is
var box = document.getElementById('llanguage[' + long_description_list_counter + ']');
// Clear any current elements
while(box.childNodes.length > 0) {
box.removeChild(box.firstChild);
}
// Add new ones
for(var i = 0; i < options.length; i++) {
var newOption = document.createElement('option');
newOption.value = options[i].value;
newOption.appendChild(document.createTextNode(options[i].text));
}
}
};
(This is a little trimmed-down from your original code, but I’m sure you can fit it in.)
It’s also probably a good idea to use an old-IE-compatible JSON parser instead of eval.
The JSON should look like this:
[
{ "text": "Some text", "value": "some-value" }
]
You can use json_encode to produce it conveniently from a PHP array.

How to pass javascript variable to php in html? (wikipedia parsing)

Hi I'm trying to pass a javascript variable called $url to a function in php all located in the same html file. The logic here is that there is a text box and the user inputs a species and we call the wikipedia api to check if the input has a wikipedia page if it does I parse the page and bring the species info up, everything works independently 100% but I cant seem to connect them. However I cant get javascript to pass the url to the php function below. and innerHTML the php function with the url which is suppose to render the parsed species info. The error I get is that from the get go I just get the php function spit out with nothing.
Enter a species here : [text box here]
find('table.infobox'); foreach($html->find('img') as $element) { $image[]= $element; } Print $image[1]; $data = array(); foreach($table[0]->find('tr') as $row) { $td = $row->find('> td'); if (count($td) == 2) { $name = $td[0]->innertext; $td = $td[1]->find('a'); $text = $td[0]->innertext; $data[$name] = $text; } } print ""; foreach($data as $value => $before ) { print ""; } print "
$value $before
"; } ?>
Here is my attempt so far, I call the javascript and check if a link is found and call the parse function to innerthml out in the result div
<?php
//call the javascript
//if link found
//send ajax url variable to php function
//ajax call the function innerhtml in the result div
//We check if we have the param within the page call
$theDeletenode = false;
if(isset($_POST['deletenode']))
$theDeletenode = $_POST['deletenode'];
if($theDeletenode)
{
//The param 'deletenode' is given, so we juste have to call the php function "parse", to return the value
parse($theDeletenode);
}else
{
// No parametre, so we echo the javascript, and the form (without the quote and \n, it's much better)
?>
Here is the start of my html, the text box is connected to javascript which called the wikipedia api to check if the input has a wikipedia page.
<html><head>
<script type="text/javascript">
// create and return an XMLHttpRequest object
function createRequest() {
var ajaxRequest; // the xmlrequest object
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
return ajaxRequest;
}; // end of createRequest
var spellcheck = function(data){
var found=false;var url='';
var text=data[0];
if(text!=document.getElementById('spellcheckinput').value) return;
for(i=0;i<data[1].length;i++)
{
if(text.toLowerCase()==data[1][i].toLowerCase())
{found=true;
url='http://en.wikipedia.org/wiki/'+text;
document.getElementById('spellcheckresult').innerHTML='<b style=\"color:green\">Correct</b> - <a target=\"_top\" href=\"'+url+'\">link</a>';
}
}
if(!found)
document.getElementById('spellcheckresult').innerHTML='<b style=\"color:red\">Incorrect</b>';
};
var requestone = createRequest();
var getjs= function(value)
{
if(!value) return;
var url='http://en.wikipedia.org/w/api.php?action=opensearch&search='+value+'&format=json&callback=spellcheck'; // this is the variable I want to pass
document.getElementById('spellcheckresult').innerHTML='Checking ...';
var elem=document.createElement('script');
elem.setAttribute('src',url);
elem.setAttribute('type','text/javascript');
document.getElementsByTagName('head')[0].appendChild(elem);
// Ajax call to this page, this time with the 'deletenode' parameter
var vars = "url=" + encodeURIComponent(url);
requestone.open("POST", "parser.php", true); // parser.php : the name of this current page
requestone.onreadystatechange = handleRequest; // function to handle the response
requestone.send(vars);
};
function handleRequest()
{
//here we handle the php page response by echoing de result of the php page (normally the result of the parse function)
try{
if(requestone.readyState == 4 && requestone.status == 200)
document.getElementById('resultdiv').innerHTML= requestone.responseText;
} catch (e) {
//Wrong server answer...
}
};
</script>
</head>
<body>
<form action="#" method="get" onsubmit="return false">
<p>Enter a species here : <input id="spellcheckinput" onkeyup="getjs (this.value);" type="text">
<span id="spellcheckresult"></span></p>
</form>
<div id=resultdiv></div>
</body>
</html>
Here is my parse function which recieves a variable called url which is the validated wikipedia page and then it parses it for species info, this tested and it works but I cant get it to innerhtml this function along with the validated wikipedia url.
<?php
}
function parse($url){
print $url;
$html = file_get_html('http://en.wikipedia.org/wiki/Beaver');
$table = $html->find('table.infobox');
foreach($html->find('img') as $element)
{
$image[]= $element;
}
Print $image[1];
$data = array();
foreach($table[0]->find('tr') as $row)
{
$td = $row->find('> td');
if (count($td) == 2)
{
$name = $td[0]->innertext;
$td = $td[1]->find('a');
$text = $td[0]->innertext;
$data[$name] = $text;
}
}
print "<table class='infobox' style='text-align: left; width: 200px; font-size: 100%'>";
foreach($data as $value => $before )
{
print "<tr><td>$value</td><td>$before</td></tr>";
}
print "</table>";
}
?>
This question has many related answers 1234
If it helps, here is some JavaScript:
var form = document.createElement("form");
var input = document.createElement("input");
form.method="{post/get}";
form.action="{page}";
input.name="{name}";
input.value="{value}";
form.appendChild(input);
form.submit();

Fault in Ajax php search

In the following Ajax based search box, if the character is at position 0 then the respective name in the array is not returning but for characters at other positions everything works well. Please fix this...
PHP
$query = $_GET['query'];
$names = array('abc', 'hello', 'cool', 'fun', 'demo', 'test');
foreach($names as $name)
{
$str = strpos($name, $query);
if(!empty($str))
{
echo "$name ";
}
}
HTML
<form name='myForm'>
Name: <input type='text' onblur="ajaxFunction(this.value);" name='username' /> <br />
Time: <input type='text' disabled="disabled" name='time' />
</form>
AJAX
function ajaxFunction(val) {
var ajaxRequest;
try {
//Opera, Safari and Firefox xml object
ajaxRequest = new XMLHttpRequest();
} catch(e) {
try {
//Internet Explorer xml object
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
//Old browser's xml object
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
} else {
//do nothing
}
}
ajaxRequest.open("GET", "names.php?query="+val, true);
ajaxRequest.send(null);
}
You can use the following -
if($str !== FALSE)
{
echo "$name ";
}
That's maybe of the 0 Value returned by strpos (it returns an integer) ... i mean the "if" statement could value it as a false.
Try to compare like
if(strpos($name, $query) === false){ .... do something..... }

How to use AJAX in IE

i'm using IE and I need to do a simple AJAX that will display a table with values from the database once a dropdown has been changed.
Here is my script:
<script type="text/javascript">
function getXML()
{
var req;
try {
req = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
req = null;
}
}
}
if (!req){
return null;
} else {
return req;
}
}
function filter(month, year)
{
if(getXML()){
var xmlhttp = getXML();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("mandayTable").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax/filterMandays.php?m="+month+"&y="+year,true);
xmlhttp.send();
} else {
alert("Error initializing XMLHttpRequest!");
}
}
</script>
and here is my ajax php
<?php
$q = "SELECT md.mandays_id,md.employeenum,md.month,md.year,md.required_man_days,d.firstname,d.lastname
FROM tbl_mandays md,tbl_employee_details d
WHERE md.active = '1'
AND md.employeenum = d.employeenum
AND md.month = '10';"; //employee_details WHERE approver = 0"
$res = $db->Execute($q);
echo "<table border = 1>";
echo "<tr><th>Employee Number</th><th>First Name</th><th>Last Name</th><th>Month-Year</th><th>Required Man Days</th><th>Edit/Delete</th></tr>";
/while($rows = $res->FetchRow())
for($i=0;$i<5;$i++)
{
$mandays_id = $rows[0];
$empnum = $rows[1];
$month_year = $rows[2] ."-" .$rows[3];
$required_man_days = $rows[4];
$firstname = $rows[5];
$lastname = $rows[6];
echo "<tr><td>".$empnum . "</td><td>".$firstname ."</td><td>".$lastname ."</td><td>" . $month_year ."</td><td>" .$required_man_days . "</td><td width = \"200\" align = \"center\"><a href = 'edit_mandays.php?mandays_id=$mandays_id');'>Edit/Delete</a></td></tr>";
}
echo "</table>";
?>
THe problem is that on the first "ONCHANGE" it does not do anything.
on the 2nd "ONCHANGE" the headers of the table in the php code is the only one that's being echoed.
I alsoi tried doing it without the query and changing the loop into for($i=0;$i<5;$i++) and changed the qvalues to be displayed into "1" but still it does noty go into the loo[ and display it.
what seems to be the problem? :(
Start here : https://developer.mozilla.org/en/AJAX/Getting_Started , Mozilla explains the correct way to do this across browsers. Later, you may consider jQuery for cross-browser compatibility once you've learned the basics
Download and use jQuery for your website: http://docs.jquery.com/Downloading_jQuery#Download_jQuery
And then your code will be something like this:
$('.mydropdown').change(function(){
//get values for month, year
$.ajax({
url: "ajax/filterMandays.php?m="+month+"&y="+year,
type: "GET",
success: function(data){
//data is returned back
$('#mandayTable').html(data);
}
});
});

Categories