How can i stop my AJAX call so I can start a new one?
The use case for this was a search functionality that was triggered on keyup. That said, the more a user typed the ajax call would fire again and again till the search had queued so many ajax calls that the final result may or may not be the last ajax call to complete. Plus the user should essentially be told the search restarted and is not wasting more time finishing searches that were no longer relevant.
It’s actually just a small addition using a variable i’m naming search_xhr. If there is is an active search happening, you can run the search_xhr.abort(); function to kill the process before it finishes. This is useful when ever you started to get something you wanted from a service that is no longer relevant based on a user interaction.
var search_xhr = null;
function api_search(options){
if( search_xhr != null ) {
search_xhr.abort();
search_xhr = null;
}
//visual start/restart queue can happen here
search_xhr = $.ajax({
type: "GET",
url: '[search_api_url]',
data: options,
dataType: "json",
success: function(ajaxdata){
//visual finish queue can happen here
search_xhr = null;
}
});
}
How do I set up a Drupal 8 Module to be an AJAX service?
File structures seem a lot different in Drupal 8, and I’m still getting the hang of them. This is an example of a simple module I made, so hopefully it can be a good starting point for you too!
my_module/my_module.info.yml
name: Module Name Here
type: module
description: Description of the module
core: 8.x
my_module/my_module.module
<?php
//basically any code you want your module to do
//ex: any functions that need API calls or data that you call in any preprocessor functions
use Drupal\my_module\Controller\DefaultController as MyModule;
function my_module_get_data(){
$data = MyModule::hello_world();
return json_decode($data->getContent());
}
**Drupal 8 includes a way to make URLs via a routing.yml file.
my_module/my_module.routing.yml
#GENERAL
my_module.hello_world:
path: '/my_module/hello_world'
defaults:
_controller: '\Drupal\my_module\Controller\DefaultController::hello_world'
requirements:
_permission: 'access content'
my_module/src/Controller/DefaultController.php
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class DefaultController extends ControllerBase{
public static function hello_world(){
return new JsonResponse(true);
}
}
So in this example: now if you go to http://mywebsite.com/my_module/hello_world if will call the defaultcontroller in your module and print out JSON you can use in an ajax call. You’ll also notice I can use it on the server side as well (my_module.module)
To me this was a lot easier or a process than Drupal 7 was. Happy Drupal Coding!
Ajax requests in WordPress
There are many reasons to use Ajax on a website as it allows the content to load into the page as needed. In the past i’ve always made a separate file for handling all these things, and performance wise they may be about the same. However, there is a built in way to do these things the official WordPress way that was actually easier to work with than creating new services.
WordPress Documentation
Demo example
Summarizing, there is a “wp_ajax_[ACTION]” hook that allows server side processing of the ajax request.
add_action( 'wp_ajax_nopriv_[ACTION]', 'ajax_process_function' );
add_action( 'wp_ajax_[ACTION]', 'ajax_process_function' );
function ajax_process_function() {
$filterpage = $_REQUEST['page'];
$filterformat = $_REQUEST['format'];
echo "Page:".$filterpage." Format:".$filterformat;
die();
}
This is accompanied by a jQuery ajax request that looks like:
$.ajax({
url: "/wp-admin/admin-ajax.php",
type: 'post',
data: {
action: '[ACTION]',
filterpage : 1,
filterformat : "format"
},
success: function( html ) {
if(html){
$('#container').html( html );
}else{
alert("no content");
}
}
});
How do I queue jQuery ajax requests
I was recently doing some javascript testing and needed to make some asynchronous (sequential) ajax requests for authentication, creating of records, etc. As with all good things jQuery, the solution to this problem is to install the plugin. The ajaxq plugin, that is.
Installation is as simple as including it in your code.
[script language="javascript" src="/js/jquery-1.6.2.min.js"][/script]
[script language="javascript" src="/js/jquery.ajaxq.js"][/script]
Then calling the $.ajaxq method, which takes the queue name (use different names to run multiple asynchronous queues synchronously) and the settings object with the same parameters as jQuery’s ajax function.
$(function() {
//Login, then logout
$.ajaxq("queue", {
url: '/api/user/login',
type: "POST",
data: {
username: "username",
password: "password"
},
success: function(data) {
document.write("Logged in...
");
}
});
$.ajaxq("queue", {
url: '/api/user/logout',
type: "POST",
success: function(data) {
document.write("Logged out...
");
}
});
});
And finally, an example which runs two queues simultaneously:
$(function() {
//Login, then logout
$.ajaxq("one", {
url: '/api/requestone',
type: "POST",
success: function(data) {
document.write("Request one queue 'one'...
");
}
});
$.ajaxq("two", {
url: '/api/user/logout',
type: "POST",
success: function(data) {
document.write("Request 1 queue 'two'...
");
}
});
$.ajaxq("two", {
url: '/api/user/logout',
type: "POST",
success: function(data) {
document.write("Request 2 queue 'two'...
");
}
});
});
Output could either be
Request 1 queue 'two'...
Request 2 queue 'two'...
Request 1 queue 'one'...
or
Request 1 queue 'one'...
Request 1 queue 'two'...
Request 2 queue 'two'...
How do I json_encode a Kohana ORM Result as an array
I’m working on an Kohana based API where I needed to return some data from an ORM result as an array. Sure, I can loop through the ORMIterator and assign the results to an array, but there must be a nicer way of doing this. I ran across this thread which uses and anonymous function to do the as_array() call. See:
echo json_encode( array_map( create_function( '$obj', 'return $obj->as_array();', ORM::factory('image')->find_all()->as_array() ) );
jQuery Variable Name Practices
On something I was working on this week, this snippet of code created a dilemma in IE8:
frame = "";
if (type == "frame"){
frame = $("#step_2 [name=frame]:checked").val();
if (frame =="black/black"){frame = "black";}
else{frame = "brown";}
}
The strange thing is that it will actually work in most browsers (firefox, IE9, chrome, etc). In fact: In IE8, it won’t even get past the first line where the variable is declared. However, I have found that renaming the variable causing the problems solved the issue quite efficiently.
Looking into why this is the case, browsers end up making global variables for each ID in the window object. Earlier in my code i indeed had a div with the ID “frame”. Most current browsers let you overwrite these auto created properties, but earlier versions of IE don’t actually let you.
So, when you create a variable name in jQuery, it’s a good practice to use names that you do not use as IDs in your actual code. My code solution is below:
frameColor = "";
if (type == "frame"){
frameColor = $("#step_2 [name=frame]:checked").val();
if (frameColor =="black/black"){frameColor = "black";}
else{frameColor = "brown";}
}