I have written this code what it does is if user types postcode or city name it fetches from database using like query now the problem is i have around 1260 records with two fields one is city and other is post code
SELECT code, area FROM post_codes WHERE code LIKE '$q%' or area LIKE '$q%' ORDER BY area LIMIT 4
i have read many questions posted by users and researched online as well but nothing works used query delay as well .i have even indexed both these fields in database as well .. its getting records too slow that is the first problem now my second problem is when user is in that text field for search and he presses tab he can bypass the search and write any invalid code he wants how to restrict that here is my code for reference.
$("#Postcode").autocomplete("get_codes2.php", {
width: 260,
queryDelay:0,
dataType: 'json',
parse: function(data) {
var array = new Array();
for(var i=0;i<data.length;i++)
{
array[array.length] = { data: data[i], value: data[i].areacode, result: data[i].areacode};
}
return array;
},
formatItem: function(row) {
return row.areacode;
}
}).result(function (){
I think Drupal's API search has a really nice approach to solving this problem. Their alternative to letting every incremental search hit the backend is to serve one big JSON file, which is used to autocomplete on client side.
In their implementation they're listening on the focus event for the search input, to fetch the JSON only when it's actually needed.
Related
i am tying to build an application where user can reorder items (and save the order to database). The items user is reordering are navigation links, which are generated dynamically on the page from php loop:
$nav_links.='<li class="collection-item ui-state-default item" data-ord="'.$navorder.'" data-url="'.$pageurlname.'"><a>' .$pagename. '</a></li>';}
$navorder is order of the page in the navigation
$pageurlname is string which is used to call the page dynamically (index.php?page=$pageurlname) and is unique key in the table.
I am using jqueryUi sortable funcion to make the process drag & drop, it is working fine and each time i reorder the links, the new order is updated to "data-ord".. the sript:
$('#sortable').sortable({
stop: function(event, ui){
$(".sortable li").each(function(i, el){
$(el).attr('data-ord',$(el).index()+1);
});
}
});
Now to the problem, which is my ajax script:
$(document).on('click','.saveorder',function(){
var neworder = $('.collection-item').attr('data-ord');
var pgurl = $('.collection-item').attr('data-url');
$.ajax({
type:'POST',
dataType:'text',
url:'/rs/pages/nav_order.php',
data: { neworder:neworder, pgurl:pgurl },
success: function(data) {console.log(data); $('#response').html(data);},
error: function(data) {console.log('Error!', data); }
});
});
I am new to ajax, so it is mostly build on scripts i found in other quiestions here. (I was able to succesfully implement cript link this to my other functions) however it is not working in this case. The problem seems to be that i am trying to post multiple data for multiple rows (At this time i have 4 links i am trying to reorder, but the link count can be more or less). When i tried to get values of variables "neworder" and "pgurl" (using alert), it always show only the values for the first item.
I have tried lot of solutions found in similar quiestion but none of them worked, simply because user were posting form data and then serialized it, which is not my case because i am not sending data from the form.
Lastly here is the nav_order.php (i guess it is wrong here too, probably need to add foreach but at first i need to have the ajax working correctly):
<?php
include "/rs/include/db.php";
$neworder = $_POST['neworder'];
$pgurl = $_POST['pgurl'];
$query = mysqli_query($Connection, "UPDATE horus_pages SET nav_order='$neworder' WHERE url_name='$pgurl'") or die (mysqli_error($Connection));
echo 'Reordered';
?>
Also when i check the console, there is no data.
So please can you tell me how to correct the ajax script to send the data for each object and then handle it correctly in the php script? Hope i described my problem clearly. Thank you for any help.
Put data-id="your_database_id" in your links html. Selecting them in your database with href, will be slow and bug things if there are multiple records with the same href.
You have save button which sends the order and href of the first link it finds? And what happens when multiple items change their order? If you have many links, you will be throwing hundreds of mysql updates for each save?
You should be better off sending json to your php. Something like that:
[{id:123, order: 332}, {id:124, order:334}, ... ]
dataType:'text' becomes dataType:'json'
If you don't care about scalability, then this will work on the backend.
$data = file_get_contents("php://input");
$links = json_decode($data, true);
foreach($links as $link) {
$order = intval($link['order']);
$id = intval($link['id'])
// UPDATE table SET `order` = '$order' WHERE id = '$id'
}
Btw. Your php code allows SQL injection. Thats bad
Perhaps you can make the order 'float' and make an algorithm which finds empty spot. This will allow you to reduce these 100's of SQL requests to 1.
I am working on a project with PHP, Jquery, CodeIgniter. We have a database of products which is stored in a MySQL table.
We have a PHP page where the user can register a service request. The requirement is that if the user starts typing #product1 in the textbox, we should be able to link it to product1 in our database.
It is quite similar to the way facebook does it, but the requirement is that as soon as the user starts typing #, our page should be intelligent to guess the product and give the options. Like for e.g. if the user is typing #pro... the system should give him product1, product2 etc.
Please help. I can elaborate if I am not clear.
You can try using the jquery.mentionsInput plugin.
$('textarea.mention').mentionsInput({
onDataRequest:function (mode, query, callback) {
// here instead of having all data you can do an AJAX-request to your server
var data = [
{ id:1, name:'product1', avatar:'..', type: 'product' },
{ id:2, name:'product2', avatar:'..', type: 'product' },
];
data = _.filter(data, function(item) { return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 });
callback.call(this, data);
}
});
And then parse #[product1](product:1) on the php side
Hey I am working on Custom php project of directory listing. in listing page i need to add one autocomplete (for directory Keywords) with multiple selection and also accept new inserted keyword by User. Is there any body for reference..?
same autocomplete like this site as we insert new tags in stack.O.F
There are two parts needed:
Allowing multiple tags
Inserting unknown tags on-the-fly into the database.
Regarding the first part, you can use something like
$("#keywords").autocomplete({
source: function(request, response) {
$.getJSON( "search.php", {
term: request.term.split(/,\s*/).pop()
}, response );
},
search: function() {
var term = this.value.split(/,\s*/).pop();
if (term.length() < 2) {
return false;
}
}
});
For a more complete example, refer to https://jqueryui.com/autocomplete/#multiple-remote.
On the other hand, the second part cannot be done on the client side. Instead, you need to split the keyword list on the server side and check for each keyword, whether it is already known, creating it, if not.
Assuming you identify keywords using integer IDs in the database and you need to get the IDs for creating many-to-many relationships, you can perform that when you get the IDs from the database.
Hello stackoverflow developer,
First of all, sorry if I couldn't find a solution, but I've been trying for a while now.
I'm not sure if my approach is the best one, so, if there's an alternative to AJAX and/JSON, please feel free to suggest it.
I'm creating a tourist guide website where registered users will include their resorts, restaurants and tourist attractions according to region and state. I'm using Joomla! and Seblod for this (with some custom PHP, MySQL, Javascript and AJAX). Since I don't want to manually create 27 dynamic selects, I've been trying selecting the list of registered beaches (to which resorts and tourist attractions must be related to) with PHP/AJAX/JSON/JQuery.
Everything works except populating the beach list, and I don't know what the problem is. I've tried multiple ways to append, create or add the options but nothing happens.
The PHP/JSON result is :
`
[{"id":"17","title":"Porto+de+Galinhas"},{"id":"18","title":"Serrambi"},{"id":"19","title":"Tamandar%E9"}]
`
It's the result of this PHP script:
`
if($_GET['q'] == 'beaches'){
$praiaSQL = sprintf("SELECT * FROM vp_content AS c LEFT JOIN vp_cck_store_item_content AS v ON c.id = v.id WHERE c.catid = 10 AND v.cck = 'praia' AND v.venue_state = '%s' ORDER BY c.title ASC;", $_GET['s']);
$query = mysqli_query($connection, $praiaSQL);
$praia = array();
while($results = mysqli_fetch_assoc($query)){
array_push($praia, array('id' => $results['id'], 'title' => urlencode($results['title'])));
}
echo json_encode($praia);
}
`
I also need a solution to handle accented characters. I'm trying urlencode here and decode in the JQuery, but may be the problem. When I left it as the original data, when there were accented characters the result item was empty.
This is the relevant JQuery that handles the result (where x = the select and u = the URL to get the AJAX JSON result - I've commented where the problem is in the code):
`
function setBeachList(x,u){
var theDiv = "#cck1r_" + x;
var theSelect = "#" + x;
$j(theSelect).children("option:not(:first)").remove();
$j.ajax({
url: u,
contentType: "application/json;charset=UTF-8",
success: function(data){
if(data.length){
/****
This is where I'm stuck, as I can't find a way to make sure the
data is actually being treated/handled.
I've tried alerts and all sorts of other options to populate the
select.
I know it's being called because the before: and after: functions
are working.
*****/
/*
$j.each(data, function(k, v){
var o = new Option();
var newTitle = urldecode(v.title);
$j(o).html(newTitle).val(v.id);
$j(theSelect).append(o);
});
*/
var htm = '';
for (var i = 0; i '+urldecode(data[i].title)+'';
}
$j(theSelect).html(htm);
}
},
beforeSend: function(){
$j(theDiv).hide();
},
complete: function(){
$j(theDiv).show();
},
dataType: 'json',
});
}
`
Thank you for the time and patience, I'm not an expert at any of this (not exactly a newbie, but close...).
urldecode is not a javascript function,
you can use decodeURIComponent instead of it.
it's working when you change it,
http://jsfiddle.net/MzMPK/1/
UPDATE:
I think your problem is about trying to encode accented chars, It should work without encoding them, if your all encodings are set as UTF-8.
This is a common JSON parsing silent error.
If the JSON is not well formatted, the ajax request will fail silently.
The second most common cause of this problem is the encoding. Make sure you are using UTF-8 in the page you're calling the AJAX and on the script that returns the data.
Your problem with accented data can be resolved by not encoding the data on the server side, thus not needing to unenconde on the client side.
To answer my own question:
Since I'm not and AJAX/JSON expert, I don't know if it's the expected behavior, but the responding page, which generates the AJAX result, cannot have different data than the one expected. Since I had left a regions' output, the requesting page had problems dealing with it somehow. Once I removed the unnecessary data, the select list got updated fine.
That was something I forgot to mention in my post, because I assumed that it was fine to have more than one result in the page. Using Firebug to check the code, the request was being brought fine.
Thank you all for your time, and sorry for the inconvenience...
I had to add htmlentities to the responding page, as accents returned null, although I explicitly have UTF-8 on every file...
So I have a PHP backend that pulls some data from SQL, let's just say its a list of user ID numbers.
I want to be able to display that list in an html select, via jquery, after a button click.
In an attempt to partially answer my own question, I assume that I could either have a jquery function perform an ajax request, grab the data from PHP/SQL, and then somehow spit out the select with jquery. Or, I could perhaps do the SQL query via PHP right there on the page, and somehow have the jquery function grab the output from that and put it into a select.
How would you do it?
a fill-in-the-blanks code example follows:
idea 1:
function button_click() {
$.ajax({
url: "PHP_backend.php", // this does the sql query and returns the results
type: 'POST',
data: 'returnquery',
success: function(result) {
//????? put the result array or whatever into a submit, perhaps with a foreach or something similar..??
}
}); // end ajax
}
Or idea 2:
$result = mysql_query("SELECT userIDnumbers FROM users",$db);
while ($row = mysql_fetch_array($result)){
/// throw these results into an array or similar, $userIDarray[]
/// maybe I could have this PHP create hidden html fields for each row, and insert its value, and then get that via jquery
}
function button_click() {
/// create the html select, displaying the values from the sql query
/// get values from hidden html fields?
}
if you are sure that the button will be clicked always or very most of time, idea2 is better becouse overhead of send/receive Ajax (trafic) and its delay (time) will be removed
if the web page is "public" (not for an intranet, behind a vpn), I strongly advise to not use any sql in jquery. It's simplistic to call the php ajax response file with arbitrary sql (ie what I want), and even modify anything in the data or database.