I have recently started to use AJAX with JQuery. I now know how to limit results in AJAX GET requests. However, I have no idea how to make a client-side button to load more requests. Say I have 100 people on the JSON file and i want to load 3 at the time. If the button is pressed, the next three load and the last three disappear.
I used this to limit:
$.ajax({
type: "GET",
url: "/people",
data: {limit: 3, order: 'desc'},
dataType: "json",
success: function(data) {
// Do some awesome stuff.
}
});
Other than limiting results, I really have no idea how to load more results.
What you need is to determine the manner in which you can execute your ajax request such as using a button that will load more data.
Firstly, you've mentioned you can successfully return the limited data by passing parameters to your ajax request, that's great.
You can wrap your ajax request in a function that will allow you to pass parameters such as limit and order direction. Now, I won't go all out here since there's very little information to work with. But to create a button that you can click that will load more data is something that can be demonstrated here.
Here's your AJAX request. We can wrap it in a function that accepts parameters. For example, limit defaults to 3, order defaults to "desc". The possibilities here are endless. You'll obviously want offsets and such but that you can work with as you go along. The purpose of this is only to demonstrate how you could create a button to fetch more data.
jQuery has a shorthand method called $.getJSON which will load JSON-encoded data using a GET HTTP request.
So here's the function which we can later call from the click of a button.
function fetchPeople(limit = 3, order = "desc") {
$.getJSON(
"/people",
{
limit: limit,
order: order
},
function (data) {
// Do something with your data
}
);
}
The button may be something like this.
<button type="button" id="loadMore">Load more</button>
In jQuery you can bind event listeners that will trigger, e.g. on click, and this listener will trigger your function that will go off to fetch whatever it is you've configured in the wrapper function.
$("#loadMore").on("click", function () {
fetchPeople();
});
There are a plethora of plugins for jQuery and code examples across StackOverflow and the WWW in general.
But I'm hoping this steers you in the right direction.
Related
I'm using the jquery tabledit plug-in to update a database. Works perfectly like in the official examples.
I can succesfuly include a static dropdown with a fixed number of options (defined in custom_table_edit.js).
I'd like to be able to dynamically get those options from a database instead, but I don't know how to customize the code in custom_table_edit.js.
I can code this in php with a loop querying the database and generating a html <select> field. But I don't have knowledge of javascript or if it's even possible in this framework.
This is the custom_table_edit.js file. A dropdown is defined with three colour options. I want this dropdown to be dynamically produced.
// custom_table_edit.js
$('#example2').Tabledit({
url: 'example.php',
eventType: 'dblclick',
editButton: false,
columns: {
identifier: [0, 'id'],
editable: [[1, 'car'], [2, 'color', '{"1": "Red", "2": "Green", "3": "Blue"}']]
}
});
I really haven't tried anything because i'd like to know if it's possible to do in this framework.
Welcome to SO, nucelar.
What you are describing is a HTTP request from the client to server through JavaScript. This is commonly referred as AJAX or Asynchronous JavaScript And XML. This API enables you to manually send requests to the server and there are multiple implementations.
Because you are using jQuery I will recommend you to use the $.ajax function which is included in the jQuery library.
Down here I've made a very basic example of how to send a HTTP request to a server with the GET method to retrieve some data.
$.ajax({
url: 'https://yourdomain.com', // Where to send the request to. Can also be a file.
method: 'GET', // What method of request it uses.
success: function(data) { // When a response is succesfully received.
// Do something with the received data.
console.log(data); // Show what the data looks like in the console.
},
error: function(jqXHR, textStatus, errorThrown) { // When an error occurs while making a request.
console.log(jqXHR, textStatus, errorThrown); // Show the error in the console.
}
});
In your case the url property value might be the URL of a PHP file in which you query the database and return the result, as you mentioned you are able to do.
The response of the AJAX function (which is stored in the data variable in the success method) can be text, as in a string, or even JSON if you want to send structured data.
Beware of the Asynchronous part. This means that the AJAX code does not stop the execution of the rest of your JavaScript code, but simply continues and comes back whenever the HTTP request has been completed.
I hope that this is enough to get you started. Good luck and don't hesitate to ask questions.
im using alot of $.ajax calls in my website that im working on and it seems to be slow and lagging at some points. Is there any faster way to retrieve data other than using the $.ajax ?
$.ajax({
type: 'POST',
url: path + 'helper/general/general.php',
data: {pass:pass},
success: function(data){
if(data == 'correct'){
$.ajax({
type: 'POST',
url: path + 'helper/process/ClassesProcess.php',
data: {classID: classID}
});
}else{
$('.feedback').html(wrong_password).slideDown();
}
}
});
Ways in which I think you could optimise this are:
Use === instead of == in an if statement, this way it will check the type before the value.
Instead of doing an ajax call with in an ajax call, surely your first call should do all the logic (try to avoid having logic in your front-end)
Instead of returning strings or html from your ajax calls, return JSON if you can... however be wary of using json_encode/json_decode in php as they seem to be two slow functions.
If the user is refreshing the page, they don't need to redownload the content for a lot of your ajax calls, if the data hasen't changed since that user's last request, return a 304 with no data instead of returning a 200 with the data. This will make the browser get the previous response from it's cache.
Avoid declaring a function where there should be a callback, instead, put the name of a pre-existing function, this will stop the function being reinitialised every time you execute you ajax method.
Finally, when using jQuery, try to target elements by id instead of class, jQuery finds the element a lot faster this way as ids should be unique in a webpage.
Often times I find myself designing apps that make AJAX calls to the server, outside APIs, HTTP requests, etc. The problem is, while this async calls are happening, the user still has the ability to click on items that make the same AJAX call or interrupt the flow of the app, etc. I've experimented with various hacks to prevent this, but I'm wondering what the most accepted way of doing this is?
To make this more concrete, let's say I have a button element that makes an AJAX call and a form element that alters some of the data my app uses for the AJAX call. What is the best way to design the button and form functions so that they do not work while button's AJAX call is in process?
The best way to accomplish what you want is to lead the AJAX calls trough a function so you can check within that function if a request is active. Here's an example assuming you're using JQuery:
active_ajax_call = false;
function get_ajax(url, senddata) {
if(active_ajax_call == false) {
active_ajax_call = true;
$.ajax({
type: "POST",
url: url,
data: senddata
}).done(function (data) {
active_ajax_call = false;
console.log(data);
});
}
}
get_ajax("some_url", {name: "John", location: "Amsterdam"});
And ofcourse present the website user a nice ajax loader or something so they know data is being pulled.
In the handler for the button, disable the button (visually and functionally), then do the AJAX call. Returning from the AJAX call, reenable the button.
This is, how the major sites do it (e.g. PayPal).
I'm creating frontend upload for an app with appengine backend.
What I want to make is a file upload solution, and I dont want to be using plupload or those kinds of ready-made solutions.
I basically submitted the images to an iframe and then put a cover while it is uploading. Then after it finishes I performed an ajax call to get the image ids for the next view to be rendered. However, the render is always called before the upload is completed, thus I'm not getting any image ids from the backend. can anyonehelp?
here's my code for the upload
perform_input3:(event)=>
event.preventDefault()
$('#product-input-3').hide()
$('#product-input-3').submit()
$('#upload-cover').show()
item_id = $('#item3_id').val()
app.views.imageselect.render(item_id)
the app.views.imageselect.render(item_id) is below:
render:(data)=>
#item_id = data
item_id = #item_id
$.ajax(
url: '/get_image_list/'
type: 'GET'
dataType: 'json'
data: {item_id: item_id}
success:(data) =>
#payload = data
$(#el).append imageSelectTemplate(#payload)
return #
)
I dont want to be using setTimeout function since it will not be flexible depending on the connection speed. Any help will be appreciated :)
Essentially, your question boils down to this: You want to wait to make your Ajax call to the server until the data you're requesting is available. Getting notifications from the server is tricky (depending on how your backend is implemented), so the best solution to your problem is probably to just make the Ajax call periodically (say, once per second) until you get a successful response from the server.
Here's some code that should do that:
do ajaxCall = =>
$.ajax
url: '/get_image_list/'
type: 'GET'
dataType: 'json'
data: {item_id: item_id}
success: (data) =>
#payload = data
$(#el).append imageSelectTemplate(#payload)
error: ->
setTimeout ajaxCall, 1000
If you are only targeting modern browsers, then XHR2's FormData can enable a very simple and elegant approach.
The concept is:
add file(s) binary data to a FormData object
make a $.ajax() call with the FormData object as the AJAX call's "data" parameter
when upload is done, the $.ajax()'s success() or complete() callbacks will be triggered
This approach works with the latest Firefox, Chrome, Safari - http://caniuse.com/xhr2.
See this post for details: Sending multipart/formdata with jQuery.ajax
What you're missing is some sort of callback from the $('#product-input-3').submit() call. I think the following would work (pardon my bad CoffeeScript):
perform_input3:(event)=>
event.preventDefault()
item_id = $('#item3_id').val()
$('#product-input-3').hide()
$('#upload-cover').show()
$('#product-input-3').submit()
$('#target-iframe').ready ->
app.views.imageselect.render(item_id)
This is predicated on the idea that calling 'submit' immediately puts the target iframe into non-ready state, which seems reasonable, but I'd test it. Once it finishes loading The other option I've seen around is to have the page the iframe loads call back into its parent (top-level) window. In JS, something like:
parent.imageUploaded()
Or, if you want to use bound events:
parent.$(parent.document).trigger('upload-complete')
Where, of course, you've set up an upload-complete event on the top-level document object.
How can I make sure that a piece of code has executed completely before executing another? I am sending some ajax requests to a server and then using the returned data to generate the rest of the webpage. the things is, is that i need to have all that data in the webpage to proceed with the rest of the code as that code will affect what has been generated and, that code, runs before the json requests and all of that have finished... is there any way I can make sure this does not happen? I managed to solve it by performing the requests and then asking the user to press a button but that is a total no-sense way of doing it.
Any ideas?
Here is some code: The problem is that the second line is executed before the first (there are many calls to similar JSON functions).
$.getJSON(url, function(data){ $("#mycontent").append("..... stuff here...... create loads of dibs with class set to mydivclass"); });
...
$("div.mydivclass").hide();
Unforunately I cannot use the ajax synchronous property because: "dataType: "jsonp" requests do not support synchronous operations"
If you are using jQuery 1.5+ you can make use of deferreds to solve your issue:
function first_ajax_request() {
return jQuery.ajax(
// Your settings here
success: success_function_1
);
}
function second_ajax_request() {
return jQuery.ajax(
// Your settings here
success: success_function_2
);
}
function final_sucess_callback() {
// Do all your display work.
}
jQuery.when(first_ajax_request(),
second_ajax_request()).then(final_success_callback);
There is an excellent article on the topic that you should read up on as well by Eric Hynds. He gives some examples of exactly the kind of problem you are trying to solve.
jquery requests are asynchonize by default , so your code does not wait for the response , so you have no guarantee that code after request will execute after the response , so you can set the request synchronize by set the async property false , now the request is synchronize and you can gurantee the rest of the code will execute after the response from the server ,
like this .
$.ajax({
url: "page.php",
processData: false,
data: xmlDocument,,
async:false,
success: handleResponse
});