I am using Google Books API PHP and would like to change search key word when user types it in order to return immediate title tips. How to implement so that q=what user types right now?
<script src="https://www.googleapis.com/books/v1/volumes?q=harry+potter&callback=handleResponse"></script>
To do this efficiently, remove &callback=handleResponse so the actual response you get back is JSON.
In your javascript set a variable as so:
var request = 'https://www.googleapis.com/books/v1/volumes';
Have a form (containing textarea and submit) handler with something like this:
$('#form').onsubmit(function(e){
e.preventDefault();
var keywords = $('#myTextAreaInputInsideTheForm').val();
$.getJSON(request + '?q=' + keywords, function(data){
//do stuff with the json response
console.log(data);
});
});
Or if you require the XMLHTTPrequest to be called everytime something changes within the textarea
$('#myTextArea').on('keyup', function(){
var keywords = $(this).val();
$.getJSON(request + '?q=' + keywords, function(data){
//do stuff with the json response
console.log(data);
});
});
EDIT: I'm assuming you're using textarea, but <input type="text"/> works as well.
EDIT2: DEMO The demo may not work because google now returns a 403 forbidden. You must not call URL too many times or google will bloc your request. I recommend calling it every couple of letters written. Good luck.
var request = 'https://www.googleapis.com/books/v1/volumes';
$('#myTextArea').on('keyup', function(){
var keywords = $(this).val();
if(keywords.length > 0 && keywords.length % 5 == 0){
$.getJSON(request + '?q=' + keywords, function(data){
//do stuff with the json response
console.log(data);
});
}
});
Using keyup is better than change.
Related
I have build some inputs to let the user search the database. The search is using ajax request.
The problem that I have is because when I get the response from the server I also get the search inputs. I don't want that.
Take a look to my code:.
<script>
$(document).on('change', '.auto-select', function(e){
e.preventDefault();
var tags = $('#auto-tag-script').serialize();
var contracts = $('#auto-contract-script').serialize();
var educations = $('#auto-education-script').serialize();
var towns = $('#auto-town-script').serialize();
runAjax(tags, contracts, educations, towns);
});
function runAjax(tags, contracts, educations, towns) {
$.ajax({
url: 'http://localhost/jobs/public/anazitisi-ergasias?' + tags + '&' + contracts + '&' + educations + '&' + towns
}).done(function(data){
$('div.show-html-from-ajax').html(data);
});
}
</script>
With the above code the inputs appears again in my page.
Is there any way to escape this form inputs.
You can hide it 2 ways...before you insert it (best way) or after you insert it
$.ajax({
url: '...'
}).done(function(data){
// create jQuery object from response
var $html = $(data);
//hide within that object
$html.find('.search-form-for-hide').hide();
// insert the object
$('div.show-html-from-ajax').html($html);
/******* OR ***************/
// the html is in the DOM now, can do whatever might be needed to it
$('.search-form-for-hide').hide();
});
For many plugins you would need to insert first and then call the plugin
With jQuery, you can implicitly convert a DOM object or html string to a jQuery object by using $(data) or jQuery(data) (See this doc). Then use $(data).find('.search-form-for-hide').hide() to find the element and hide it.
I am successfully Posting to a PHP file, and getting a good response. The part I cannot seem to get is parsing it out then displaying it on my page. Here is my javascript in a validate handler:
submitHandler: function(form) {
var formData = $(form).serialize();
$.post('http://test.php', formData, function(data) {
if(data.success) {
$('#load').show();
var response = i;
$('#load').hide();
//var msg = '';
for(var i = 0; i < x.flights.length; i++) {
msg += '<span>';
msg += '<p>Flight Number: ' + x.flights[i].flight_number + '</p>';
msg += '<p>Cost: ' + x.flights[i].cost + '</p>';
msg += '</span>';
}
//this is were I think it should display. but It's not working
$('#load').html(msg);
Here is my json response:
success
true
message
"Success"
flights
[Object { flight_number="334", cost="983.40", departure_city="Kearney Regional Airpor...arney, Nebraska - (EAR)", more...}]
0
Object { flight_number="334", cost="983.40", departure_city="Kearney Regional Airpor...arney, Nebraska - (EAR)", more...}
flight_number
"334"
cost
"983.40"
departure_city
"Kearney Regional Airport, Kearney, Nebraska - (EAR)"
arrival_city
"Chadron Muni Airport, Chadron, Nebraska - (CDR)"
departs
"2014-03-19 04:33:00"
arrives
"2014-03-19 08:12:00"
duration
"219"
adult_seats_available
"2"
senior_seats_available
"1"
I know you you are not seeing the JSON response, but I can see it in FF firebug. I'm new to jQuery/JSON, and I just want to print the response to my page. Thanks in advance.
Look into JSON.stringify(data) doc I don't know where you want to display your JSON but if you just want to see what it is open up the debugger and console.log(JSON.stringify(data)); should do it.
You are using post method and it may default return xml, json, script, text, html. So you are getting the data from post method.
Try looking at https://api.jquery.com/jQuery.post/
And if you want to access it, then you can use JSON.stringify(data) to show json as a string. And to access data from json you can use dot(.) notation.
There's a couple of things to look at here.
First you're adding your html (ie msg) to the #load element ($('#load').html(msg);) but earlier in the code you're hiding it ($('#load').hide();). So I think this will answer your main question; i.e. remove the the line $('#load').hide(); or add $('#load').show(); after the line $('#load').html(msg);.
Still not seeing anything? Then perhaps the response isn't as corrent as you're claiming so perhaps an easier way to check what's been assigned to msg is to alert the html alert(msg); <- make this call after you've built your html.
So aside from this is the use of the #load element you seem to be using it to hold a loading gif but also assigning it the response via the content of msg. Perhaps you need to separate the use of the elements so that the #load element is for the loading gif and you add another element for the response. so you're code is more like this.
html
<div id="load" class="hide"><img src="loading-animation.gif">...</div>
<div id="post-response" class="hide alert"><div>
where the hide class is display none and alert class represents an style for a response alert.
js
submitHandler: function(form) {
// show the loading gif before we make the
// post data and wait for an async response
$('#load').show();
...
$.post('http://test.php', formData, function(data) {
if(data.success) {
// post-back has completed so lets hide the animation
$('#load').hide();
// your code to build html msg
// assign and show the response element
$('post-response').html(msg);
$('post-response').show();
...
I work on an auto complete search box that search Database and return users that related to search.I use jquery ajax to do this.when keyup on input element occurred then I send a ajax request to the `/ajax/search/ url like below:
$("#search").keyup(function(){
$(".itemSearch").remove();
$(".notfound").hide();
$("#searchResultSection").height("70px");
if(!$("#search").val()){
$("#searchResultSection").slideUp();
$(".ajaxLogoSearch").hide();
$(".notfound").hide();
}
else{
var data = {
query: $("#search").val()
};
$("#searchResultSection").slideDown();
$(".ajaxLogoSearch").show();
$.ajax({
url: '/ajax/search',
data: data,
dataType:'json',
success:function(result){
if(result.found==0){
$(".ajaxLogoSearch").hide();
$(".notfound").show();
}
else{
var searchResult = $("#searchResultSection");
$(".ajaxLogoSearch").hide();
searchResult.css({"height":20});
for(var i=0;i<result.users.length;i++){
var content = '<div class="itemSearch">\
<img src="../../static/social/images/defaultMaleImage.png" height="50px">\
<p>'+ result.users[i].firstname+ ' '+ result.users[i].lastname +'</p>\
</div>'
if(searchResult.height() < 370){
searchResult.height("+=70px");
}
$("#innerSearch").append(content);
}
$(".itemSearch").hover(function(){
$(this).css({"background":"rgb(55, 108, 221)"});
},function(){
$(this).css({"background":"#658be6"});
});
}
}
});
}
})
My problem is when I type 2 letters immediately 2 ajax request sent and I see the search result twice in search result box.I want a way to prevent to send 2th ajax request while first is not completely done.How can I do this ?
EDIT:I finally find the solution in codeproject site thanks for your answers.
this is thte link of the solution
The better way is to simply not send a request until the user stops typing. this is easily done using the keydown event and a throttle waiting for 250ms of inactivity. Doing it your way will result in not getting the results that the user wants.
$("#search").on("keydown",function(){
var $this = $(this);
clearTimeout($this.data("throttle"));
$this.data("throttle",setTimeout(function(){
doSearch.call($this.get(0),$this.val()); // perform the ajax search
},250))
});
Also, when inserting the new results, build the entire result list in a single variable then insert it all at once with .html(thehtml) after the loop.
You should create an additional variable kind of request. This variable will be store link of current ajax-request. When keyup event fire again you should do checking.
if(request) {
request.abort();
}
request = $.ajax({/* */});
UPD1: If first ajax-request completed you should set to zero request variable in success callback.
UPD2: Subscribe on change event is better
I am having an issue trying to set the data name or the objects being passed in. I am writing a system that uses AJAX to send requests to the server which then returns the necessary data. However, I am trying to make things generic to where if the developer adds more "slates" then it will automatically send the request on its behalf. The code looks as following:
$(document).ready(function() {
$(".slate").each(function(){
$.get("requests.php", { $(this).attr('name') : "true" }, function(data){
});
});
});
in other words it takes the name of the element and applies it to the query string. JavaScript doesn't seem to like the
$(this).attr('name')
in the syntax which is understandable since it expects just text (not a var or a string). Is there a way to make this work? Any help is greatly appreciated!
$(document).ready(function() {
$(".slate").each(function(){
var data = {};
data[$(this).attr('name')] = "true";
$.get("requests.php", data, function(data){
});
});
});
I'm using coldfusion and jquery. This is my first real go at jquery and I've searched and read for a long time without cracking this so any help would be greatly appreciated...
Ok, I have an autocomplete returning an id. I'm then passing the id to a second function that returns an array of datatype json. The autocomplete works great and I can get the json to display in an alert box but am a bit stuck on how to use the json results.
I'm trying to loop through the json array and write the values into radio buttons, which then dynamically display on page... So the whole idea is this.
user is selected from drop box and id is returned
user id from selection is passed to user options function and user options are returned in json arrary.
json array is looped through and on each iteration a radio button is created with appropriate values.
all radio buttons are then output to screen for access and selection.
The code I have so far is this :
<script type="text/javascript">
// <!--
$(document).ready(function() {
$("#userName").autocomplete({
cache:false,
source: "/jqueryui/com/autocomplete.cfc?method=getUser&returnformat=json",
//setup hidden fields
select:function(event,ui) {
var uid = ui.item.id;
$("#userid").val(ui.item.id);
// start call to get user options
$.ajax({
type: "POST",
url: "/jqueryui/com/autocomplete.cfc?method=getUserOptions&returnformat=json",
data: ({ userid: uid }),
success: function(data) {
alert(data)
}
});
/// end call to get user options
}
});
});
// --->
</script>
The json displayed in the "alert(data)" popup, which looks fine, is this :
[{"productname":"licence free","quantity":1,"term":12,"id":1},
{"productname":"licence basic","quantity":1,"term":24,"id":1},
{"productname":"licence full","quantity":1,"term":12,"id":2}]
I need to know how to loop through this data and create a radio button for each option, probably something like this, and display them all on screen, which I'm guessing I'll just write to a via the dom once I have something to write :
<input type="radio" name="userOption" value="#id#|#qty#|#term#">#productname#
I have tried a few things, without success, such as :
for(var i =0;i<Data.length-1;i++)
{
var item = Data[i];
alert(item.productname + item.id);
}
And
$.each(data.items, function(i,item){
alert(item);
if ( i == 3 ) return false;
});
I couldn't get either of these to work.
Anyway this is getting a bit long winded. Hope it's clear, and again any help or suggestions appreciated.
Thanks!
First check the datatype of the data parameter returned. You might first need to use .parseJSON() to construct a JSON object.
Then your for loop syntax is not correct. this code works for me:
var data = [{"productname":"licence free","quantity":1,"term":12,"id":1},
{"productname":"licence basic","quantity":1,"term":24,"id":1},
{"productname":"licence full","quantity":1,"term":12,"id":2}];
for (var i=0; i<data.length; i++) {
alert(data[i].productname);
}
Here's a jsfiddle
Try checking parseJSON jquery function.
I quess that the type is a string? If so try it with the javascript function eval. It converts a string to a javascript type.. in your case something like this should work:
Var new_data = eval(data);
Now it should be a workable array/object
Edit: to stay with the data variable:
data = eval(data);
Edit 2:
Your ajax call misses the dataType property:
dataType: "json"
With this you dont need the stuff above i said
Use a each loop to get data and appendTo function to print data in an HTML element with result1 id:
dataType:"json", //nature of returned data
success: function(data) {
var content = '';
$.each(data, function(i, dbdata) {
content += '<p>' + dbdata.columnName + '<p>';
});
$(content).appendTo("#result1");
}