I am new to UI technologies like JQuery, AJAX, PHP etc.
I am building a Google Instant like feature. My search engine infrastructure at backend is pretty fast and returns results even for Tera Bytes of data in super quick time.
I have a PHP function in a class that returns me an array:
solrsearch.php
class SolrSearch{
...
...
public function find( $q ){
...
...
return $found;
}
}
$found is a key value pair something like documentID=>Data
When I dry run it i.e. on a console (not on a browser) with a test string and not using $q input variable everything seems to be fine and I print $found and it prints the values.
Now my html file with embedded javascript looks like this, so basically here I am capturing each key press on the textbox and doing a get request
testjson.html
<html>
...
<body>
<div align="center"><p><font size = 7 face="Verdana"> Search: <input type="text" id="term" size = 60 style="font-size:22pt"/>
<table id="results">
</table>
<script>
$(document).ready( function() {
$('#term').keyup( function() {
$.get('search_json.php?q='+escape($('#term').val()), function(data) {
html = '<table id="results">';
$.each( data, function( index, val ) {
html += '<tr><td class="document"><b>'+index.key+'</b> ';
html += 'Dated '+val.value+'</td></tr>';
} );
html += '</html>';
$('#results').replaceWith( html );
} );
} );
} );
</script>
...
...
</html>
And then finally here is my
search_json.php
$s = new SolrSearch();
print json_encode( $s->find( $_REQUEST['q'] ) );
Even the json encoded string is working perfectly fine and prints the json though on a console (not on browser)
Here is the problem I am facing: On the browser when I run testjson.html which just has a textBox and I input some strings so I dont get any results displayed back on the browser. When I debug it using Fiddler (HTTP Debugging Proxy) I can see AJAX get requests in that.
Any help would be appreciated. If there is anything else I can add to the question which is required I will be more than happy to do that.
EDIT:
I further debugged and printed $q in the find function in solrsearch.php and it did not print the value that means the value is not getting passed from search_json.php however I can see the GET requests on Fiddler.
I guess that this line:
html += '</html>';
should be
html += '</table>';
By the way, instead of using $('#results').replaceWith( html ); try with $('#results').html( html );
Edited:
Instead of $.get(), try with $.ajax():
$.ajax({
url: 'search_json.php',
type: 'POST',
data: { q: escape($('#term').val() },
}).done(function(resp) {
//Your html code with response options
});
If your front end uses HTML you definitely have to take a look on AJAX-SOLR
AJAX Solr is a JavaScript library for creating user interfaces to Apache Solr
Play with the demo site
Follow the tutorial
Browse the wiki
Read the documentation
Explore the code
Related
I am a new user of ajax; so...
I am using ajax on a simple html page to access a php script to receive data, calculate results using data in an mysql table, and echo results in a div on the same page. My javascript statement to do this is:
$.post('ajax/phpscript.php', {
postuser:theuser,
postname:uans1
}, function(data) {
$('#outputdiv1').html(data);
}
);
The php echo output goes to a div on the main page called outputdiv1.
I got that part; no problem. Not sure exactly how it works, but it does work.
I would also like to echo output to a different div (which I will call outputdiv2) on the same page, using the php script. In my php script, How do I refer to or echo output this other div?
I guess I could have a second $.post statement in the javascript code, accessing a second php script. But that would force me to access the mysql database a second time. Doesn't seem efficient to me.
Is there a better way to do this?
Thanks.
HTML code is here:
theuser is defined earlier
<table width=400 align=center><tr><td>
There is a question here, with 2 possible answers:<p>
<form>
<input type=radio style="width:22px; height:22px" name="ques1" id="opt1" value="answer 1" onclick="post1()"> answer 1<br>
<input type=radio style="width:22px; height:22px" name="ques1" id="opt2" value="answer 2" onclick="post1()"> answer 2<br>
</form>
<div id="outdiv1">first response from php will go here, beneath the question.<br></div>
<script type="text/javascript">
function post1() {
var uans1 = "none"
if (document.getElementById("opt2").checked) {
uans1 = "answer 2"
}
if (document.getElementById("opt1").checked) {
uans1 = "answer 1"
}
$.post('ajax/phpscript.php',{postuser:theuser,postname:uans1}, function(data) {$('#ans1div').html(data);});
}
</script>
</td>
<td width=20%>
<div id="outputdiv2">
second response from php will go here, to the right of the question.<p>
</div>
</td>
</tr></table>
first response will not be the same as the second response.
You could use JSON to communicate and return an array. something like this in js
$.ajax({
url: 'ajax/phpscript.php',
method: 'POST',
data: {
postuser: theuser,
postname: uans1
},
dataType: 'JSON'
}).done(function(data) {
if ($.isArray(data)) {
$('#outputdiv1').html(data[0]);
$('#outputdiv2').html(data[1]);
}
});
And your php script should do something look like this
<?php
include('dbconnection.php');
$result = [];
//SELECT data for div1 (part you already have)
$result[] = $mysql_result_as_html_for_outputdiv_1; // In your case this would be a html string
//SELECT other data for div2
$result[] = $mysql_result_as_html_for_outputdiv_2; // In your case this would be a html string
header('Content-Type: application/json');
echo json_encode($result);
?>
An even more clean solution would be to just return the data as objects from php and make some templates in js suitable for your data.
You need to understand this: who write in the div is javascript, not php, cause you are using ajax. Ajax is a way to comunicate with php, and give a response. Now you need to handle this response with javascript.
If you want to put the same content in outputdiv1 and outputdiv2, you not need to post ajax again, only write it in two divs.
$.post('ajax/phpscript.php',{postuser:theuser,postname:uans1}, function(data) {$('#outputdiv1').html(data);$('#outputdiv2').html(data);});
if you want different data i suggest you think the system to get all result that you need in one post request and return it in a json format (see http://php.net/manual/es/function.json-encode.php), so you can handle better with JSON.parse() in client side.
I am having a problem with setInterval in the $(document).ready(function(){}
What I am doing is setting the interval to do is call a PHP script that runs some MySQL queries to check the condition of 4 switches and then updating the screen with the values are in the database like so:
$(document).ready(function(){
setInterval(function(){
<?php require('fetchSwitchStatuses.php'); ?>
$("#switch1").css('background', 'rgb(<?php echo $switchColor1 ?>)');
$("#switch1").html('<?php echo $switchState1 ?>');
$("#switch2").css('background', 'rgb(<?php echo $switchColor2 ?>)');
$("#switch2").html('<?php echo $switchState2 ?>');
$("#switch3").css('background', 'rgb(<?php echo $switchColor3 ?>)');
$("#switch3").html('<?php echo $switchState3 ?>');
$("#switch4").css('background', 'rgb(<?php echo $switchColor4 ?>)');
$("#switch4").html('<?php echo $switchState4 ?>');
},1000);
});
Here is the code for fetchSwitchStatuses.php:
$connect = mysqli_connect("localhost", "root", "root");
mysqli_select_db($connect, "db_name");
$fetch1 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '3'"
);
$fetch2 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '5'"
);
$fetch3 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '6'"
);
$fetch4 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '9'"
);
$i = 1;
while($row = mysqli_fetch_array(${'fetch'.$i}))
{
if($row['SwitchStatus'] == 0)
{
${'switchColor'.$i} = "255, 0, 0";
${'switchState'.$i} = "OFF";
}
else if ($row['SwitchStatus'] == 1){
${'switchColor'.$i} = "0, 255, 0";
${'switchState'.$i} = "ON";
}
else {
${'switchColor'.$i} = "100, 100, 100";
${'switchState'.$i} = "ERROR";
}
$i++;
}
mysqli_close($connect);
When the page is loaded the information is correct, whatever is in the database is what is reflected by the colors on the screen.
When I click on the object to change the value, all of the necessary changes are made and the database is updated. However, the problem arises when the Interval is repeated. The values are switched back to whatever the original values were when the page was loaded. So, although the information is correctly changed in the database, for some reason the colors of the buttons is always reset to the first value read by the queries.
How can I fix this so that the information that is reflected on the screen is accurate?
With AJAX technology you can:
Send a request and get results from server by requesting a page (a .txt .js .html or even php).
So with AJAX you can get result of a page save something to database, get something from data base, you can work with sessions and anything you can do with a php file.
When you send an AJAX request to a see a page(i.e /userData.php?userId=5) the page /userData.php?userId=5 will be executed and its output will be returned.(HTML or just a word ‘yes’ or ‘no’ or ‘you can’t access to this user’s information’).
You can send data to file with POST or GET. But the question is how you can get data from page. Because the result AJAX will give you is what the requested page echoed to page like this
<html>
….
</html>
Or
‘Yes’
Or
<?php echo ‘something’; ?>
So what about getting a row of Date or lots of data? Because the only thing you are getting is a text or maybe a long text.
For that you can use JSON which Is something like nested arrays.
[
{
"term": "BACCHUS",
"part": "n.",
"definition": "A convenient deity invented by the...",
"quote": [
"Is public worship, then, a sin,",
"That for devotions paid to Bacchus",
"The lictors dare to run us in,",
"And resolutely thump and whack us?"
],
"author": "Jorace"
},
…
And this is a string too. But you can get Data in it with $.getJSON in jQuery and you can generate JSON data in server side like this.
<?php
$arr=array(
‘data’=>’ffff’,
‘anotherData’=>array(‘rrrrr’,’sssss’);
);
Echo json_encode($arr);
?>
Json_encode() in PHP gets an array and returns json string of it. And we echo it.
Now we can use jQuery to get Data which will be retrieved from server.
This section if from
Learning jQuery 1.3
Better Interaction Design and Web Development with Simple JavaScript Techniques
Jonathan Chaffer
Karl Swedberg
Global jQuery functions
To this point, all jQuery methods that we've used have been attached to a jQuery object that we've built with the $() factory function. The selectors have allowed us to specify a set of DOM nodes to work with, and the methods have operated on them in some way. This $.getJSON() function, however, is different. There is no logical DOM element to which it could apply; the resulting object has to be provided to the script, not injected into the page. For this reason, getJSON() is defined as a method of the global jQuery object (a single object called jQuery or $ defined once by the jQuery library), rather than of an individual jQuery object instance (the objects we create with the $() function).
If JavaScript had classes like other object-oriented languages, we'd call $.getJSON() a class method. For our purposes, we'll refer to this type of method as a global function; in effect, they are functions that use the jQuery namespace so as not to conflict with other function names.
To use this function, we pass it the file name as before:
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json');
return false;
});
});
This code has no apparent effect when we click the link. The function call loads the file, but we have not told JavaScript what to do with the resulting data. For this, we need to use a callback function.
The $.getJSON() function takes a second argument, which is a function to be called when the load is complete. As mentioned before, AJAX calls are asynchronous, and the callback provides a way to wait for the data to be transmitted rather than executing code right away. The callback function also takes an argument, which is filled with the resulting data. So, we can write:
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json', function(data) {
});
return false;
});
});
Here we are using an anonymous function as our callback, as has been common in our jQuery code for brevity. A named function could equally be provided as the callback.
Inside this function, we can use the data variable to traverse the data structure as necessary. We'll need to iterate over the top-level array, building the HTML for each item. We could do this with a standard for loop, but instead we'll introduce another of jQuery's useful global functions, $.each(). We saw its counterpart, the .each() method, in Chapter 5. Instead of operating on a jQuery object, this function takes an array or map as its first parameter and a callback function as its second. Each time through the loop, the current iteration index and the current item in the array or map are passed as two parameters to the callback function.
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json', function(data) {
$('#dictionary').empty();
$.each(data, function(entryIndex, entry) {
var html = '<div class="entry">';
html += '<h3 class="term">' + entry['term'] + '</h3>';
html += '<div class="part">' + entry['part'] + '</div>';
html += '<div class="definition">';
html += entry['definition'];
html += '</div>';
html += '</div>';
$('#dictionary').append(html);
});
});
return false;
});
});
Before the loop, we empty out so that we can fill it with our newly-constructed HTML. Then we use $.each() to examine each item in turn, building an HTML structure using the contents of the entry map. Finally, we turn this HTML into a DOM tree by appending it to the .
This approach presumes that the data is safe for HTML consumption; it should not contain any stray < characters, for example.
I have an AJAX request that can have two possible outcomes:
The server responds with a message which I should place in a <div>
The server responds with an HTML page, in this case I need to substitute current page with a new one and change the address (the client knows the address before a request).
What would be the solution if I have the AJAX request that needs to handle both of these cases?
url = "http://example.com"
ajax.request(callback)
function callback(response) {
if (case2(response)) {
history.pushState({}, "New page", url);
document.innerHTML = response
} else {
updateDiv(response)
}
}
I'm interested in a correct way to implement the first branch, or if the server can somehow compose a headers that will make browser to handle a response as a usual HTTP response and update a page location and content, something like redirect with given content.
I understand that the server can return a link instead of a page, but in this case one additional stage will be needed on a client - redirect and then populating the new page on the server.
Quite frankly, I think that approach is basically broken by design. You shouldn't have to make that decision at that place. For example, the ajax response could only signal that a whole new page should be loaded and the new content then be generated on a second (non-ajax) request to a new URL.
In case you're forced to take the way you already go, and provided the response content is not very large, you could try Javascript-URIs. Basically, an URI in the form of javascript:"string" will load a new page which that string is the source code for. So, if response already is a string, just assigning javascript:response to window.location.href should suffice. Maybe you have to do some escaping beforehand. And I don't know, how cross-browser-compatible this approach is.
load
is also possible.
A variant of this is building the URL not with the variable name, but with the actual string data. Like
function source2url(src) {
// make valid javascript string from source text
var esc1 = src
.replace(/\\/g, '\\\\')
.replace(/\'/g, '\\\'')
.replace(/\x0A/g, '\\x0A')
.replace(/\x0D/g, '\\x0D');
// make valid url from that
return "javascript:'" + encodeURIComponent(esc1) + "'";
}
window.location.href = source2url(response);
This will, of course, generate pretty large URIs. And you'll always have the Javascript-URI in the address bar.
UPDATE
A similar approach is to use base64 encoding in a data URI. The Wikipedia entry explains how it works, including a javascript example. However, you'd have to base64-encode the content somehow. (Note: You can use data URIs with or without the base64 encoding. You have to see what gives you shorter URIs for your specific content.)
I had a similar issue once. A full error page was returned instead of a simple HTML snippet. We eventually fixed this by changing the logic, but here is one of the solutions I found:
document.open();
document.write(responseText);
document.close();
The reason we abandoned this is that on IE there were some problems. I didn't loose any time to investigate why, but it threw an 'Access denied' exception when attempting to write the string. I think there were some <meta> tags that confused IE, or maybe conditional comments, I'm not sure. (It worked when I used some simple pages...)
Bottom line is: you shouldn't have to do this, but if there is nothing else you can do (like returning an url string) the code above might work.
It's really easy if the response is valid XML.
var new_doc = (new DOMParser).parseFromString(response, "application/xml");
document.replaceChild(document.adoptNode(new_doc.doctype), document.doctype);
document.replaceChild(document.adoptNode(new_doc.documentElement), document.documentElement);
Since the request is for an updated answer, here's my solution using HTML5's History API with jQuery. It should run easily by combining the PHP and HTML parts into one file.
My solution allows for AJAX to return the following:
A message through AJAX, which updates a <div> container.
A URL, which causes the browser to redirect to the URL
A complete HTML page, which calls the History API's history.pushState() to add the current URL to the browser's history and replaces the entire HTML on the page with the HTML returned from AJAX.
PHP
This is just a sample of what the PHP script will need to return when it is invoked via AJAX. It shows how to encode flags to determine whether the AJAX call should update the container or load a new page, and how to return its result via JSON through json_encode. For completeness, I named this script test.php.
<?php
// Random messages to return
$messages = array(
'Stack Overflow',
'Error Message',
'Testing'
);
// If the page was requested via AJAX
if( isset( $_POST['ajax']))
{
$response = array(
'redirect' => // Flag to redirect
( rand() % 2 == 0) ? true : false,
'load_html' => // Flag to load HTML or do URL redirect
( rand() % 2 == 0) ? true : false,
'html' => // Returned HTML
'<html><head><title>AJAX Loaded Title</title></head><body>It works!</body></html>',
'title' => 'History API previous title',
'message' => // Random message
$messages[ (rand() % count( $messages)) ]
);
echo json_encode( $response);
exit;
}
JS
Since I am using jQuery, lets start with that. The following submits an AJAX POST to the server, to the above PHP script at URL test.php. Note that it also sets the POST parameter ajax to be true, enabling the PHP script to detect that it received an AJAX request. The dataType field tells jQuery that the server's response will be in JSON, and that it should decode that JSON to a JSON object in the response callback. Finally, the success callback, which is fired when the AJAX response is successfully received, determines what to do based on the flags sent from the server.
$.ajax({
type: 'POST',
url: "/test.php",
data: {ajax : true},
dataType: "json",
success: function( json) {
if( json.redirect) {
if( json.load_html) {
// If the History API is available
if( !(typeof history.pushState === 'undefined')) {
history.pushState(
{ url: redirect_url, title: document.title},
document.title, // Can also use json.title to set previous page title on server
redirect_url
);
}
// Output the HTML
document.open();
document.write( json.html);
document.close();
}
else {
window.location = redirect_url;
}
}
else {
$('#message').html( json.message);
}
},
});
HTML
Here is the complete HTML source of my tested file. I tested it in FF4 - FF8. Note that jQuery provides the ready method to prevent the JS from executing until the DOM is loaded. I've also used Google's hosting of jQuery, so you do not need to upload a copy of jQuery to your server to test this.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
<title>Default Page</title>
<script type="text/javascript"">
$( document).ready( function() {
$('#ajax_link').click( function() {
var redirect_url = "/test.php";
$.ajax({
type: 'POST',
url: "/test.php",
data: {ajax : true},
dataType: "json",
success: function( json) {
if( json.redirect) {
if( json.load_html) {
// If the History API is available
if( !(typeof history.pushState === 'undefined')) {
history.pushState(
{ url: redirect_url, title: document.title},
document.title, // Can also use json.title to set previous page title on server
redirect_url
);
}
document.open();
document.write( json.html);
document.close();
}
else {
window.location = redirect_url;
}
}
else {
$('#message').html( json.message);
}
},
});
})
});
</script>
</head>
<body>
<div id="message">The default contents of the message</div>
<a id="ajax_link" href="#">Fire AJAX</a>
</body>
</html>
Give an id to body <body id="page"> and your other div will be <div id="message"></div> now your ajax will look like
$.ajax({
url:'myAjax.php',
data:{datakey:datavalue},
dataType:"JSON",
success: function (response) {
if(response.message=="your message")
{
$('#message').html(response.content);
}
else
{
$('#page').html(response.content);
}
}
});
as T-Bull say... the whole process is wrong here....
you simply are over-complicating things and you know that infact:
I understand that the server can return a link instead of a page, but
in this case one additional stage will be needed on a client -
redirect and then populating the new page on the server.
stop complicating and start do it well...
Client open the page first time, so, track it $_SESSION['tmp_client_id'] = 'client_'.session_id(); obviously is better if the client is already subscribed, anyway, put stuff in temp table OR into another session var etc...
Client fill in the form;
Client submit the form;
Make the AJAX request;
Store $_POST variable inside tmp_client_tbl with it's unique tmp_client_id OR just $_SESSION['client_'.session_id()] = json_encode($_POST);
Outcome #1 ? display message in a </div>
Outcome #2 ? refresh page and check if( isset($_SESSION['client_'.session_id()])) { if so let's display the form again with filled fields: } else { display empty form;
SELECT * FROM tmp_client_tbl WHERE tmp_client_id = '{$_SESSION['tmp_client_id']}' OR json_decode($_SESSION['client_'.session_id()]);
$form_data = $mysql_rows; OR $json_array;
foreach($form_data as $name => $value) { echo "<input name='$name' value='$value' />" } in a ninja way that assume you have such kind of form builder array where $form = array('text' => array('name','lastname'), 'select' => array('countries'), ... ), OR simply by <input name='lastname' value='{$lastname}' /> where the fields values are pre-polutated with empty vars;
time elapsed, error occurred, browser closed? session_destroy(); or unset($_SESSION['client_'.session_id()]);
I have this:
<div ><span id="compareResult"></span> <span id="result"></span></div>
$.get(
'data.php',
{ valA: $(this,'option:selected').val() , valB:$(this,'option:selected').val()},
function(childData){
$('#result').html(childData).css('display', 'none')});>
PHP:
function getData($names,$id,$flag){
if($flag==0){
$strResult = '<select multiple class="sel" id="selectname" size='.count($names).'>';
}
if($flag==1){
$strResult = '<select multiple class="sel" id="selname" size='.count($names).'>';
}
for($i=0; $i<count($names); $i++)
{
$strResult.= '<option value='.$id[$i].'>'.$names[$i].'</option>';
}
echo $strResult.= '</select>';}
How do I break apart/parse the response inside .html(childData) so I can put it in different span(i.e. id="compareResult")?
Thanks in advance.
This doesn't directly answer your question, but it answers what I think the real question might be.
If the data is coming from your own server, I strongly recommend you look at the jQuery Taconite plugin. It makes child's play of doing multiple-element updates via AJAX. All you have to do is make a slight change to the format of how the data is delivered to the browser.
Seriously, check it out.
After you make the html call to update #result's HTML, you will be able to access anything that was inserted inside #result in subsequent calls.
For example:
$.get(
'data.php',
{ valA: $(this,'option:selected').val() , valB:$(this,'option:selected').val()},
function(childData){
$('#result').html(childData).css('display', 'none');
$('#result #someContainer').appendTo('#compareResult');
}
);
I responded to a similar question recently, but you can actually grab any information you might need from the HTML response by creating a jQuery object of the response. For example:
var response = $("<div>This is my element <span class='a-thing'>Thing</span></div>");
alert(response.find('.a-thing').text());
In your callback, you could do the same thing:
$.get(
'data.php',
{ valA: $(this,'option:selected').val() , valB:$(this,'option:selected').val()},
function(childData){
var result = $(childData);
alert(result.find('.some-selector').text());
}
});
I'm trying to build a form where certain text fields and text areas have autocomplete.
I've used the formidable plugin for wordpress to build my form. I'm using the jQuery autocomplete plugin for the autocomplete part.
The code looks like this:
<script>
$(document).ready(function(){
var data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" ");
$("#example").autocomplete(data);
});
</script>
So basically I need to use php to pull data from the mysql database and feed it to that data var. I'm a php newbie, so I'm not sure how to do this. A coder who works on the formidable plugin suggested the following code for the var data part:
<?php
global $frm_entry_meta;
$entries = $frm_entry_meta->get_entry_metas_for_field($field_id, $order='');
?> //db_frm_entry_metas is the name of the mysql db that stores the values for every field from the form. I suspect get_entry_metas_for_field is a function added by the formidable plugin. $field_id is the id for a given field on the form.
var data = new Array();
<?php foreach($entries as $value){ ?>
data[] = <?php echo $value ?>;
<?php } ?>
I tried to run this code with an id number in the place of $field_id, but it didn't work. I'm stuck here.
I can understand most of the code, except for this part:
var data = new Array();
<?php foreach($entries as $value){ ?>
data[] = <?php echo $value ?>
I don't get what the data[] is doing there... should the php be feeding the data to the var data= line?
I have around 15 form text/textarea fields, each of which needs to pull data associated with its given field_id. Unless there's an easier way to do this, this means I'll have to write 15 scripts, each with a particular $field_id and jQuery object with field's css selector.
Any help getting this to work would be much appreciated!
The coder is wrong, this:
data[] = something;
will cause a syntax-error in JS, it's a PHP-shorthand for pushing members to an array and doesn't work in JS.
Try this:
data.push(unescape('<?php echo rawurlencode($value); ?>');
According to the autocomplete docs, you can pass a url as the data parameter. That being said, do something such as the following:
<?php
// --- PLACE AT VERY TOP OF THE SAME FILE ---
$search = isset($_GET['q']) && !empty($_GET['q']) ? $_GET['q'] : null;
if (!is_null($search))
{
$matches = Array();
// some search that populates $matches based on what the value of $search is
echo implode("\r\n",$matches);
exit;
}
?>
then, in your jQuery code replace the .autocomplete(data) with .autocomplete('<?php echo $_SERVER['PHP_SELF']; ?>');
your jquery will be something like this
$("#example").change(function(){
$.ajax(
{
type: "POST",
url: "php_page.php",
data: "data=" + $("#example").val(),
beforeSend: function() {
// any message or alert you want to show before triggering php_page.php
},
success: function(response) {
eval(response);
// print your results
}
});
});
in your php page after getting all info echo the results like this.
echo "var result=" . json_encode($results);
then eval(response) jquery function will give you javascript variable result with your results in it.
Hope this helps...