Autocomplete in jQuery just...stopped working? - javascript

I had jQuery autocomplete working perfectly with CodeIngiter when inexplicably it just stopped functioning completely. When I visit the controller for the autocomplete I still see the correct array - Javascript just isn't returning the JSON data. What makes this weird is that it was working fine, and then out of the blue just stopped working.
Here's my Javascript:
$( "#clubs-complete" ).autocomplete({
source: function(request, response) {
$.ajax({
url: 'http://www.myurl.com/create/autocomplete',
data: 'term='+$("#clubs-complete").val(),
dataType: "json",
type: "POST",
success: function(data){
alert(data);
response(data);
}
});
},
minLength: 1
});
Here's my controller:
public function autocomplete()
{
// Search term from jQuery
$term = $this->input->post('term');
$this->db->select('name','address2');
$this->db->from('clubs');
$this->db->like('name', $term);
$suggestions = $this->db->get()->result();
if (count($suggestions) > 0) {
$data = array();
foreach ($suggestions as $suggestion) {
array_push($data, $suggestion->name);
}
// Return data
echo json_encode($data);
}
}
Does anyone have any idea what's going on? The alert in the javascript function returns nothing now, and it used to. When I visit the URL directly I still see the full array.
Please help, I'm tearing my hair out.

In IE there are developer tools available if you press F12. There's something similar in Firefox called Firebug. In either of these you can debug in-browser javascript. Set breakpoints inside the source fn and also within the success function, it may give you some insight.
You also may want to get an http debugging proxy, something like Fiddler2 or Charles, which will let you see outgoing HTTP requests and their corresponding responses. Fiddler2 runs on Windows and works with FF and IE, and pretty much every other http client. This will let you see the messages that your AJAX service is returning to the in-browser javascript.
Those things ought to give you insight into the "not working" problem.

Related

Cannot access $wpdb, comes back NULL

I'm developing a rather simple plugin using the Wordpress Plugin Boilerplate. Utilizing AJAX, I set up a action based upon a button press that's supposed to remove an item from the custom database table I set up. The AJAX works, the button works, the call to the operating PHP file works.
However, when I get to the operating PHP file where some simple database manipulation is supposed to take place, nothing happens. The file at this point consists of:
global $wpdb;
$table_name['database_name'] = $wpdb->prefix . 'database_name';
echo var_dump($wpdb);
echo var_dump($table_name);
echo var_dump($wpdb->prefix);
That's it right now. And these var dumps come back as "NULL," "database_name", and "NULL."
What am I doing wrong here? In the few others files involved in this project everything works fine. What did I break? If it's an AJAX thing and Wordpress handles AJAX differently, I'd love to see a good tutorial for it, because the few I've found that handle Wordpress AJAX explicitly have been outdated and/or broken.
it means you are calling $wpdb even before wordpress can initialize it, or you're doing something even more weirder
it can be done something like this,
jquery
$('body').on('click', '.some-click-handler', function() {
$.ajax({
type: 'POST',
url: ajaxurl,
data: {'action':'test_ajax'},
success: function(data) {
console.log(data);
},
error: function(errorThrown) {
console.log(errorThrown);
},
});
});
your php ajax handler, though you should add more security like nonce
//wp_ajax_nopriv for non logged-in user
add_action('wp_ajax_test_ajax', function() {
global $wpdb;
wp_send_json( $wpdb );
});
checkout wordpress ajax docs https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

Use Javascript array in PHP

I know this question has been asked before several times on this forum, but I think I am missing something. Or maybe it is because I don't know JSON/AJAX that well.
Here is the thing.
I got some javascript/JQuery code on a page, say on index.php, (not yet in a seperate JS file) which let you put any number in an array from 1 to 10. If it's already in it, it will be removed if clicked again.
Now I want to pass that JS array to PHP, so I can create tables with it.
Here's what I have done.
$(".Go").click(function() {
var enc = JSON.stringify(tableChoice);
$.ajax({
method: 'POST',
url: 'calc.php',
data: {
elements: enc
},
success: function(data) {
console.log(enc);
}
});
});
And in my calc.php I got this to get the values to PHP.
<?php
$data = json_decode($_POST['elements'],true);
echo $data;
?>
Now here comes the noob question:
If I click my (.Go) button, what really happens?
Because the console.log let's me see the correct values, but how do I access it? The page (index.php) doesn't automatically go to the calc.php.
When I use a <form> tag it will take me there, but it shows this error:
Undefined index: elements
I am sure I am looking at this the wrong way, interpreting it wrong.
Can someone please help me understand what it is I should be doing to continue with the JS array in PHP.
With a XHR request you don't do a page reload. With your $.ajax method you post data to the server and receive information back. Since you can see information in your console, the success method is triggered.
You might want to take a look at your DevTools in for example Chrome. When you open your Network tab and filter on XHR you see what happens. You can inspect your XHR further by looking into the data you've send and received.
So my question to you is: what do you want to happen onSuccess()? What should happen with the data you receive from your backend?
In JavaScript:
$(".Go").click(function() {
var enc = JSON.stringify(tableChoice);
$.ajax({
method: 'POST',
url: 'calc.php',
data: {
"elements="+enc;
},
success: function(data) {
console.log(data);// You can use the value of data to anywhere.
}
});
});
In PHP:
<?php
if(isSet($_POST[elements]))
{
$data = json_decode($_POST['elements'],true);
echo $data;
}
else
{
echo "Elements not set";
}
?>

Signalr polling issue with Internet Explorer 9 and ForeverFrames

I use Signalr to show real time updates of long processes happening on the server.
The idea is that the user can see how many items have been processed out of a set amount.
An AJAX post request sends the call to the server to start the process through a controller, at the end of this a partial view is returned and the container element is populated with this result.
$("body").on("click", "#process-button", function ()
{
var hub = $.connection.myHub;
$.connection.hub.start().done(function ()
{
connectionId = $.connection.hub.id;
$.ajax({
type: "POST",
url: "StartProcess/MyController"+ "&connectionId=" + connectionId,
cache: false,
success: function (data) {
$(".modal #container").empty();
$(".modal #container").html(data);
}
})
});
hub.client.sendMessage = function (message) {
$(".modal #container").empty();
$(".modal #container").append(message);
}
});
I cant show the controller ActionResult method for legal reasons but im 100% sure the problem is in the above code. I just cant figure out why.
Ive tested this in Chrome, Firefox, IE10,11 and edge all fine (presumably cos they use websockets) but on IE9 which is using ForeverFrames the process is stalling.
Its worth noting that I tested IE9 using the document mode emulator through IE11.
Here is the output from the network trace.
Excuse the blacked out entries, trying not to broadcast the code.
As you can i have highlighted where the request simply stalls and to my knowledge the partial view is not returned because of this.
Anyone encountered this before?
You can try adding
$.connection.hub.start({ transport: ['webSockets', 'serverSentEvents', 'longPolling'] });
To your script to disallow the use of ForeverFrames.

How to get Twitter search results in Javascript

I would like to grab a list of the recent appearances of a hashtag, but this seems to be impossible to do in Javascript at the moment. I have seen a lot of code snippets around that read like:
function searchTwitter(query) {
$.ajax({
url: 'http://search.twitter.com/search.json?' + searchTerm,
dataType: 'jsonp',
success: function (data) {
//some code
}
});
}
However, this does not seem to work anymore. If I try to use it, I get an error in the console like so:
XMLHttpRequest cannot load http://search.twitter.com/search.json?q=%23twitter. Origin http://myserver.com is not allowed by Access-Control-Allow-Origin.
The same thing happens if I use $.getJson(). Is there a solution for this? A workaround? It seems as though they changed something and then suddenly no one's client-side code works anymore. I really would like to be able to grab the data using Ajax so I can update my page without having to reload the whole thing.
If I am missing something obvious, please let me know.
You can solve this by configurin apache to
Access-Control-Allow-Origin *
Or for some reasons which i do not understand it worked using jQuery.getJSON();
function searchTwitter(query) {
$.getJSON({
url: 'http://search.twitter.com/search.json?' + searchTerm,
success: function (data) {
//some code
}
});
}
http://api.jquery.com/jQuery.getJSON/

IE8 XHTML returned in jQuery ajax call issue

I'm having an issue I cannot resolve through trying lots of different methods!!
Works in Chrome, FF, IE9 but not IE8 or IE7
Overview
I have a page, that Ajax's in the whole HTML from a local .aspx of which reads a photobucket XML feed puts into an HTML list and returns.
http://custommodsuk.com/Gallery.aspx
I've done it this way so the page ranking isn't penilised by Google speed rankings, as the server would be going off and making the call.
The code
$.ajax({
type: "GET",
url: ajaxURL,
dataType:'html',
success: function (feedHTML) {
var galleryList = $(feedHTML).find('#galleryList').find('.listItem');
var noItems = galleryList.length;
console.log(feedHTML.type);
galleryList.each(function (index) {
...
});
}
});
What I've tried
As you can see the console.log(),
the type is undefined, the feedHTML.length shows no. of characters. And from what I gather is generally treated as a string.
It is the JQuery not being able to turn the response into a jQuery object, and I can't traverse it. Therefore the each won't cycle.
I've seen lots of people with the same/similar issue on SO, but no answers, partly due to crap code examples.
Photobuckets RSS feed is malformed.
<p>CustomModsUK posted a photo</a></p>
This tripped up IE8. If you ever have problems like this in the future, check the validity of the HTML!!!

Categories

Resources