0

Using this commadelimited autocomplete I have created a php file to get some values from my MySQL database the created php script is follows

<?php
$connection = mysql_connect("my_host", "usr", "pwd"); // Establishing connection with server..
$db = mysql_select_db("appdb", $connection); 
$wid =$_POST['wid1'];
$result = mysql_query("select * from shop where wid=$wid");
$to_encode = array();
$data = mysql_num_rows($result);
if ($data > 0){
    while($row = mysql_fetch_assoc($result)) {
  $to_encode[] = $row;
}
echo json_encode($to_encode);
}
else{
    echo "No Shops Available, Contact Your Wholesaler !!";
}
mysql_close ($connection); // Connection Closed.
?>

and I have created a function in JavaScript to fetch values into a variable

$.post("http://theurl.com/app/get_shopname.php",{ wid1:10},
function(shopnames){
if(shopnames=='No Shops Available, Contact Your Wholesaler !!'){
$('input[type="text"],input[type="searchField"]').css({"border":"2px solid red","box-shadow":"0 0 3px red"});
alert(shopnames);
}else{

var availableTags = shopnames;
}
    }


    );

$("#searchField").autocomplete({
    target: $('#suggestions'),
    source: availableTags,
    link: 'target.html?term=',
    minLength: 1
});

The problem is, it doesn't enters inside function(shopnames) function when hit $.post("http://theurl.com/app/get_shopname.php" .. it simply passing to the next function

mplungjan
  • 169,008
  • 28
  • 173
  • 236
rimboche
  • 87
  • 1
  • 12
  • 1
    I would really recommend you to not use `mysql_*` functions as the are deprecated, and would be removed in the future. – Ikari Aug 06 '15 at 09:39
  • Here is an SO question about it: http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php – Albzi Aug 06 '15 at 09:41
  • 1
    Any console messages? – mplungjan Aug 06 '15 at 09:42
  • @mplungjan unfortunately NO – rimboche Aug 06 '15 at 09:44
  • http://api.jquery.com/jquery.post/ add a fail function to find out why – Steve Aug 06 '15 at 09:44
  • 1) `var avaiableTags` makes the var only available in the function you call it (scope) 2) it will not be available ANYWAY until after the post has returned so the .autocomplete assignment must be in the success of the post. – mplungjan Aug 06 '15 at 09:45
  • Try `$.post(....).fail(function(jqXHR, textStatus, errorThrown) { console.log(jqXHR, textStatus, errorThrown); })` and see if you get error details. – artm Aug 06 '15 at 09:45
  • @mplungjan Am using this - https://github.com/commadelimited/autoComplete.js/blob/master/readme.md – rimboche Aug 06 '15 at 09:53
  • @mplungjan So How can I pass the Id along with `get_shopname.php` ?? – rimboche Aug 06 '15 at 10:02
  • @mplungjan the return format is like this `[{"wid":"10","shopname":"ABC Medical shop"},{"wid":"10","shopname":"ZYX Drugs shop"}]` – rimboche Aug 06 '15 at 10:04
  • I read the documentation and looked at the network tab on the example: `...?method=search&returnformat=json&data=simple&term=XXX` so 1) change your PHP to use `$_POST["term"]` instead of wid, clean the term var and change to `"select * from shop where shopname LIKE '%".$term."%'"` and return the answer as `[{"value":"10","label":"ABC Medical shop"},{"value":"20","label":"ZYX Drugs shop"}]` – mplungjan Aug 06 '15 at 11:28
  • @mplungjan Actually my scenario is before showing this search box there is a login page when a user successfully logged in the search box source should be fill with shopname(note: here the shop names to be shown are retrieved by using `wid` this id taken when user logon ) – rimboche Aug 07 '15 at 05:12
  • Then your Ajax call needs to transform the JSON into the simple array used and THEN do the `$("#searchField").autocomplete({..` – mplungjan Aug 07 '15 at 05:44
  • @mplungjan I need to get shop id along with a shop name because Need to use another database task when a user select a particular shop name using the selected shop name's id – rimboche Aug 07 '15 at 05:56
  • Please update your question with what should be searchable, ID or shopname? Also please explain again: All the shops are loaded into the page when the user starts? What is WID then? Will ONE wid return many shops? – mplungjan Aug 07 '15 at 06:29
  • Also check that you are getting the expected JSON (with the appropriate mime type) from the server when you just use the URL of `http://theurl.com/app/get_shopname.php?wid1=10` after changing the PHP to use $_GET for testing reasons. It seems to me you also miss `header("Content-type: application/json");` – mplungjan Aug 07 '15 at 06:30
  • @mplungjan _what should be searchable, ID or shopname?_ > Shopname , _All the shops are loaded into the page when the user starts?_ > Yes,(fetch shop name form database with `WID` of the logged in user,here `WID` will take from user table) , _What is WID then?_ > its the id present in user table and shop table to identify which shops are available for a user(source for fill the autocomplete) , _Will ONE wid return many shops?_ Yes – rimboche Aug 07 '15 at 06:35

2 Answers2

1
  1. Change the $_POST to $_GET for testing
  2. Load the URL http://theurl.com/app/get_shopname.php?wid1=10 in the browser and see it returns proper JSON
  3. Change back to $_POST and add header("Content-type: application/json"); somewhere before the echo
  4. Make sure you do not call the autocomplete event handler until you have the data

Something like this:

$(function) { // when page loads 
  var wid = "<?PHP echo $wid; ?>"; // for example
  $.post("http://theurl.com/app/get_shopname.php", { wid1: wid },
    function(shopnames) {
      if (shopnames == 'No Shops Available, Contact Your Wholesaler !!') {
        $('input[type="text"],input[type="searchField"]').css({
          "border": "2px solid red",
          "box-shadow": "0 0 3px red"
        });
      } else {
        var availableTags = [];
        $(shopnames).each(function(i,tag) {
          availableTags.push(tag.shopname);
        });
        $("#searchField").autocomplete({
          target: $('#suggestions'),
          source: availableTags,
          link: 'target.html?term=',
          minLength: 1
        });
    });
});
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

I'd open the Network tab in the browser dev tools to see if there wasn't an error code for the ajax request result. That would make the callback to be skipped. It only gets fired if the request was successful (code 200).

John Smith
  • 1,559
  • 1
  • 12
  • 18