I'm currently working with the jQuery Autocomplete Plugin.
The code they provided in the demonstration is:
<?php
$q = strtolower($_GET["q"]);
$items = array(
"Peter Pan"=>"peter#pan.de",
"Molly"=>"molly#yahoo.com",
);
$result = array();
foreach ($items as $key) {
if (strpos(strtolower($key), $q) !== false) {
array_push($result, array(
"name" => $key
));
}
}
echo json_encode($result);
?>
I'd like to know how I can modify this code to output my own array from my MySQL database.
I've tried on my own modification, but I'm not doing it correctly. This is what I am trying:
$q = strtolower($_GET["q"]);
$sql = "SELECT name from user_info";
require("connection.php");
$result = mysql_db_query($DBname,$sql,$link) or die(mysql_error());
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
foreach ($rows as $key) {
if (strpos(strtolower($key), $q) !== false) {
array_push($result, array(
$key
));
}
}
}
print json_encode($rows);
And this is my jQuery/Javascript:
$("#email").autocomplete('emails.php', {
multiple: false,
dataType: "json",
parse: function(data) {
return $.map(data, function(row) {
return {
data: row,
value: row.name,
result: row.name
}
});
},
formatItem: function(item) {
return format(item);
}
}).result(function(e, item) {
$("#content").append("<p>selected " + format(item) + "</p>");
});
});
As a result, Firebug shows that it throws the following error:
value is undefined
Any help on getting my query setup properly would be greatly aprpeciated. Thanks!
I think that this occurs because you using a array converted in json, then you need to use how an array too in jquery result. Or you can do a json string without using json, in the format: '[{"name":"john","year":2009},{"name":"tom","year":2000},...]'.
Your jquery is fine. After several hours I found out that it was the formatting in the 'format' function that was triggering the error.
If you look at the source code at
http://jquery.bassistance.de/autocomplete/demo/json.html
You'll see the following, seemingly inconsequential function
function format(mail) {
return mail.name + " <" + mail.to + ">";
}
If you're leaving out the 'less than' and 'greater than' representations, then you're probably getting the
value is undefinded
error after the first record is looped through in your console. For some strange reason the less than and greater than symbols are significant. Make sure you keep them in your format function.
Related
I'm working on a php project and the search function from the database is not returning any results or any error. Below is the code for the search function:
function searchweb() {
console.log("click");
//e.preventDefault();
searchWebsite = $("#searchWebsite").val();
if (searchWebsite == "")
$("#searchWebsite").focus();
else {
console.log("else");
$("#search").html("Searching..");
$("#search").attr("disabled", true);
var excat = "like";
if ($('input[type=checkbox]').prop('checked'))
excat = "match";
$.post("userinput.php", {
searchWebsite: $("#searchWebsite").val(),
excat: excat
}, function (data) {
console.log("hey"+data);
populateSearch(data);
});
function populateSearch(data){
data = JSON.parse(data);
$('#result').empty();
$.each(data, function (key, value) {
//console.log(data);
$('#result').append("<tr>\
<td><a href='"+value.website_name+"' target='_blank'><i class='glyphicon glyphicon-search'></i></a></td>\
<td>"+value.website_name+"</td>\
<td>"+value.avg_score+"</td>\
<td><img class = 'imgs img-responsive center' src='../img/"+value.remark+".png' alt ='"+value.remark+"' />\
</td></tr>");
});
}
// console.log(searchWebsite);
$("#search").html("Search Website");
$("#search").attr("disabled", false);
}
}
The 'searchweb' function calls the post method to search in the mysql database. I'm using phpmyadmin for this project. The code for post function in userinput file:
if(isset($_POST['searchWebsite'])){
$searchWebsite = $_POST['searchWebsite'];
$type = $_POST['excat'];
$sql = "SELECT * from websites WHERE ";
//for excact match
if($type=="match")
$sql.= "MATCH(tags) Against('$searchWebsite') ORDER BY avg_score DESC";
//for tags contaionun gthose words
else
$sql.= "tags LIKE '%$searchWebsite%' ORDER BY avg_score DESC";
$result = mysqli_query($db, $sql);
if($result){
$rr = array();
$i=1;
while($row = mysqli_fetch_assoc($result))
{ $rr[] = $row;
$i=$i+1;}
echo json_encode($rr);
}
else
{
echo "<script type='text/javascript'>alert('Error: '".mysqli_error($db).");</script>";
}
}
No error will be spit back as this is a .post in javascript call / AJAX request. AJAX will not dynamically parse the javascript error code you're trying to trap within the AJAX request.
It's better to do something like this:
PHP side:
Replace:
echo "alert('Error: '".mysqli_error($db).");";
With:
echo json_encode( [ 'error' => mysqli_error($db) ] );
Javascript Side:
// Note you shouldn't have to parse JSON since on the PHP side the error array has been encoded as json
if( ! $.isEmptyObject(data.error) ) {
alert( data.error );
}
I am dynamically adding table rows by selecting options from dropdown and then I am trying to send html table rows to php function using ajax as array in json format. However php function does not print all rows in the console log, when I am submitting more than one row. I got the desired output like once or twice. I think I am missing something in the php function. Please check once. If anymore information about the code is required, let me know, I will update.
Javascript:
function storeClgValues() {
var CollegeData= new Array();
$('#collegetable tr').each(function(row, tr){
CollegeData[row]={
"college" : $(tr).find('td:eq(0)').text()
}
});
CollegeData.shift();
return CollegeData;
}
$('#submit').click(function() {
CollegeData=storeClgValues();
CollegeData=$.toJSON(CollegeData);
$.ajax({
type:"POST",
url: '<?php echo base_url();?>ajaxController/insertcollege',
data: "CollegeData=" + CollegeData,
success: function(msg) {
console.log(CollegeData);
console.log(msg);
}
});
});
PHP function in AjaxController class:
public function insertcollege()
{
$data=array();
$data=stripcslashes($_POST['CollegeData']);
$data=json_decode($data, TRUE);
//echo $data[0]['college'].'<br>';
//echo $data[1]['college'].'<br>';
if (is_array($data) || is_object($data))
{
foreach ($data as $key => $item) {
echo $item['college'].'<br>';
}
}
}
Output in console in three tries:
[{"college":"College of Agriculture"}]
College of Agriculture
[{"college":"College of Agriculture"},{"college":"College of Business"}]
College of Agriculture
College of Business
[{"college":"College of Agriculture"},{"college":"College of Business"}, {"college":"College of Comm & Educati"}]
<!--nothing gets printed-->
Try like this...
<?php
$json = '[{"college":"College of Agriculture"},{"college":"College of Business"}, {"college":"College of Comm & Educati"}]';
$data = json_decode($json,TRUE);
//print_r($data);
if (is_array($data) || is_object($data))
{
foreach ($data as $key => $item) {
$output[]=$item['college'].'<br>';
}
}
echo json_encode($output);
?>
OR
<?php
$json = '[{"college":"College of Agriculture"},{"college":"College of Business"}, {"college":"College of Comm & Educati"}]';
$data = json_decode($json,TRUE);
//print_r($data);
if (is_array($data) || is_object($data))
{
foreach ($data as $key => $item) {
foreach($item as $value){
$output[] = $value."</br>";
}
}
}
echo json_encode($output);
?>
Please help.
I am using codeigniter/php for my website. It is working well in my localhost but when I tried to transfer it to live, it's getting an error. The error part is detected in my script where I am trying to parse a json generated in php. this is where the json is encoded :
function get_product_offered_json(){
$data = [];
$query = $this->db->get("product_smb");
if ($query->num_rows() > 0){
foreach ($query->result() as $row) {
$data[] = $row;
}
return json_encode($data);
}else{
return "empty";
}
}
and this is where i parse it:
jQuery.post(base_url + "/product/smb/get_product_offered_json/", function(data, status){
if (data != "empty"){
//productOffered.prop( "disabled", false );
var $data = jQuery.parseJSON(data);
productOffered.empty();
productOffered.append("<option value='0'>Please choose here...</option>");
Hope this is enough to explain my issue. thanks
Use echo instead of return ,in ajax we get the output
if ($query->num_rows() > 0){
foreach ($query->result() as $row) {
$data[] = $row;
}
echo json_encode($data);
}else{
echo "empty";
}
i am trying to get the data which is in array, from an SQL query to the ajax success data. Here is the code i tried,
function adminchecksub(value1){
//alert('hi');
var value1=$('#adminsid').val();
//alert(value1);
if(value1==''){
alert('Please enter a Sub id');
}
else{
//alert(value1);
$.ajax({
type: 'POST',
url: root_url + '/services/services.php?method=adminsubcheck',
data: {value1:value1},
async: true,
success: function (data) {
alert(data);
if (data == 1) {
alert('inside');
//window.location.assign(rdurl+"?sid="+sid);
return true;
} else {
//alert('does not exist!');
//alert('outside');
return false;
}
}
});
}
now in the php method which is requested from the above ajax call, i have to get the data return by this function which is returning an array
function adminsubcheck($sid){
$subid=$sid['value1'];
$row = array();
//echo $subid;
$query = "SELECT Sub_id,Status,Sub_type FROM Sub WHERE Sub_id=$subid";
//echo $query;
//echo $subid;
$queryresult = mysql_query($query);
$count = mysql_num_rows($queryresult);
//echo $count;
while ($r = mysql_fetch_assoc($queryresult)) {
$row[] = $r;
}
return $row;
}
here $row is returning an array as data to the ajax function, where i need to get all the items seperately. Some one help me out to get the values into the ajax call. Thanks in advance..
In your PHP file, you can return your array as a json object in the following way (notice how the PHP file echos the result to pass it back to javascript)
...
$json = json_encode($row);
echo $json
Now add the following to your javascrip ajax
$.ajax({
...
// Whatever code you currently have
...
}).done(function ( json ) {
var data = JSON.parse(json);
//Continue with javascript
});
You can handle the java script variable 'data' as an associative array like it was in PHP
also, look how you populate the php variable $row and adjust the following way:
$cnt = 0;
while ($r = mysql_fetch_assoc($queryresult)) {
$row[$cnt] = $r;
$cnt++;
}
$json = json_encode($row);
echo $json;
in javascript you can access your rows the following way in teh data variable:
var value = data[0]['field_name'];
in the above statement, 0 will correspond to the value of $cnt (i.e. mysql returned row number)
return $row;
replace like this
echo json_encode($row);
and add dataType='json' in ajax like this
dataType: 'json',
If you want get the value in ajax call i think it shoul be :
while ($r = mysql_fetch_assoc($queryresult)) {
$row[] = $r;
}
echo json_encode(array('data'=>$row));
exit;
I am getting a NaN error in my ajax callback function and can only think it has to do with an array in PHP. I have been trying to find ways to correct it but have come up against a brick wall.
What is supposed to happen is that PHP queries the database and if there are no results send a response to ajax and issue the error message. However, all I am getting is NaN. The error stems from the success code below.
I would be grateful if someone could point out my error.
PHP code:
$duplicates = array();
foreach ($boxnumber as $val) {
if ($val != "") {
mysql_select_db($database_logistor, $logistor);
$sql = "SELECT custref FROM boxes WHERE custref='$val' and status = 'In'";
$qry = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($qry) < 1) {
$duplicates[] = '[ ' . $val . ' ]';
$flag = 1;
} else {
$duplicates[] = $val;
}
}
}
//response array with status code and message
$response_array = array();
if (!empty($duplicates)) {
if ($flag == 1) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'ERROR: ' . implode(',', $duplicates) . ' needs to be in the database to be retrived.';
}
//if no errors
} else {
//set the response
$response_array['status'] = 'success';
$response_array['message'] = 'All items retrieved successfully';
$response_array['info'] = ' You retrieved a total of: ' . $boxcount . ' boxes';
}
//send the response back
echo json_encode($response_array);
Relevant ajax:
$("#brtv-result").html(msg.message+msg.info);
jQuery code:
$(function() {
$("#BRV_brtrv").submit(function() {
var send = $(this).serialize();
$.ajax({
type: "POST",
url: "boxrtrv.php",
cache: false,
data: send,
dataType: "json",
success: function(msg) {
if( msg.status === 'error') {
$("#brtv-result").fadeIn(1000).delay(1000).fadeOut(1000);
$("#brtv-result").removeClass('error');
$("#brtv-result").removeClass('success');
$("#brtv-result").addClass(msg.status);
$("#brtv-result").html(msg.message);
}
else {
$("#brtv-result").fadeIn(2000).delay(2000).fadeOut(2000);
$("#brtv-result").removeClass('error');
$("#brtv-result").addClass('success');
$("#brtv-result").addClass(msg.status);
$("#brtv-result").html(msg.message+msg.info);
//location.reload(true);
//$('#brtv-result').addClass("result_msg").html("You have successfully retrieved: "+data.boxnumber).show(1000).delay(4000).fadeOut(4000);
$("#BRV-brtrv-slider").val(0).slider("refresh");
$("input[type='radio']").attr("checked",false).checkboxradio("refresh");
var myselect = $("select#BRV-brtrv-department");
myselect[0].selectedIndex = 0;
myselect.selectmenu("refresh");
var myselect = $("select#BRV-brtrv-address");
myselect[0].selectedIndex = 0;
myselect.selectmenu("refresh");
}
},
error:function(){
$("#brtv-result").show();
$("#brtv-result").removeClass('success');
$("#brtv-result").addClass('error');
$("#brtv-result").html("There was an error submitting the form. Please try again.");
}
});
return false;
});
});
NaN (pronounced nan, rhymes with man) only happens when you try to do an operation which requires a number operand. For example, when you try to Number('man') you'll get this error.
What you return from your PHP file, is simply an array which contains simply data. So, the problem is in your JavaScript. You have to send more parts of your JavaScript, so that we can see it thoroughly.
However, I recommend that you use Firebug and set a breakpint at the correct place (the callback function start), and check the stack trace of the calls to diagnose the problem.