I'm trying to implement auto-complete on a textbox in php. The data from autocomplete is retrieved using a GET ajax call (which calls a certain api and returns json output).
The code for my ajax was as follows:
<script type="text/javascript">
$(function() {
$( "#tags" ).keyup(function() {
var query = document.getElementsByName('newartist')[0].value;
$.ajax({
type: "GET",
url: "https://lab.anghami.com/rest/v1/SEARCHedge.php",
data: "output=jsonhp&q=" + query,
dataType: "html",
success: function (data) {
var obj = JSON.parse(data);
console.log("1. " + obj[0]);
console.log("2. " + obj[1]);
}
});
});
});
</script>
This code was working perfectly find, and the output was shown in the console correctly. Next I tried adding this ajax call as "source" to my autcomplete call as follows:
<script type="text/javascript">
$(function() {
var query = document.getElementsByName('newartist')[0].value;
$( "#tags" ).autocomplete({
source: function( request, response ) {
$.ajax({
type: "GET",
url: "https://lab.anghami.com/rest/v1/SEARCHedge.php",
data: "output=jsonhp&q=" + query,
dataType: "html",
success: function (data) {
var obj = JSON.parse(data);
var outp = [];
outp.push(obj.sections[0].data[0].name);
outp.push(obj.sections[0].data[1].name);
console.log(obj.sections[0].data[0].name);
console.log(obj.sections[0].data[1].name);
response(outp);
}
});
}
});
});
</script>
Here, the code stopped working for some reasons, and any console.log commands I had stopped outputting the results.
One other method I found as answer to a similar question was to implement the following code:
<script type="text/javascript">
$(function() {
$( "#tags" ).keyup(function() {
var query = document.getElementsByName('newartist')[0].value;
$.ajax({
type: "GET",
url: "https://lab.anghami.com/rest/v1/SEARCHedge.php",
data: "output=jsonhp&q=" + query,
dataType: "html",
success: function (data) {
var obj = JSON.parse(data);
var artists = [];
artists.push(obj[0]);
artists.push(obj[1]);
test(obj);
}
});
});
});
function test(data){
console.log(data);
$("#tags").autocomplete({
source: data
});
}
</script>
This was a bit better as autocomplete was indeed suggesting results, but it was inconsistent as it sometimes outputted 1 result instead of 2 (my ajax call ALWAYS returns 2 results, and I made sure that it's always the case by using console.log), and sometimes the suggestions proposed by autocomplete were those of the previous AJAX call and not the current one (again, console showed new results but autocomplete suggested previous ones.
If you could point to the errors in both of these methods, it would be great.
Thanks!!
Code looking fine. Please mention the JSON output format.
Related
I have one html page which contains a jquery function.
<script>
function loadCustomers() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/cache/getCustomers',
dataType: 'json',
success: function(data) {
var rows = [];
$.each(data,function(id,value) {
rows.push('<tr><td><a href="clientSiteInfo.html?client=">'+id+'</td><td>'+value+'</td></tr>');
});
$('table').append(rows.join(''));
}
});
};
window.onload = loadCustomers;
</script>
I have linked another html page for each row. When each rows populated, the id values has to be passed to the clientSiteInfo.html page.
In the clientSiteInfo.html page i have another jquery function similar to above.
<script>
function loadSites() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/cache/getSite?clientName='+${param.client},
dataType: 'json',
success: function(data) {
var rows = [];
$.each(data,function(id,value) {
rows.push('<tr><td>'+id+'</td><td>'+value.machine+'</td><td>'+value.state+'</td></tr>');
});
$('table').append(rows.join(''));
}
});
};
window.onload = loadSites;
</script>
in the GET url I try to read client parameter. But it is not passing from my initial page.
What Im doing wrong here? I look for simple solution
jQuery doesn't have a native way to read the url parameters. However, javascript works just fine:
function getParameterByName(name) {
const match = RegExp(`[?&]${name}=([^&]*)`).exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' ') );
}
In your code you would just call it as getParameterByName('client')
alright, I have a popup which displays some notes added about a customer. The content (notes) are shown via ajax (getting data via ajax). I also have a add new button to add a new note. The note is added with ajax as well. Now, the question arises, after the note is added into the database.
How do I refresh the div which is displaying the notes?
I have read multiple questions but couldn't get an answer.
My Code to get data.
<script type="text/javascript">
var cid = $('#cid').val();
$(document).ready(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "ajax.php?requestid=1&cid="+cid,
dataType: "html", //expect html to be returned
success: function(response){
$("#notes").html(response);
//alert(response);
}
});
});
</script>
DIV
<div id="notes">
</div>
My code to submit the form (adding new note).
<script type="text/javascript">
$("#submit").click(function() {
var note = $("#note").val();
var cid = $("#cid").val();
$.ajax({
type: "POST",
url: "ajax.php?requestid=2",
data: { note: note, cid: cid }
}).done(function( msg ) {
alert(msg);
$("#make_new_note").hide();
$("#add").show();
$("#cancel").hide();
//$("#notes").load();
});
});
</script>
I tried load, but it doesn't work.
Please guide me in the correct direction.
Create a function to call the ajax and get the data from ajax.php then just call the function whenever you need to update the div:
<script type="text/javascript">
$(document).ready(function() {
// create a function to call the ajax and get the response
function getResponse() {
var cid = $('#cid').val();
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "ajax.php?requestid=1&cid=" + cid,
dataType: "html", //expect html to be returned
success: function(response) {
$("#notes").html(response);
//alert(response);
}
});
}
getResponse(); // call the function on load
$("#submit").click(function() {
var note = $("#note").val();
var cid = $("#cid").val();
$.ajax({
type: "POST",
url: "ajax.php?requestid=2",
data: {
note: note,
cid: cid
}
}).done(function(msg) {
alert(msg);
$("#make_new_note").hide();
$("#add").show();
$("#cancel").hide();}
getResponse(); // call the function to reload the div
});
});
});
</script>
You need to provide a URL to jQuery load() function to tell where you get the content.
So to load the note you could try this:
$("#notes").load("ajax.php?requestid=1&cid="+cid);
I've been trying to amend the example from http://jqueryui.com/autocomplete/#maxheight to work with input from a locally stored text/csv file looking like
ItemA
ItemB
ItemC
....
I am able to create an array from the data in the textfile and print it to console.log() but I'm not sure how to hand over this array to the autocomplete function. I've tried initializing the array a outside the function but when using it in autocomplete it will use the non-populated array a.
</style>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "john.txt",
dataType: "text",
success: function(data) {processData(data);}
});
});
var a = [];
function processData(myTxt) {
var myLines = myTxt.split(/\r\n|\n/);
for (var i=1; i<myLines.length; i++) {
a.push(myLines[i]);
}
console.log(a);
}
$( "#tags" ).autocomplete({
source: a
});
</script>
How do I pass the array correctly to autocomplete?
I think you are trying to add autocomplete source before the AJAX query is completed.
The query is done on $(document).ready() but the autocomplete source is set before it. So a still remains empty.
Try this:
var a = [];
function processData(myTxt) {
var myLines = myTxt.split(/\r\n|\n/);
for (var i=1; i<myLines.length; i++) {
a.push(myLines[i]);
}
console.log(a);
$( "#tags" ).autocomplete({
source: a
});
}
I want to show all google search auto completes in a textbox.
After searching google i found "http://google.com/complete/search?output=toolbar&q=test" link that is return a xml data contains ten google search suggets.
My jQuery code for showing this xml values is :
$(window).ready(function(){
$( "#textbox" ).keypress = showSuggest();
});
function showSuggest() {
$.ajax({
type: "GET",
url: "http://google.com/complete/search?output=toolbar&q=" + $("#textbox").val(),
dataType: "xml",
var data = [];
success: function(xml) {
$(xml).find('CompleteSuggestion').each(function(){
data.push($(this).find('suggestion')[0].attr('data'));
});
}
});
$( "#textbox" ).autocomplete({
source: data
});
}
jquery-1.9.1.js and jquery-ui-1.10.3 was imported but this code not working.
sorry for my bad english.
thanks.
UPDATE
thanks to everyone.
i edit my code and remove xml reading part and replace
url: "http://google.com/complete/search?output=toolbar&q=" + $("#textbox").val()
$("#textbox").autocomplete({
source: data
});
with this :
$( "#textbox" ).autocomplete({
source: "http://suggestqueries.google.com/complete/search?client=firefox&q=" + $( "#textbox" ).val()
});
now on typing text only show progress image left side of textbox and still not showing suggets.
please help.
NEW UPDATE
I write new code with firefox DOMParser but still not working.
$("#textbox").keypress(function() {
var data = [];
var parser = new DOMParser();
var xml = parser.parseFromString("http://google.com/complete/search?output=toolbar&q=" + $("#new-tag-post_tag").val(), "application/xml");
xml.domain = "google.com";
suggests = getElementsByTagName("CompleteSuggestion");
for (var i = 0; i < suggests.length; i++) {
data.push(suggests[i]);
}
$( "#textbox" ).autocomplete({
source: data
});
}
$(document).ready(function(){
$( "#textbox" ).keypress(showSuggest);
});
function showSuggest() {
// Declare the variable here, not inside the $.ajax code
var data = [];
$.ajax({
type: "GET",
url: "http://google.com/complete/search?output=toolbar&q=" + $("#textbox").val(),
dataType: "xml",
success: function (xml) {
$(xml).find('CompleteSuggestion').each(function () {
data.push($(this).find('suggestion')[0].attr('data'));
$("#textbox").autocomplete({
source: data
});
});
}
});
}
your javascript syntax is wrong. This could work:
$(document).ready(function() {
$("#textbox").on("keypress", showSuggest);
});
function showSuggest() {
var data = [];
$.ajax({
type: "GET",
url: "http://google.com/complete/search?output=toolbar&q=" + $("#textbox").val(),
dataType: "xml",
success: function(xml) {
console.log(xml);
$(xml).find('CompleteSuggestion').each(function(){
data.push($(this).find('suggestion')[0].attr('data'));
});
$( "#textbox" ).autocomplete({ source: data});
}
});
}
anyway I recommend you to learn JavaScript before you start programming.
I have an ajax call which will return a set<E>. I need to process this set from the JavaScript function from which I call this ajax.
<script type="text/javascript">
function mySr(id){
$.ajax({
type: 'POST',
url: '../controller/action',
data: 'id=' + id,
success: function(data) {
var length= data.length
var size = data.size
alert(data[0]+'----'+length+'--'+size+'----'+data)
},
error: function () {
alert('error')
}
});
</script>
This is the way i used,
The alert will display like this
["37",
"40","80","90"]----22--undefined----[
I understood the data is clearly reached in the script but i don't know how to iterate through it.
How to iterate here?
How to get the length?
How to get each elements?
You need to parse the data. Try putting data = $.parseJSON(data); after the line success: function(data) {
See http://api.jquery.com/jQuery.parseJSON/ for more details.