How can i get looping autocomplete value - php

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.

Related

Wordpress ajax call is returing the html of the page

I am getting the data from the sql table and storing the results inside the associative array after that i have encoded into json but the problem is that it is returning the html of the page along with the results
this is my php code
<?php
add_action('wp_ajax_nopriv_my_loadmore','my_loadmore');
add_action('wp_ajax_my_loadmore','my_loadmore');
function my_loadmore(){
global $wpdb;
$table_name="wpnn_tweets";
$paged=$_POST['page'];
$page=$paged*10;
$results = $wpdb->get_results("SELECT * FROM $table_name LIMIT 1 OFFSET $page");
$arr = array();
foreach($results as $row){
$arr['userScreen']=$row->userScreen;
$arr['userName']=$row->userName;
$arr['tweetCreated']=$row->tweetCreated;
$arr['tweetText']=$row->tweetText;
$arr['tweetRetweetCt']=$row->tweetRetweetCt;
$arr['tweetFavoriteCt']=$row->tweetFavoriteCt;
}
echo json_encode($arr);
wp_die();
}
?>
this is how i am retrieving the json in the front end
$ = jQuery;
function scroller() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 200) {
$(this).off("scroll.ajax");
var page=parseInt($(this).data('page'));
var ajaxurl=$(this).data('url');
$.ajax({
url:ajaxurl,
type:"POST",
data:{
page:page,
action:"my_loadmore"
},
error:function(response){
console.log("error");
},
success:function(data){
for(i = 0; i < data.length; i++) {
console.log(data[i]);
}
}
});
}
}
$(window).on("scroll.ajax", scroller);
var ajaxurl = $(this).data('url');
This returns null unless you explicitly set it in your HTML. The easiest solution is to replace it with something like the following.
var ajaxurl = 'my-cool-endpoint';
This was not the solution to this particular problem, but I feel like it's a good thing to check for others coming to this page with the same problem. Replace wp_die() with die(). See the documentation for more details, but here is the relevant line.
A call to this function complements the die() PHP function. The difference is that HTML will be displayed to the user in the case of a typical web request.

Push Array Value to Ajax [JQuery / PHP / HTML]

I can't push the value of my array to my php file.
Script:
<script>
$(document).ready(function() {
var item_code = [];
$('#save').click(function() {
var item_name = [];
var item_value = [];
var item_quantity = [];
for (var i = 0; i < item_code.length; i++) {
item_code.push($(this).val());
}
$('.item_name').each(function() {
item_name.push($(this).val());
});
$('.item_value').each(function() {
item_value.push($(this).val());
});
$('.item_quantity').each(function() {
item_quantity.push($(this).val());
});
$.ajax({
url: "insert2.php",
method: "POST",
data: {
item_name: item_name,
item_code: item_code,
item_value: item_value,
item_quantity: item_quantity,
},
success: function(data) {
}
});
</script>
I have a value storing at "item_code" whenever I search the item code on my search bar. And after that, I want to push the value of item_code[] on the insert2.php.
I'm not getting any error, but the system itself is frozen.
I am guessing that "item_code" variable is also declared globally somewhere else in your code, otherwise there would be no point in iterating through it. Try using a different name instead of "item_code" to send it to "insert2.php".
for (var i = 0; i < item_code.length; i++) {
item_code.push($(this).val());
}
You can't push data into the same array that you are looping because you will never reach the end of it, unless the memory limit will tell you otherwise. Declare "item_code_second" and push into that:
$(document).ready(function() {
var item_code_second = [];
and change your loop:
for (var i = 0; i < item_code.length; i++) {
item_code_second.push($(this).val());
}
also you are pushing the same value "$(this).val()" as many times as there are values in item_code, which is not making any sense and the exact same value in name, quantity and value. $(this) represents the button that was pushed, don't forget you are in an on click event.

How to get array data passed by .post in jquery into php?

I have a problem regarding on how to get the value of the array variable passed by .post in jquery into my php page
this is my jquery code:
minDate = [];
hoursWork = [];
empId = [];
$('.minDate').each(function() {
minDate.push($(this).val());
});
$('.hoursWork').each(function() {
hoursWork.push($(this).val());
});
$('.empId').each(function() {
empId.push($(this).val());
});
$.post('rtInsert.php', { minDate: minDate, hoursWork: hoursWork, empId: empId }, function(data) {
alert(data);
});
How can I get the passed data in my rtInsert.php
i tried
$minDate = $_POST['minDate'];
$empId = $_POST['empId'];
$workHours = $_POST['hoursWork'];
now how will i get the individual value of the array because all the 3 variables is an array
All I know is a single array using foreach() but
what if there are 3 arrays passed
Is there any idea how I can get it or how can I passed into single array.
Thanks in Advance.
You can use the JSON.stringify(data); to turn them into JSON and prase it on the server side as this; $data = json_decode($json);.
Your code will then become this:
var minDate = [];
var hoursWork = [];
var empId = [];
$('.minDate').each(function() {
minDate.push($(this).val());
});
$('.hoursWork').each(function() {
hoursWork.push($(this).val());
});
$('.empId').each(function() {
empId.push($(this).val());
});
$.post('rtInsert.php', { minDate: JSON.stringify(minDate), hoursWork: JSON.stringify(hoursWork), empId: JSON.stringify(empId) }, function(data) {
alert(data);
});
And your server side ccode:
<?php
$mindate = json_decode($_POST['minDate']);
$hourswork = json_decode($_POST['hoursWork']);
$empid = json_decode($_POST['empId']);
foreach($mindate as $k=>$val)
{
$date = $val;
$work =$hourswork[$k];
$id =$empid[$k];
//...
}
?>

PHP/jquery autocomplete not loading JSON_ERROR_UTF8

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");

call two ajax function inside each other

i have an ajax call and it works good , when i call a new ajax call inside the old one , i got error in the first call
just one ajax call
$.getJSON("http://localhost/Mar7ba/Ontology/getRelatedConceptsAndRelations/"+conceptName+"/TRUE",function(data){
var concepts = data[0];
var relations = data[1];
for(var i = 0 ; i < concepts.length ; i++){
var IOS = '';
$("#ioAddRelatedConcepts").append('<p>\n\
connect to\n\
<span class="ioAddConcept">'+concepts[i]+'</span>\n\
with\n\
<span class="ioAddRelation">'+relations[i]+'</span>\n\
<select name ="concetedIOs[]" class="TypeSelector">\n\
'+IOS+'</select>\n\
<span class="errorMessage"></span>\n\
remove\n\
</p>\n\
<p>');
}
});
after adding this ajax call
$.getJSON("http://localhost/Mar7ba/Ontology/getRelatedConceptsAndRelations/"+conceptName+"/TRUE",function(data){
var concepts = data[0];
var relations = data[1];
for(var i = 0 ; i < concepts.length ; i++){
$.getJSON("http://localhost/Mar7ba/InformationObject/getIOsForConcept/"+concepts[i]+"/TRUE",function(data1){
var IOS = '';
$("#ioAddRelatedConcepts").append('<p>\n\
connect to\n\
<span class="ioAddConcept">'+concepts[i]+'</span>\n\
with\n\
<span class="ioAddRelation">'+relations[i]+'</span>\n\
<select name ="concetedIOs[]" class="TypeSelector">\n\
'+IOS+'</select>\n\
<span class="errorMessage"></span>\n\
remove\n\
</p>\n\
<p>');
});
}
});
after that , the concepts[i] and the relations[i] will be as undifined
and the data1.length always null
and the this is the second php code for ajax
public function getIOsForConcept($conceptName, $AJAX) {
if ($AJAX) {
$results = $this->model->getIOsForConcept($conceptName);
$IOs = array();
$i = 0;
while ($row = $results->fetch()) {
$IOs[$i] = $row['name'];
$i++;
}
return json_encode($IOs);
}
}
and i tried it and it works good
You can't use a loop variable ( i in your case) inside a callback function - it'll have whatever value it had when the loop terminated by the time your async callback function is invoked.
As you're already using jQuery, you might as well use $.each():
$.getJSON(..., function(data) {
var concepts = data[0];
var relations = data[1];
$.each(concepts, function(i, value) {
// concepts[i] is OK to use now, and is also in "value"
// relations[i] is OK to use too
$.getJSON(..., function() {
// you can still use them here, too!
});
});
});
which will ensure that i is correctly bound to the current iteration number each time.
The reason that concepts[i] and the relations[i] are undefined within the callback function of the inner $.getJSON() function is that $.getJSON() is aysnchronous which means that the entire for loop will have finished running before any of the callbacks occur on the inner $.getJSON() calls - so by the time these inner callbacks occur i is one higher than the maximum index of the concepts and relations arrays.
To get around this you can introduce an extra closure to keep the values from each iteration:
$.getJSON("http://localhost/Mar7ba/Ontology/getRelatedConceptsAndRelations/"+conceptName+"/TRUE", function(data){
var concepts = data[0];
var relations = data[1];
for(var i = 0 ; i < concepts.length ; i++){
(function(currentConcept, currentRelation) {
$.getJSON("http://localhost/Mar7ba/InformationObject/getIOsForConcept/"+currentConcept+"/TRUE" , function(data1){
var IOS = '';
$("#ioAddRelatedConcepts").append('<p>\n\
connect to\n\
<span class="ioAddConcept">'+ currentConcept +'</span>\n\
with\n\
<span class="ioAddRelation">'+ currentRelation +'</span>\n\
<select name ="concetedIOs[]" class="TypeSelector">\n\
'+IOS+'</select>\n\
<span class="errorMessage"></span>\n\
remove\n\
</p>\n\
<p>');
});
})(concepts[i], relations[i]);
}
});
The anonymous function I've added inside the for loop will run once per iteration creating separate closures each with their own currentConcept and currentRelation.
EDIT: To make it really obvious what I've changed compared to your original code--
Add the following line as the first thing inside your existing for loop:
(function(currentConcept, currentRelation) {
And then the following line as the last thing before your existing for loop's closing }:
})(concepts[i], relations[i]);
And then everywhere inside the for loop where you did have concepts[i] and relations[i] change them to currentConcept and currentRelation.

Categories