How to use jquery autocomplete with server/sql data fetched with php? - php

Is there something wrong with this code?
Form input:
<input type="text" id="currentTag" name="currentTag" class="inputbox"/>
jquery:
$("#currentTag").autocomplete({
source:'getautocomplete.php',
minLength:1
});
getautocomplete.php
$term=$_GET["term"];
$query=mysql_query("SELECT * FROM table_name WHERE tag_value LIKE '%".$term."%' ORDER BY tag_value ");
$results=array();
while($row = mysql_fetch_array($query)){
$results[] = array('label' => $row['tag_value']);
}
echo json_encode($results);
getautocomplete.php output when script is called directly:
[{"label":"birdseye"},{"label":"doggy"},{"label":"tomhat"}]
'SOLVED'
It's a bit of a hack job, but I ended up setting source as a jquery var instead of url. Then used php include to echo the json into the var. All this in a Joomla site. Some conflict that I don't understand was happening, because the above code worked in a test file outside of Joomla. If anyone knows the conflict I'd curious to learn. Cheers.
$(document).ready(function() {
$( "#currentTag" ).autocomplete({
source: tags
});
});
var tags = <?php include("getautocomplete.php");?>;

see this link http://jqueryui.com/autocomplete/
Include all js .
Get the data from MySQL using Ajax. Proceed With
what you did now.
In the above link you will find demo source code see once
try this once
$( "#currentTag" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "getautocomplete.php",
dataType: "jsonp",
data: {
q: request.term
},
success: function( data ) {
response( data );
}
});
},
minLength: 3
});

There is a few thing wrong here, it could be any of the problems
i assume you connect to the db first, this is not shown in the example but that might be the problem
you should make sure you escape your $term, because you give the availability of SQL injection
you should avoid useing SELECT * if you only need tag_value
you should use mysql_fetch_assoc if you want to use assoc arrays in your result
you should make sure the source URL is correct, it is a relative path the way you've put it, try to always use absolute paths, you never know where your script will be used (and with pretty urls, this becomes worse)

Related

Posting data from ajax to php

Trying to send a post request from ajax to php.
I did many trial and errors based from the answers including making sure that the "type" is set to post, specifying "dataType", correct "url". I think I miss something important but I can't figure out what it is.
main.php
<script>
$(document).ready(function(){
$(".editContact").on("click", function(){
let dataID = $(this).attr("data-id");
console.log(dataID);
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
dataType: "text",
data:{data:dataID}
});
});
});
</script>
functions/phonebook.php
if(isset($_POST["data"])){
$res = array($data=>var_dump($_POST["data"]));
}
else{
$res ='null';
}
Then print the $res variable containing the dataID from ajax to my html element in main.php
<label class="m-label-floating">Contact name <?php echo $res; ?> </label>
The console.log in my main.php prints the data what I want to send in ajax but when I try to send the dataID to my phonebook.php, I get a null value.
Your problem is here:
$res = array($data=>var_dump($_POST["data"]));
You are using var_dump the wrong way.
From the docs:
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
This function does not return any value, so, in your case, $data=>var_dump($_POST["data"]) will always be null.
What you need to is:
$res = array($data => $_POST["data"]);
If you are sending data to a different page altogether and need to use jquery / JS to do it, it might be simpler to send via window replace:
window.location.replace(...)
If you need to stay on the same page, you might want to include a success function in your ajax query, as this will return to the page you are calling from:
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
data:{data:dataID},
success: function (html) {
// do your HTML replace / add stuff here
},
});

Why is AJAX only replacing my variable in some places?

I have the following AJAX code, which replaces anything with class "percentreplacer" with the data in the "Percent" column of the MYSQL database:
<script type='text/javascript'>
$(document).ready(function () {
$('#functionsquestionform2').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : "aplaygroundajaxtest.php",
type: "POST",
data: $(this).serialize(),
success: function (data) {
$(".percentreplace").text(data.percent);
},
});
});
});
</script>
In another part of my script, I have this snippet of PHP code:
<?php echo '<span class="percentreplace">'.$data['FunctionsPercent'].'</span>'; ?>
When I run the code, the AJAX code at the top successfully replaces the above span with the percent value stored in the database (such as "6").
Later on in my code, I try to set this percent as a variable with the JQuery script shown below:
<script type='text/javascript'>
$(function(){
var carouselbutton1percentage='<?php echo '<span class="percentreplace">'.$data['FunctionsPercent'].'</span>'; ?>' ....[cont'd]
Here, however, instead of replacing the entire PHP snippet with the percent (let's say 6), it sets the variable carouselbutton1percentage equal to <span class="percentreplace">6</span> I want the tags to get stripped here just like they did in the former. I'm guessing this has something to do with the quotes, but I've played around with it quite a bit and I can't figure out what to change.
Any help would be greatly appreciated!
Thanks
I might be missing something. But instead of storing a string 'that contains characters that look like PHP and jquery', I would think you want to actually update that html element, like you do in the AJAX response block. So..
$(".percentreplace").text('6');
or
var carouselbutton1percentage = 6;
$(".percentreplace").text(carouselbutton1percentage);
But again, maybe I'm misunderstanding.
I think you need to escape your string properly?
var carouselbutton1percentage='<?php echo \'<span class="percentreplace">\'.$data[\'FunctionsPercent\'].\'</span>\'‌​; ?>';

Json parse and add format

I use this in a function:
$.ajax({
type: 'POST',
url: 'demopost.php',
data: { ... },
dataType: 'json',
success: function(data)
{
console.log(data);
}
});
The demopost.php contains only a query.
The output will be:
But how can I show it inside a div? OR How can I add some formation e.g. with foreach like a php array?
EDIT:
I tried with it (the place of console.log(data):
$('.inner').append(data);
Of course there was a div with class inner. But nothing show
EDIT2:
The query in the demopost.php:
... try
{
$c_id = htmlspecialchars($_POST['cid']);
$leftprice = $_POST['left'];
$rightprice = $_POST['right'];
$items=$main->pdo->prepare("SELECT name, price FROM clf_items WHERE category_id IN (
SELECT node.id
FROM clf_category AS node,
clf_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt AND price BETWEEN :left AND :right
AND parent.id = :c_id)");
$items->execute(array(':c_id' => $c_id, ':left' => $leftprice, ':right' => $rightprice));
$items_array = array();
while ($row = $items->fetch(PDO::FETCH_ASSOC))
{
$items_array[] = $row;
}
echo json_encode($items_array);exit;
}...
What you are doing here is to return some JSON data from the server which can be read by javascript, but is not useful to be pushed into HTML without some processing.
One solution would be to get the JSON array you receive and transform it into a HTML string before pushing it onto the page. This might look like:
success: function(data)
{
var result = '<table>';
for (i=0; i<data.length; i++) {
result += '<tr><td>'+ data[i].name+'</td><td>'+data[i].price+'</td></tr>';
}
result+= '</table>';
$(".inner").html(result);
}
Now this has not money formatting, no html escaping, very crude layout etc pp. Before you try to make this raw sketch into something useful I recommend looking into the various template engines available for jQuery; a few are listed in this post: jQuery Templates are deprecated? (and unlike the question suggests, jQuery templates are not dead, but got some competition).
However I would prefer another approach: create the HTML server side (instead of JSON), so you return a HTML snippet the same way you would return a full HTML page normally in PHP, and in the ajax request say you want HTML: dataType: 'html', and then you can push the result straight into $(".inner").html(data) (or $(".inner").append(data), no idea how your HTML should look like), as you originally wanted.
I guess this is the same as schwierig wanted to say, but I feel one need to tell it more explicit.
For what reason are you using Ajax if you are not processing the data you are sending? If you just want to format the data, you don't really need PHP to do that.
Of course it would be possible. If you want to process with PHP you need to echo your formatted result and use the .done() function as described in the jQuery API
http://api.jquery.com/jQuery.ajax/
$.post('demopost.php',{..}, function(data) {
$('.inner').html(data);
});
try this one hope it will help and make sure you have div with inner class

Jquery:create a dictionary to autocomplete all inputs

i want to add an smart autocomplete to my project in which when ever user is typing a word in any input its autocompleted from his own dictionary.
his owner dictionary is built by saving every word he ever submit to server something like (array_values($_POST))
my current JS
$('input.complete').live('keyup.autocomplete', function(){
var hi=$(this).val().toUpperCase();
var was=this;
$(this).autocomplete({
//PROBLEM Should i consider to change source from ajax/mysql to different source ?
//since there gona be too many requests ??
source: function(request, response) {
$.ajax({ url: '<?=base_url()?>ajax/ac',
//PROBLEM how can i set term=word currently being edited..(start=' ',end=pointerpos)
data: { 'term': this.term },
dataType: "json",
type: "POST",
success: function(data){
if(data.length){
//response(data);
//Commented out cause i dont wana display dropdown.. just typeahead.
if(data[0]['value'].substr(0,hi.length).toUpperCase()==hi){
$(was).val(data[0]['value']);
//currently working with single word inputs..once i get how to select only current word will edit these..
was.selectionStart=hi.length;
was.selectionEnd=data[0]['value'].length;
}
}
}
});
},
select: function(event, ui){},
minLength: 2,
delay: 500
});
As u can see i have 2 problems
Question
how can i select current word that user is typing ?
is this a good approach to reach my goal, or i should consider different plugin
You are using PHP language as well. So in my opinion you can use PHP to solve your problem more easily. Let's say you have php function get_word($excerpt) in get.php file. So,
<?php
get_word($_POST['excerpt']);
function get_word($excerpt) {
// Find exact word from database or array using given $excerpt
// and return complete word.
return $complete_word;
}
?>
And in your jquery (assuming input field as .input),
$(document).ready(function() {
$('.input').live('keyup',function() {
var excerpt = $(this).val();
$.post("get.php", {excerpt:excerpt}, function(data) {
// do anything with data.
$('.input').val(data);
});
});
})
For more precise, you can get bunch of matching words from get.php file, and display list of words to be selected.

jquery php issue

Hey everyone. This one is puzzling me. I'm using PHP and Jquery. I am making an ajax request to a PHP file containing a get url. Eg. Path/to/file/?ID=369
The request goes out fine, I've watched it in fire bug.
However in the PHP file, the ID variable doesn't exist. When I do
var_dump($_GET)
I can see that there are two arrays inside the GET array. These are JSON and action.
Can anyone explain to me what's going on here and how I can receive my ID variable?
here are my codes:
<?php
$program_price_id = $_GET['id'];
$programDepatures = getProgramDepaturesGreaterThanToday($program_price_id);
echo "[{optionValue: 0, optionDisplay: 'Select a date'}";
while ($programDepartureData = mysql_fetch_array($programDepatures)) {
echo ", {optionValue: ".
$programDepartureData['id'].", optionDisplay: '".
tidyDateEnglish($programDepartureData['departure_date'])."'}";
}
echo "]";
?>
Best wishes,
Mike
i think you need to specify the ajax method you are using.It might be a $.ajax, $.get or $.getJson.
but i use $.ajax and here is a snippet
$.ajax({
url:"event/service_ajax_handler.php",
type: "GET",
data: {action:"getTime"},
dataType : "json",
success: function(data) {
$("#cmbTimeRange").html("<option value='-1'>Please select time range</option>");
$.each(data, function(){
$("#cmbTimeRange").append("<option value='"+ this.id +"'>" + this.hours +"</option>")
});
},
error: function(){
alert("error");
}
});
pay attention to the data parameter. see also
getJSON
This may be obvious, but I noticed in the sample URL you have ID capitalized, but in your PHP code you have it lowercase. PHP is case sensitive, so it could be as simple as that.

Categories