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.
Related
I found a script on the net, which makes two PHP files interact.
Specifically, the first file (details.php) shows some statistical data of a football match. If the match is in progress, I show the live score by running another PHP file (live_score.php). The two files interact thanks to the following script, present in the details.php file
$(document).ready(function(){
setInterval(function() {
var id=<?php echo"$id"?>;
var x = "<?php echo"$cod"?>";
$("#risultato").load("live_score.php", {var:id, x});
refresh();
}, 5000);
});
from details.php, I call live_score.php passing it some parameters.
These parameters are used by the live_score.php file to retrieve the score and other information in real time.
To print the result on the screen in details.php, I use a simple ECHO inside the live_score.php file, but I would like to retrieve this data and the others in a different way, via ajax if possible, but I don't know if it can be done and how....can you help me please? Thank you
I think you have already solved half of your problem. From your code , you should first remove the "refresh()" to stop reloading the page every 5 seconds.
then make sure that the the payload is correct, because the word "var" is a reserved keyword in JavaScript.
HTML
<div id="risultato"></div>
Javascript
$.ajax({
url: "live_score.php",
type: "POST",
data: { id, x},
success: function(response) {
//this response will be the data from "live_score.php"
//now assuming that
// 1. you use vanilla javascript with plain html + css
// 2. the returning reponse looks like this
// [{"teamName": "theTeam1", "score": 10}, {"teamName": "theTeam2", "score": 10}]
//Clear the current score
$("#risultato").empty();
// Now iterate through the response,
$.each(response, function(index, item) {
var teamName = item.teamName;
var score = item.score;
var html = "<p><strong>" + teamName + "</strong>: " + score + "</p>";
// this code will append (add to the end) the data iterated
$("#risultato").append(html);
});
},
error: function(xhr, status, error) {
//if your code or ajax call had any problems ,
//you can debug here and write error handling logic here, like
if(error){
alert("failed to fetch data");
console.log(error);
}
}
});
I am attempting to use AJAX to generate PHP to be displayed inside of a div based on the ID of the link clicked. (I haven't dealt with HTML formatting yet, just want to figure this out first)
My Code:
<script type="text/javascript">
jQuery(document).ready(function()
{
$(".myClass h3").click(function(){
var clickID = $(this).attr('id'); //For sake of argument lets say id = 1.
$.ajax({
url: 'landingPage.php',
data: {ProductIDNumber: clickID},
success: function(html) {
$('#container').append(html);
}
});
});
});
</script>
I have dealt with getting the PHP to run when the url is landingPage.php?ProductIDNumber=1 and that all works properly, I just don't quite grasp how to return the resultant HTML.
Edits made and commented on.
You need to include success, which is run once the response is received, similar to;
<script type="text/javascript">
jQuery(document).ready(function()
{
$(".myClass h3").click(function(){
var clickID = $(this).attr('id'); //For sake of argument lets say id = 1.
$.ajax({
url: 'landingPage.php',
data: {
ProductIDNumber : clickID
},
success: function(html) {
// Do what you need to here with 'html'
$('#container').append(html);
}
});
});
</script>
As Alvaro said the structure of the data was also incorrect
Here's a link to the jQuery docs where you can find out more about the parameters and options you have (such as handling fails etc)
the data is wrong,
it is like this:
data: {varname: value, varname1: value},
First I want to show you guys what I am trying to do.
I am trying to create a search functionality in my application using AJAX, jquery and php
and as for the framework I am using Codeigniter, but it's not necessary to be CI, this could be similar to all(well I suppose).
I have this piece of code to observe a focus and blur event.
$("#searchbox").on({
keyup : debounce(function(){
MSI.Interface.search();
},350,false),
blur : function(){
$("#search_results").hide();
}
});
I have not finished it yet that is why the blur event has only .hide() . I can't think of what other else to include, maybe reset the html of the #search_results to make it blank, but I don't know if that is reasonable.
1st question: What do you think is a more reasonable solution for that?
As you can see in the previous code, i have the debounce function, just to prevent per character request on the server, I wonder if that is correct.
Then I have this search function
search : function() {
var keyword = $("#searchbox").val();
if (keyword == '') {
} else {
$.ajax({
url : MSI.variables.base_url + 'search',
type: 'POST',
data: {
keyword : keyword
},
dataType : 'json',
success: function(output) {
$.each(output, function() {
$.each(this, function(key, value){
$("#search_results").show().prepend("<p>"+value+"</p>");
});
});
}
});
}
}
With that code, the script will be able to add contents to the #search_results div.
2nd Question: What do you think is a better solution for this?
I want to basically create a link which says:
Click here to show contact information
Upon clicking it, it will ping a script via an ajax request, the ajax request will look up the user table where the ID is what is contained in the alt tag, it will return a certain field from the database and then the div will change from this link, to a contact number.
I'm sure some of you have seen this done before, for example:
Click to see persons phone number
They click it, and it changes to their phone number.
How would I go about doing this? I want to do it using ajax instead of having the phone number in the source code, because that really defeats the purpose of them having to click to reveal if bots can get it from the source code.
Thanks :)
Somethign along the lines of
$("#reveal").click(function(){
$.get('getphoneNumber.php',{id:$(this).attr('alt')}, function(data) {
$('#reveal').html(data);
});
});
with a php script called getphoneNumber.php that accepts a get parameter of id
Try this one
$('#reveal').click(function () {
var th = $(this);
$.get('/get-the-phone-number', { id: th.attr('alt') }, function (response) {
th.text(response);
});
});
Also, I'd recommend you put the id number inside a data-contact-id attribute and access it via th.data('contact-id') instead of using the alt attribute. Ignore me if you have other reasons to do this.
$("#reveal").live('click',function(event) {
var link = $(this).attr('alt');
var dataString = 'alt=' + link ;
$.ajax({
type: "POST",
url: "url",
cache:false,
data: dataString,
success: function(data){
this.href = this.href.replace(data);
}
});
}
Click here to show contact information
<div id="myHiddenDiv"></div>
$("#reveal").click(function(){
$.get("test.php", { id: $(this).attr("alt") },
function(data){
$("#myHiddenDiv").html(data);
$("#myHiddenDiv").show();
});
});
This example works assuming you've only got one of these "plugins" on your site, if you'll have multiple, use this:
Click here to show contact information
<div class="myHiddenDiv"></div>
$(".reveal").click(function(){
var divSelector = $(this).next("div");
$.get("test.php", { id: $(this).attr("alt") },
function(data){
divSelector.html(data);
divSelector.show();
});
});
i have a set of php function that i want to call on different events mostly onclick with jquery async (ajax).
The first function is called on load
$(document).ready(function()
{
$("#div2").hide('slow');
$("#div1").empty().html('<img src="ajax-loader.gif" />');
$.ajax(
{
type: "POST",
url: "WebFunctions.php",
data: {'func':'1'},
success: function(html)
{
$("#div1").show('slow').html(html)
}
});
The Data: {'func':'1'} --> is a switch statement on the php side
switch($_POST['func'])
{
case '1':
getParents();
break;
case '2':
getChilds(params);
break;
case '3':
getChildObjects(params);
break;
default:
}
"This functions are calls to a soap server" <-- irrelevant.
So when that function finishes i get an array which contains IDs and Names. I echo the names but i want the ID for reference so when i click on the echoed name i can call an other php function with parameter the ID of the name...
How do i get rid of the switch statement?? How do i call properly php functions and pass params to it??? How can i save this IDs so when i click on an item with that id an other php function is called??
Plz feel free to ask any question, any answer is welcome :)
``````````````````````````````EDIT``````````````````````````````````````````
$(document).ready(function()
{
$("#div2").hide('slow');
$("#div1").empty().html('<img src="ajax-loader.gif" />');
$.ajax(
{
type: 'post',
async: true,
url: "Parents.php",
data: {'id' : 12200},
dataType: "json",
cache: false,
success: function(json_data)
{
$("#div1").empty();
$.each(json_data, function(key, value)
{
$("#div1").append('<p class="node"><b>['+key+']</b> => '+value+'</p>');
$(this).data('id', key);
});
}
});
$("p.node").click(function()
{
var id = $(this).data('id');
alert('The ID is: ' + id);
});
});
I got json communication working but my problem is the data stuff,
when i click on a node the id is undefined... it gets printed but when i click on it oupsss.. so the problem is how can i properly attach the ID to each corresponding .. .
You can avoid the switch statement by using an MVC framework that routes your request to the proper function. For example, using CodeIgniter REST Server, you might have the following URL's to your functions:
http://myserver/my_api/parents
http://myserver/my_api/children
http://myserver/my_api/childObjects
You can then POST the parameters along with each AJAX request.
You would probably also want to return the ID you pass as part of the response, so it will be available when you make a request for the next function.
One solution for managing your ID's would be to encode your data as JSON. This will allow you to pass the whole PHP array to Javascript, and have it natively understand and read the ID's and Names.
To encode your PHP array as JSON, try this:
echo json_encode($my_array);
(You'll need PHP 5.2+ for this to work)
This will print out JSON data when the page is requested. Next, in your JavaScript add a "dataType" argument to your Ajax function call. Something like this:
// Get JSON Data and Save
$.ajax({
type: "POST",
url: "WebFunctions.php",
data: {'func':'1'},
dataType: "json",
success: function(json_data) {
$("#div1").data(json_data);
}
});
// Display the ID when clicked
$("#div1").click(function(){
var id = $(this).data('id');
alert('The ID is: ' + id);
});
This tells the Ajax function to expect JSON back.
When the success function is called you can access the "json_data" variable and find all the ID's and Names just as you had them in PHP. You'd then need to write some code to appropriately save those ID's and Names. They can then be used later on (ie. when you click on the button etc).
EDIT: I've updated the code above. The JSON data is now associated with the HTML element "#div1", so you can refer back to it in the future. I've also added a simple click event. Whenever the element is clicked, it's ID will be displayed.