PHP/jquery autocomplete not loading JSON_ERROR_UTF8 - php

I've got the following code which works only for 70 items. the moment I added the 71st item to the DB it fails to work.
$('document').ready(function() {
//autoComplete() returns a php array with all the products
<?php $productArray = autoComplete();?>
var js_products_array = <?php echo json_encode($productArray); ?>;
var result;
for(var i=0;i<js_products_array.length;i++){
result += js_products_array[i] + ', ';
}
//printing js_products_array
document.write(result);
$( "#autocompleteID" ).autocomplete({
source: js_products_array
});
...
I can see that js_products_array holds all the values but the autocomplete feature fails to work. The moment i remove the 71st item from the DB it works again.
I'm puzzled as to what's causing this. Would appreciate some help, cheers.

hmmm, try to use
json_last_error
var last_error = <?php echo json_last_error(); ?>;
http://php.net/manual/en/function.json-last-error.php
to check the problem
or
limit the number of records , it is easy to limit the number of records in database level
UPDATE
try
in your server function autoComplete() before returning the result to the view use this function to utf-8 encode the array
utf8_encode_deep($result_from_db);
function utf8_encode_deep(&$input) {
if (is_string($input)) {
$input = utf8_encode($input);
} else if (is_array($input)) {
foreach ($input as &$value) {
utf8_encode_deep($value);
}
unset($value);
} else if (is_object($input)) {
$vars = array_keys(get_object_vars($input));
foreach ($vars as $var) {
utf8_encode_deep($input->$var);
}
}
}
then you can use
json_encode($productArray);

The following piece of code fixed the problem: mysqli_set_charset($db, "utf8");

Related

Access Each JSON Array Element onClick Using AJAX PDO PHP

I'm trying to access each element stored as a Base64 image/blob in a JSON array constructed from a MySQL query.
The idea is to click a button that goes through each element and displays the image.
I have gotten it to display the first image however when i click again, the next image doesn't show.
Any help will be much appreciated.
AJAX:
$(function () {
$('#getimg1').on('click', function () {
$.ajax({
type:'GET',
dataType: 'json',
url: 'http://testing/api/getimg',
success:function(getinfo){
$.each(getinfo, function(i, displayimg){
$('#HTMLBox').prop('src','data:image/png;base64,' + displayimg.XXX ---- //Here I'm suspecting something?);
});
}
});
});
});
PHP:
$sql = "SELECT img from artistlocation";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$data = array();
while($result = $stmt->fetch(PDO::FETCH_OBJ))
{
$data[] = base64_encode($result->img);
}
echo json_encode($data);
}
catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
I'm using just 2 images to test this.
Because the ajax call you make will return all of the image records, I think it would be more efficient to store that data in a variable and then just rotate through the images rather than making call to your php code with each click. Here's what I would suggest, if you're using just jQuery:
var images = [],
index = 0,
count = 0,
max = 0;
$.getJSON("http://testing/api/getimg", function(data) {
images = data;
count = images.length;
max = count - 1;
});
$('#getimg1').on('click', function() {
if (count === 0) {
return;
}
if (index === max) {
index = 0;
} else {
index++;
}
$('#HTMLBox').attr('src', 'data:image/png;base64,' + images[index]);
});
I must admit I didn't test it, but I believe it should work - if you could try and see how you get on.
So, if you wanted to do something really dirty, you could track how many images you've loaded via a hidden input. You can increment that upon your ajax success. Then, what you can do is pass to your PHP via your AJAX that value, and run something like:
SELECT * FROM images LIMIT 1 OFFSET $images_already_fetched
By passing an OFFSET declaration, you're telling it to skip that many rows.

Attribute from php to Jquery.click within php foreach

I've been trying out different things for a while, but nothing seems to be working. And would probably need another kind of perspective.
For the question: I got a php foreach loop going, and every object is posting the ID of that object.
But my problem in this that when i click, the object is giving me the last number of the foreach.
Ive been trying to post the value in JSON, and just plain php.
PHP
<?php
foreach ($places as $place) {
$place_id = json_encode($place['id']);
echo "<div class='placeContainer' onClick='openMessage(\'' . $place_id .
'\')'>";
?>
Jquery
$(document).ready(function () {
$('.placeContainer').click(function () {
$(this).attr(phpvar);
var myKey = JSON.parse(phpvar);
console.log(myKey);
})
});
Thanks for the help!
Try this :
PHP Code :
<?php
foreach ($places as $place) {
$place_id = json_encode($place['id']);
echo "<div class='placeContainer' data-id='".$place_id."'>";
?>
JS Code :
$(document).ready(function () {
$('.placeContainer').click(function () {
var myKey = $(this).attr('data-id');
console.log(myKey);
})
});

can getJSON() be used for php?

This is the JQuery code loaded over click but the callback function isn't working:
$.getJSON("load_img.php", {"id":"start"} , function(json){
alert(json);
});
PHP code gives me this output:
[
{"img_name":"shiva.jpg","img_id":"1"},
{"img_name":"shiva.jpg","img_id":"2"},
{"img_name":"Recoverd_jpg_file(4).jpg","img_id":"3"},
{"img_name":"Recoverd_jpg_file(542).jpg","img_id":"4"}
]
I cannot load any PHP pages from getJSON() function...i downloaded sample source code from [here][1]
[1]: http://www.sitepoint.com/ajaxjquery-getjson-simple/ and have run it on browser but it doesnt work still...
any help would be much appreciated!!!Thank you
I got my answer today...no <html> tags should be included in the code to be outputted... it should only contain starting and ending php tags i.e.
<?php
//your code or codes
?>
$.getJSON("path to php file", {method: "*", "id":"start"})
.done(function (data) {
console.log(data)
});
//================in php=================================
if($_REQUEST['method'] == "your method" AND $_REQUEST['id'] ) {
//call your php function
}
//-------------------
//and put your php code in function
//.. i hope this help you
<button id="try" type="button">Try</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
$.getJSON("load_img.php", {"id":"start"}, function(result){
$.each(result, function(i, field){
alert(field.img_name);
});
});
i is the field name and field is value. Please check and post me back. For further details :-http://www.w3schools.com/jquery/ajax_getjson.asp
Page Two:-
<?php
// ini_set("display_errors", "On");
//header('content-type:application/json');
$id = $_GET["id"];
if ($id == "start")
{
$con=new mysqli("localhost", "root", "rootwdp", "try");
$numbers = array();
$img_arr = array();
$res = $con->query("select img_name, img_id from img");
while ($row = $res->fetch_assoc())
// mysql_fetch_array() passes parameters from 0
{ $numbers[]=$row; }
echo json_encode($numbers);
}
?>

How can i get looping autocomplete value

My PHP Code In Model using Codeigniter
$return_arr =array();
$new_row =array();
foreach($query->result_array() as $row) {
$new_row['value'] = $row['test_type_name'];
$this->db->select('*');
$this->db->from('p_test');
$this->db->where('test_type_name',$new_row['value']);
$query_tt = $this->db->get();
$i =0;
foreach($query_tt->result_array() as $row_tt) {
$i++;
$new_row['test_name'.$i] = $row_tt['test_name'];
}
$new_row['inc_i'] = $i;
array_push($return_arr,$new_row);
}
echo json_encode($return_arr);
My jQuery Code
$('#p_test_name').keydown(function () {
var id_no_t = document.getElementById('id_no').value;
$(this).autocomplete({
source: "<?php echo base_url(); ?>p_con/p_test_name/" + id_no_t,
minLength: 0,
autoFocus: true,
select: function (event, ui)
{
var tot_i = ui.item.inc_i;
for (i = 1; i <= tot_i; i++)
{
var test_name = 'test_name'+i;
test_name = ui.item.test_name;
$("#test_name"+i).val(test_name);
}
}
}
});
});
Actually i want to get value using loop.
If i use separately ui.item.test_name1, ui.item.test_name2 .......etc without loop.
Then Value comes perfect but if i use loop like my above code then value comes undefined.
Please tell me, How to solve it?
You are using the ui.item.test_name in which the test_name is referred to as the key. If I understand your question correctly, what you are willing to do is to use the value of test_name as key. Try this instead:
for (i = 1; i <= tot_i; i++)
{
var test_name = 'test_name' + i;
test_name = ui.item[test_name];
$("#test_name"+i).val(test_name);
}
This should effectively turn out to be using ui.item['test_name1'] or object style notation ui.item.test_name1, for every value of i.
Also on a side note, you are redeclaring test_name using the var keyword. Declaring it once is fine and better for code readability. Only declare vars once.

Using foreach loop, how can we echo data with ob_start()

We have designed a Progress bar, using Jquery Ui. we need a program that can deliver data in numeric value.
That code is not working
PHP CODE
<?php
ob_start();
$array = array(10,20,30,40,50,60,70,80,90,100);
foreach($array as $a ){
echo $a;
sleep(1);
ob_end_clean();
}
echo 100 ;
?>
PHP code for echo a single item, it clears the existing data, so that our Ajax program can get the actual numeric data.
Thanks
You need to send a request to your php script with a parameter if you don't have an actual update:
$(function() {
$("#progressbar").progressbar({ value: 0 });
setTimeout(function(){ updateProgress(0); }, 500);
});
function updateProgress(data) {
$.get(url+'?progress='+data, function(data) {
// data contains whatever that page returns
if (data < 100) {
$("#progressbar").progressbar({value: parseInt(data)});
$("#progresstext").html("<p> Loading...<p>");
setTimeout(function(){ updateProgress(data); }, 500);
} else {
$("#progressbar").progressbar({value: 100});
}
});
}
and your PHP script:
<?php
echo (int)$_GET['progress']+10;
?>

Categories