I am trying to call a PHP function from an external PHP file into a JavaScript script. My code is different and large, so I am writing a sample code here.
This is my PHP code:
<?php
function add($a,$b){
$c=$a+$b;
return $c;
}
function mult($a,$b){
$c=$a*$b;
return $c;
}
function divide($a,$b){
$c=$a/$b;
return $c;
}
?>
This is my JavaScript code:
<script>
var phpadd= add(1,2); //call the php add function
var phpmult= mult(1,2); //call the php mult function
var phpdivide= divide(1,2); //call the php divide function
</script>
So this is what I want to do.
My original PHP file doesn't include these mathematical functions but the idea is same.
If some how it doesn't have a proper solution, then may you please suggest an alternative, but it should call values from external PHP.
Yes, you can do ajax request to server with your data in request parameters, like this (very simple):
Note that the following code uses jQuery
jQuery.ajax({
type: "POST",
url: 'your_functions_address.php',
dataType: 'json',
data: {functionname: 'add', arguments: [1, 2]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
and your_functions_address.php like this:
<?php
header('Content-Type: application/json');
$aResult = array();
if( !isset($_POST['functionname']) ) { $aResult['error'] = 'No function name!'; }
if( !isset($_POST['arguments']) ) { $aResult['error'] = 'No function arguments!'; }
if( !isset($aResult['error']) ) {
switch($_POST['functionname']) {
case 'add':
if( !is_array($_POST['arguments']) || (count($_POST['arguments']) < 2) ) {
$aResult['error'] = 'Error in arguments!';
}
else {
$aResult['result'] = add(floatval($_POST['arguments'][0]), floatval($_POST['arguments'][1]));
}
break;
default:
$aResult['error'] = 'Not found function '.$_POST['functionname'].'!';
break;
}
}
echo json_encode($aResult);
?>
Try This
<script>
var phpadd= <?php echo add(1,2);?> //call the php add function
var phpmult= <?php echo mult(1,2);?> //call the php mult function
var phpdivide= <?php echo divide(1,2);?> //call the php divide function
</script>
use document.write
for example,
<script>
document.write(' <?php add(1,2); ?> ');
document.write(' <?php milt(1,2); ?> ');
document.write(' <?php divide(1,2); ?> ');
</script>
You need to create an API :
Your js functions execute AJAX requests on your web service
var mult = function(arg1, arg2)
$.ajax({
url: "webservice.php?action=mult&arg1="+arg1+"&arg2="+arg2
}).done(function(data) {
console.log(data);
});
}
on the php side, you'll have to check the action parameter in order to execute the propre function (basically a switch statement on the $_GET["action"] variable)
index.php
<body>
...
<input id="Div7" name="Txt_Nombre" maxlenght="100px" placeholder="Nombre" />
<input id="Div8" name="Txt_Correo" maxlenght="100px" placeholder="Correo" />
<textarea id="Div9" name="Txt_Pregunta" placeholder="Pregunta" /></textarea>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$(".Txt_Enviar").click(function() { EnviarCorreo(); });
});
function EnviarCorreo()
{
jQuery.ajax({
type: "POST",
url: 'servicios.php',
data: {functionname: 'enviaCorreo', arguments: [$(".Txt_Nombre").val(), $(".Txt_Correo").val(), $(".Txt_Pregunta").val()]},
success:function(data) {
alert(data);
}
});
}
</script>
servicios.php
<?php
include ("correo.php");
$nombre = $_POST["Txt_Nombre"];
$correo = $_POST["Txt_Corro"];
$pregunta = $_POST["Txt_Pregunta"];
switch($_POST["functionname"]){
case 'enviaCorreo':
EnviaCorreoDesdeWeb($nombre, $correo, $pregunta);
break;
}
?>
correo.php
<?php
function EnviaCorreoDesdeWeb($nombre, $correo, $pregunta)
{
...
}
?>
This work perfectly for me:
To call a PHP function (with parameters too) you can, like a lot of people said, send a parameter opening the PHP file and from there check the value of the parameter to call the function. But you can also do that lot of people say it's impossible: directly call the proper PHP function, without adding code to the PHP file.
I found a way:
This for JavaScript:
function callPHP(expression, objs, afterHandler) {
expression = expression.trim();
var si = expression.indexOf("(");
if (si == -1)
expression += "()";
else if (Object.keys(objs).length > 0) {
var sfrom = expression.substring(si + 1);
var se = sfrom.indexOf(")");
var result = sfrom.substring(0, se).trim();
if (result.length > 0) {
var params = result.split(",");
var theend = expression.substring(expression.length - sfrom.length + se);
expression = expression.substring(0, si + 1);
for (var i = 0; i < params.length; i++) {
var param = params[i].trim();
if (param in objs) {
var value = objs[param];
if (typeof value == "string")
value = "'" + value + "'";
if (typeof value != "undefined")
expression += value + ",";
}
}
expression = expression.substring(0, expression.length - 1) + theend;
}
}
var doc = document.location;
var phpFile = "URL of your PHP file";
var php =
"$docl = str_replace('/', '\\\\', '" + doc + "'); $absUrl = str_replace($docl, $_SERVER['DOCUMENT_ROOT'], str_replace('/', '\\\\', '" + phpFile + "'));" +
"$fileName = basename($absUrl);$folder = substr($absUrl, 0, strlen($absUrl) - strlen($fileName));" +
"set_include_path($folder);include $fileName;" + expression + ";";
var url = doc + "/phpCompiler.php" + "?code=" + encodeURIComponent(php);
$.ajax({
type: 'GET',
url: url,
complete: function(resp){
var response = resp.responseText;
afterHandler(response);
}
});
}
This for a PHP file which isn't your PHP file, but another, which path is written in url variable of JS function callPHP , and it's required to evaluate PHP code. This file is called 'phpCompiler.php' and it's in the root directory of your website:
<?php
$code = urldecode($_REQUEST['code']);
$lines = explode(";", $code);
foreach($lines as $line)
eval(trim($line, " ") . ";");
?>
So, your PHP code remain equals except return values, which will be echoed:
<?php
function add($a,$b){
$c=$a+$b;
echo $c;
}
function mult($a,$b){
$c=$a*$b;
echo $c;
}
function divide($a,$b){
$c=$a/$b;
echo $c;
}
?>
I suggest you to remember that jQuery is required:
Download it from Google CDN:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
or from Microsoft CDN: "I prefer Google! :)"
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
Better is to download the file from one of two CDNs and put it as local file, so the startup loading of your website's faster!The choice is to you!
Now you finished! I just tell you how to use callPHP function. This is the JavaScript to call PHP:
//Names of parameters are custom, they haven't to be equals of these of the PHP file.
//These fake names are required to assign value to the parameters in PHP
//using an hash table.
callPHP("add(num1, num2)", {
'num1' : 1,
'num2' : 2
},
function(output) {
alert(output); //This to display the output of the PHP file.
});
If you actually want to send data to a php script for example you can do this:
The php:
<?php
$a = $_REQUEST['a'];
$b = $_REQUEST['b']; //totally sanitized
echo $a + $b;
?>
Js (using jquery):
$.post("/path/to/above.php", {a: something, b: something}, function(data){
$('#somediv').html(data);
});
Void Function
<?php
function printMessage() {
echo "Hello World!";
}
?>
<script>
document.write("<?php printMessage() ?>");
</script>
Value Returning Function
<?php
function getMessage() {
return "Hello World!";
}
?>
<script>
var text = "<?php echo getMessage() ?>";
</script>
I wrote some script for me its working .. I hope it may useful to you
<?php
if(#$_POST['add'])
{
function add()
{
$a="You clicked on add fun";
echo $a;
}
add();
}
else if (#$_POST['sub'])
{
function sub()
{
$a="You clicked on sub funn";
echo $a;
}
sub();
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<input type="submit" name="add" Value="Call Add fun">
<input type="submit" name="sub" Value="Call Sub funn">
<?php echo #$a; ?>
</form>
Try looking at CASSIS. The idea is to mix PHP with JS so both can work on client and server side.
I created this library JS PHP Import which you can download from github, and use whenever and wherever you want.
The library allows importing php functions and class methods into javascript browser environment thus they can be accessed as javascript functions and methods by using their actual names. The code uses javascript promises so you can chain functions returns.
I hope it may useful to you.
Example:
<script>
$scandir(PATH_TO_FOLDER).then(function(result) {
resultObj.html(result.join('<br>'));
});
$system('ls -l').then(function(result) {
resultObj.append(result);
});
$str_replace(' ').then(function(result) {
resultObj.append(result);
});
// Chaining functions
$testfn(34, 56).exec(function(result) { // first call
return $testfn(34, result); // second call with the result of the first call as a parameter
}).exec(function(result) {
resultObj.append('result: ' + result + '<br><br>');
});
</script>
I made a version only using js, without using any dependencies. I think this is the shorest solution but probably not the best one since it doens't check for any errors.
javascript
var a = 1;
var b = 2;
function add(){
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "YOUR_SERVER/function.php?a="+a+"&b="+b, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
var c = add(a, b)
function.php file
<?php echo $_GET["a"] + $_GET["b"]?>
c = 3
I created this library, may be of help to you.
MyPHP client and server side library
Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- include MyPHP.js -->
<script src="MyPHP.js"></script>
<!-- use MyPHP class -->
<script>
const php = new MyPHP;
php.auth = 'hashed-key';
// call a php class
const phpClass = php.fromClass('Authentication' or 'Moorexa\\Authentication', <pass aguments for constructor here>);
// call a method in that class
phpClass.method('login', <arguments>);
// you can keep chaining here...
// finally let's call this class
php.call(phpClass).then((response)=>{
// returns a promise.
});
// calling a function is quite simple also
php.call('say_hello', <arguments>).then((response)=>{
// returns a promise
});
// if your response has a script tag and you need to update your dom call just call
php.html(response);
</script>
</body>
</html>
I have a PHP code, where I need to make some manipulations with JS, and I tried the following
<?php
include './parse.service.php';
echo putContent();
$jsScript = "
<script type='text/javascript'>
const json = require('./transacitions.json');
window.onload = modifyData;
function modifyData() {
document.getElementById('n_transactions').innerHTML = parseInt(document.getElementById('n_transactions').innerHTML, 10) + json.data.length;
document.getElementById('total_received').getElementsByTagName('font')[0].getElementsByTagName('span')[0].innerHTML = `${this.totalReceived(convertToFloat(document.getElementById('total_received').getElementsByTagName('font')[0].getElementsByTagName('span')[0].innerHTML))} BTC`;
document.getElementById('final_balance').getElementsByTagName('font')[0].getElementsByTagName('span')[0].innerHTML = `${this.finalBalance(convertToFloat(document.getElementById('final_balance').getElementsByTagName('font')[0].getElementsByTagName('span')[0].innerHTML))} BTC`;
}
function convertToFloat(element) {
var numb = element.match(/[+-]?\d+(\.\d+)?/g);
numb = numb.join(\"\");
return (parseFloat(numb, 10));
}
function totalReceived(quantity) {
json.data.forEach(element => {
if (element.finalSum > 0) {
quantity += element.finalSum;
};
});
return quantity;
};
function finalBalance(quantity) {
json.data.forEach(element => {
quantity += element.finalSum;
});
return quantity;
};
</script>";
echo $jsScript;
?>
And when I echo the created "script", i get the message similar to this Uncaught Error: Call to undefined function totalReceived() how shall I modify the code, in sucha a way that JS will integrate normally in my PHP script.
$ has special meaning inside PHP strings delimited with " characters, so ${this.totalReceived is causing the PHP engine to try to find an execute a function called totalReceived.
There's no apparent reason to use a PHP string here anyway. Just exit PHP mode and just output the code directly.
<?php
include './parse.service.php';
echo putContent();
?>
<script type='text/javascript'>
const json = require('./transacitions.json');
window.onload = modifyData;
// etc etc
</script>
Better yet. Move the JS to a separate file and include it with <script src>.
I have an extremely simple little JavaScript/Perl CGI example that I've used to get started with a larger project. When I run it as client.html and server.pl, it works flawlessly. However, when I change the client.html to client.tmpl, and call it from the same server.pl script using Template Toolkit, it can't seem to find jQuery functions.
I have even created a master.tmpl file, and used [% INCLUDE client.html %] inside it, and it fails. The browser console verifies that the path to jquery.js is correct, but it's like it fails to load it when it's inside a template.
The following is the HTML file that I'm essentially trying to turn into a .tmpl file (formatting messed up, first time here, sorry):
client.html
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<meta charset="UTF-8" />
<script src="http://domainname/ajax_example/jquery.js"></script>
<script type="text/javascript">
function myTimer() {
var typingTimer;
var doneTypingInterval = 2000;
$("#user_text").keyup( function() {
clearTimeout(typingTimer);
if ( $('#user_text' ).val()) {
typingTimer = setTimeout(updateText, doneTypingInterval);
}
});
function updateText() {
var current_text = document.getElementById('user_text').value;
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if ( http.readyState == 4 && http.status == 200 ) {
var response = http.responseText;
document.getElementById('server_response').value = response;
}
};
http.open("GET", "http://domainname/ajax_example/cgi-bin/server.pl?user_text=" + current_text , true );
http.send();
}
}
</script>
</head>
<body>
<div>Input Text: <input type="text" id="user_text" name="user_text" onkeyup="myTimer()"/></div><br/>
<div>Server Resp.: <textarea id="server_response" name="server_response"> </textarea></div>
<br/>
</body>
</html>
The server.pl that works:
server.pl
$cgi = CGI->new;
$id = $cgi->param('user_text');
$result = uc($id);
print $cgi->header();
print $result;
The server.pl that doesn't work:
server.pl
$cgi = CGI->new;
$id = $cgi->param('user_text');
**returned from result calculation sub** $result = uc($id);
my $config = {
EVAL_PERL => 1,
POST_CHOMP => 1,
INTERPOLATE => 1,
INCLUDE_PATH => '/usr/lib/cgi-bin/ajax_example/:/var/www/html/ajax_example/',
};
print $cgi->header( -charset=>'utf-8' );
my $tt = Template->new($config);
$tt->process('client.tmpl', \$result);
}
Keep in mind, I am trying my best to summarize the code, but the Perl and JavaScript work just fine, unless it's being used through TT. The error is:
#user_text.keyup is not a function:
("#user_text").keyup(function(){
Same error I would get if I put in a bad path to jquery.js. The path is good though, without a doubt.
Thank you for any recommendations anyone can provide.
The immediate problem is that you have enabled the INTERPOLATE option, which interpolates Perl variables anywhere in the template. That makes the module attempt to replace $( by its value, and destroys the JavaScript syntax
It's a sloppy way of using templates anyway: you should pass all the values you need in the $vars hash, and extract them from there using [% variable %] template directives. The same applies to the EVAL_PERL option, as any complex data manipulation should ordinarily be in the code that calls process. Everything you need to do inside the template is available as a Template directive
Talking of the $vars hash, you should be getting Not a HASH reference errors, because you are passing to process a reference to the string variable $result instead of a hash containing that value. It's unclear how you want that value to be handled, but the only mention of id in your HTML is the id attribute of the <input> element at the bottom of the HTML, so I've put a directive in their to show you how it all works
Take a look at this code
CGI program
use strict;
use warnings 'all';
use CGI;
use Template;
my $cgi = CGI->new;
my $id = $cgi->param('user_text') // 'abc123';
my $result = uc $id;
print $cgi->header( -charset => 'utf-8' );
my $tt = Template->new( {
# INCLUDE_PATH => '/usr/lib/cgi-bin/ajax_example/:/var/www/html/ajax_example/',
POST_CHOMP => 1,
} );
$tt->process('client.html', { result => $result } );
I have modified your HTML file like this. I couldn't tell what you wanted to do with the value that the CGI code pulls from the user_text parameter, so I put it into a value attribute for the first input field
Template file
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<meta charset="UTF-8" />
<script src="http://domainname/ajax_example/jquery.js" />
<script type="text/javascript">
function myTimer() {
var typingTimer;
var doneTypingInterval = 2000;
$("#user_text").keyup( function() {
clearTimeout(typingTimer);
if ( $('#user_text' ).val() ) {
typingTimer = setTimeout(updateText, doneTypingInterval);
}
} );
function updateText() {
var current_text = document.getElementById('user_text').value;
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if ( http.readyState == 4 && http.status == 200 ) {
var response = http.responseText;
document.getElementById('server_response').value = response;
}
};
http.open("GET",
"http://domainname/ajax_example/cgi-bin/server.pl?user_text=" + current_text,
true );
http.send();
}
}
</script>
</head>
<body>
<div>Input Text:
<input type="text" id="user_text" name="user_text" value="[% result %]" onkeyup="myTimer()"/>
</div>
<br/>
<div>Server Resp.:
<textarea id="server_response" name="server_response"/>
</div>
<br/>
</body>
</html>
And here's the resulting output from the CGI code. As you can see, the $("#user_text").keyup call remains intact, and the value from the CGI code—the result element passed in the $vars hash—has been substituted into the value attribute of the text input element
I hope this helps you to progress and get your application working
output
Content-Type: text/html; charset=utf-8
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<meta charset="UTF-8" />
<script src="http://domainname/ajax_example/jquery.js" />
<script type="text/javascript">
function myTimer() {
var typingTimer;
var doneTypingInterval = 2000;
$("#user_text").keyup( function() {
clearTimeout(typingTimer);
if ( $('#user_text' ).val() ) {
typingTimer = setTimeout(updateText, doneTypingInterval);
}
} );
function updateText() {
var current_text = document.getElementById('user_text').value;
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if ( http.readyState == 4 && http.status == 200 ) {
var response = http.responseText;
document.getElementById('server_response').value = response;
}
};
http.open("GET",
"http://domainname/ajax_example/cgi-bin/server.pl?user_text=" + current_text,
true );
http.send();
}
}
</script>
</head>
<body>
<div>Input Text:
<input type="text" id="user_text" name="user_text" value="ABC123" onkeyup="myTimer()"/>
</div>
<br/>
<div>Server Resp.:
<textarea id="server_response" name="server_response"/>
</div>
<br/>
</body>
</html>
Hello I am new in PHP and JavaScript. I have a code of Dropdown Checkbox. I want to try get out values of checked options with comma separate like 1,2,3
My problem is that when i run my code my output have one extra comma at the end like 1,2,3, and my desired output is 1,2,3
Here is my code
HTML Part
<select id="agency" multiple="multiple">
<?php
if (is_array($rating_agencies) && !empty($rating_agencies)) {
foreach ($rating_agencies as $rating_agencie) {
echo '<option value="'.$rating_agencie->ID.'"';
echo '>';
echo $rating_agencie->name;
echo '</option>';
}
}
?>
</select>
<input type="button" id="btnSelected" value="Get Selected" />
Java Script
<script type="text/javascript">
$(function () {
$('#agency').multiselect({
includeSelectAllOption: true
});
$('#btnSelected').click(function () {
var selected = $("#agency option:selected");
var message = "";
selected.each(function () {
message += $(this).val() + ",";
});
alert(message);
});
});
</script>
Use jQuery.map with Array#join
.get() will return basic-array instead of array-of-objects
$(function() {
$('#agency').multiselect({
includeSelectAllOption: true
});
$('#btnSelected').click(function() {
var message = $("#agency option:selected").map(function() {
return this.value;
}).get();
alert(message.join(','));
});
});
Use slice to remove the last comma.
$('#btnSelected').click(function () {
var selected = $("#agency option:selected");
var message = "";
selected.each(function () {
message += $(this).val() + ",";
});
message = message.slice(0, -1);
alert(message);
});
This is your question solution, OR you can go with #Rayon.
Use slice function :
<script type="text/javascript">
$(function () {
$('#agency').multiselect({
includeSelectAllOption: true
});
$('#btnSelected').click(function () {
var selected = $("#agency option:selected");
var message = "";
selected.each(function () {
message += $(this).val() + ",";
});
message = message.slice(0, -1);
alert(message);
});
});
</script>
Try to get the value instead of option:selected, It may work for you
var selected = $("#agency").val();
use rtrim method in php
// $commaString = "1,2,3,";
$string = rtrim($commaString,",");
// output
// 1,2,3
in Javascript
var comma_string = "1,2,3,";
string = comma_string.replace(/,+$/,'');
You can use in either side as your logic.
Just use $rating_agencies = array_filter($rating_agencies) before your "if" statement.
Following this post :
Define Apex controller in javascript home component
I tried to improved it, because the limit of Salesforce for an SOQL request is 50k records.
The Code_Postal__c object can have more than 50k of records.
I saw that we can parse item in javascript (i'm pretty bad with this language).
The idea is to make a dynamic call of my controller when the user will start typing the postal code ( id of the field = #acc18zip ). But i got an error with my item list, so i came back to use my string but it didn't work.
When i tried to find the error with the chrome console or firebug i saw this error into my console :
Uncaught SyntaxError: Unexpected end of input
and when i start typing a postal code:
event.returnValue is deprecated. Please use the standard event.preventDefault() instead.
My updated controller is this one :
global class cpSearch2{
webService static String searchCP() {
String pickValues='';
for(Code_Postal__c cp : [Select Commune__c, Code_Postal__c from Code_Postal__c ]){
pickValues = pickValues +cp.Code_Postal__c+ ' - ' + cp.Commune__c+'+';
}
return pickValues;
}
webService static string searchCP2(string searchTerm) {
String pickValues='';
for(Code_Postal__c cp : [Select Commune__c, Code_Postal__c from Code_Postal__c where Code_Postal__c LIKE :searchTerm]){
pickValues = pickValues +cp.Code_Postal__c+ ' - ' + cp.Commune__c+'+';
}
return pickValues;
}
/*
Function with list of object
webService static list<Code_Postal__c> searchCP2(string searchTerm) {
list<Code_Postal__c> matchingCP = new list<Code_Postal__c>();
for(Code_Postal__c cp : [Select Commune__c, Code_Postal__c from Code_Postal__c where Code_Postal__c LIKE :searchTerm]){
matchingCP.add(cp);
}
return matchingCP;
}*/
}
and the updated javascript is :
<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="/soap/ajax/15.0/connection.js" type="text/javascript"></script>
<script src="/soap/ajax/15.0/apex.js" type="text/javascript"></script>
<script>
var url = document.URL;
if(url.indexOf('001')!=-1)
{
var sid = document.cookie.match(' sid=([^;]*)')[1];
sforce.debug.trace=true;
sforce.connection.sessionId = sid; ;
var stages;
var cpObjects;
var queryTerm;
$ = jQuery.noConflict();
$(function()
{
$( "#acc18zip" ).autocomplete({
source:function( request, response ) {
queryTerm = request.term;
stages = sforce.apex.execute("cpSearch2", "searchCP2", {queryTerm,function(result, event)});
if(event.type == 'exception') {
alert(event.message);
} else {
cpObjects = stages.toString().split("+");
response(cpObjects);
}
},
focus: function( event, ui ) {
$("#acc18zip").val(selectedArray[0]);
$("#acc18city").val(selectedArray[1]);
return false;
},
select: function( event, ui ) {
console.log(ui.item);
selectedArray = ui.item.split(" - ");
$("#acc18zip").val(selectedArray[0]);
$("#acc18city").val(selectedArray[1]);
return false;
}
});
});
}
</script>
Trying to follow this :
http://jqueryui.com/autocomplete/#remote-jsonp