WordPress Ajax Get Request? - ajax

I have a page that includes a php file I have written like so
HTML
<div id="playlists_div_holder">
<?php include(dirname(__FILE__) . '/includes/get_playlists.php'); ?>
</div>
I have created a button that will refresh the playlists , incase the user has uploaded (added/removed) anything, and I am trying to do so with an ajax request to get the file and include it back into that div, but I am receiving a 500 error.
I am doing this in WordPress so that may be an issue.
The Button
<span class="button-primary refresh-playlists" onclick="ReloadPlaylists()">Refresh Playlists</span>
Ajax Request
function ReloadPlaylists() {
jQuery.get('<?php echo plugins_url();?>/Player/includes/get_playlists.php', function(data) {
jQuery('#playlists_div_holder').html(data);
alert('Load was performed.');
});
}
Including it works but an ajax get throws a 500 error

It's pretty hard to guess the problem but some simple workarounds that you can use all the time:-
CAUTION! Please take backup of your WordPress before doing anything.
1st workaround:-
Download fresh WordPress copy
Delete every folder, except the wp-content folder.
Upload all the files and folders again, except the wp-content folder.
2nd workaround:-
Rename
wp-content/themes
to
wp-content/themes-backup
Create a new folder:-
wp-content/themes
start copying each theme from themes-backup to themes one by one and see if the error is gone.
Now what you have done with the themes folder, do exactly with the plugins folder.

Based on your comment,
i'm getting call to undefined function get_option on line 8 , which is odd because it works when i include it the first time. Could it be because its calling the same file on the other and it has some sort of variable conflict?
This is because when the plugin in running as an include, all the wp-includes are laoded before your plugin code is execute. However when you make an AJAX call directly to that file, the wp-includes are no loaded hence your get_option() isn't working.
You can fix that by adding include_once("../../../wp-blog-header.php"); on top of your get_playlists.php file. That might break your plugin (not sure) so in that case its safe to use it inside a condition like this
if(stristr($_SERVER["REQUEST_URI"], get_playlists.php))
include_once("../../../wp-blog-header.php");
However once you do that you will get an Error 404 when you make an AJAX request because that URL is not registered in Wordpress URL Rewrite. You can override that by using header() function.
if(stristr($_SERVER["REQUEST_URI"], get_playlists.php)) {
include_once("../../../wp-blog-header.php");
header("HTTP/1.1 200 OK");
}

Related

ajax returns page source, not the message

All the answers I saw here or elsewhere on Google were with jquery. This is not jquery.
I send an ajax string to a php file.
The php, among other things, formulates a message string which I echo
back to the client.
The returned string is put up in the client as an alert.
The form is then reset.
The problem is that when I do this it puts up as much of the page source that the alert can handle. If I open developer tools to look at the return, it puts the message up correctly, not the page source. Here is the return snippet in my ajax:
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
alert(ajaxRequest.responseText);
document.getElementById("thisForm").reset();
}
}
The php file does a simple echo of a text string.
What is it about developer tools that makes this run correctly and why doesn't it print out the message in the alert when developer tools is not there?
When I run the backend php by itself, with or without developer tools, it displays the message properly.
Does anyone have any ideas?
More information: I tried to replace the alert and reset with a
display.innerHTML=ajaxRequest.responseText where display is a javascript object formed from getElementById("ajaxReturn") of a "div id="ajaxReturn". It didn't work. When I tried developer tools, it showed the network response text as being the page source.
I also added && this.status == 200 to the if statement. No change.
The problem is solved. I am not deleting this because it might help some other poster who runs into the same problem. I launched the AJAX with an onclick to a javascript function called ajaxFunction(). The html entity containing the onclick had an href="#" in it. Removing that href solved the problem.
I had the exact same issue and my cause was related to having an extra slash in my URL.
Lets say my URL was:
https://example.com/index.php
I had a wrong link as follows:
https://example.com/index.php/
On both instances my server loads the page,
But the Ajax shows the page source as response for:
https://example.com/index.php/
But works fine for:
https://example.com/index.php
The ajax is essentially posting to index.php/ajaxpage.php which then responds with whats on index.php instead of whats on ajaxpage.php

Ajax Request gets blocked in Firebug but works in Genymotion. Why?

I am trying to build an "app version" of my website (a social network).
I am using PhoneGap + jQuery Mobile (i started learning them today).
The app simply needs to retrieve new posts from the website and show them to the user. Therefore I thought a simple Ajax Request would do the job.
So, i created a php test file on the server (URL: http://www.racebooking.net/it/moto/app/get_post_test.php), which simply Echoes Alien contact SUCCESS!
I've made a simple html page in localhost (on my PC) called index.html with a div called #post-container and an AJAX request:
var root = "http://www.racebooking.net/it/moto"
$.get(root + "/app/get_post_test.php", function(data){
$("#posts-container").html(data);
});
If everything is correct, i expect to see Alien contact SUCCESS! in the post-content div.
What happens looks strange:
If i run the app from eclipse using Genymotion, everything works fine
and i see the message Alien contact SUCCESS! -> the AJAX request
went fine
If i open the index.html file on firefox, i don't see anything
and FireBug informs me that the cross-origin request was blocked.
He also tells me to activate CORS.
1) Why is that happening and how can i make FireBug work (which is better and faster for debugging)?
2) Am i following the right procedure or i am missing something?
I found the solution from this post.
I just needed to add header('Access-Control-Allow-Origin: *'); at the top of my php file.

Localhost returns 404.3 when fetching json through ajax (Windows 8.1)

So I have been getting the infamous 404.3 error when trying to use AXAJ to access a .json file launching the site (or more of a test app hehe) through WebMatrix on localhost.
Yes, I am aware of the IIS configuration. I am on Windows 8.1(x64), so I had to even turn on MIME types functionality separately. I configured a MIME type for .json with application/javascript. Then I went and added a handler to *.json, pointed it to C:\WINDOWS\system32\inetsrv\asp.dll. I set the verbs to GET and POST (those are what I use in my ajax function). I also tried unchecking the "Invoke the handler only if request is mapped to..." to no avail.
I am using one function to send data to PHP file which writes it to the JSON file and then another to fetch data from the JSON file directly. Writing through PHP works. Fetching doesn't. I am completely at a loss, does anyone have any ideas? The code I am using to fetch the data is your bog-standard ajax:
function getDate(path, callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText);
if (callback) callback(data);
}
}
};
httpRequest.open('GET', path);
httpRequest.send();
}
When I host this on my server space, it works totally fine. But I want to get it to work locally for testing purposes as well.
If writing to the file works but fetching doesn't work. Then you should check for the link of the file.
The error 404 as the name refers to, is an error for the file name. There isn't any other sort of error, even the Ajax request is working fine and giving the error 404 (file not found). So the only thing that you can do is, to make sure that while fetching the data, you use the correct link.
Here can be a help, when you send the Request through Ajax, there is a Network tab in your Browser's console. Open it, and look for the request. It would in red color denoting an error and click it. You'll see that the link you're providing isn't valid.
Look for the errors in the File Link then and update it.
The lengths I go to, to clean up my profile...
When you require a JSON format, or any file for that matter you have to specify in your request what data type you need, IIS will not make any assumptions. So
xhr.setRequestProperty('Content-Type', 'application/json');
is something one must not forget. I set also the X-Requested-With header. Note that to reproduce this issue I used IIS that is installed on Windows 10 Pro, so not exactly the same system (3 years later - holy crap!).

CodeIgniter redirect not working on a real Server

I'm having a problem with CI 2.1.3 redirect function.
Everytime I call redirect, it shows a white-blank page. In fact, it works well on my localhost, the problem just occurs on my real server (with CentOS 5 installed).
This is how I call the redirects :
redirect('frontend/article/index');
or
redirect(base_url('articles.html'));
I did add a route in config/routes.php
$route['articles.html'] = 'frontend/article/index';
with : frontend is module, article is controller, and index is action (I'm using wiredesignz's HMVC module extension)
How could I fix it? And what is the problem here?
Thanks in advance!
UPDATE
I replaced CI redirect function by calling :
header("Location: http://example.com");
but it didn't work too.
So I created a file named info.php and uploaded it to my server. Here's the content:
<?php
phpinfo();
?>
When I type in the address bar : http://example.com/info.php, it shows like in the image.
Why was there a ">" character? Was it the problem causing redirect not working?
Firstly, make sure error reporting is enabled, or try placing the following at the top of your index.php.
error_reporting(E_ALL | E_WARNING | E_NOTICE);
ini_set('display_errors', TRUE);
If this doesn't point you in the right direction make sure you don't have any output echo, print_r, print, dump, etc before your call to redirect() method.
Another common cause or problems when moving to a new environment is white space. Check that your files don't have any whitespace at the bottom of them.
if you are defining .html in the config.php as the file ext. you do not need to postfix the route with it.
$route['articles'] //instead of $route['articles.html']
Also you need to remove the base_url() from the redirect cos that is not needed.
redirect('articles'); //should sort it
Hope this sorts ur problems.
EDIT
If this is still not working after attempting these changes, it will most likely be a problem in the controllers. If this is the case you may need to turn on error reporting in your index.php file to find out exactly where the problem is occurring.

Loading a JSON file in Firefox Addon Page Script, everything locally within the package

I have been developing a Firefox extension using the Addon SDK and need to load some data that is stored in the same package, as a separate file: "data.json". It needs to be loaded from a page script, i.e. "loader.js" which is included in the "panel.html" using the script src tags.
The structure is like this:
+data
panel.html
panel.js
loader.js
data.json
...
+lib
main.js
...
panel.html has:
<script type="text/javascript" src="loader.js"></script>
Initially we stored the data simply into a js file as "data.js" and included from the "panel.html" using script src tags and it worked without any problems. However when we submitted the add-on to the Mozilla Addon site, this was addressed as one of the issues to fix, saying that we need to use a non-executable format, such as a JSON file to make it more safe.
Now the problem seems like "loader.js" is not allowed to make a AJAX request to "data.json". (Using the JQuery $.ajax() call returns with no success, giving the error code 0) So the solution I have been thinking of is to load "data.json" from "main.js" using the SDK's request() function and somehow pass it to the "loader.js", the page script. But that seems to be complicated since, as far as I understand, the data needs to be first sent to a content script, and then from there to the page script. And this needs to be happen when the page script is loading! I am confused about this since I am not sure if I am missing a much more practical solution, or is it really something complicated what I am trying to do, simply loading local JSON data in the package into a local page script?
Here's an example on the Add-on Builder that explores and approach to this.
First off, you can load the json file from data and parse it using self.data.load:
let data = require('self').data;
let taps_data = JSON.parse(data.load('taps.json'));
This loads synchronously, so it isn't something you want to do often, in the example it would only happen when the add-on firsst becomes active in a browsing session.
Next, you would use content scripts and message passing to pass the data in to the panel.
In the main.js script:
panel.on('show', function() {
if (!loaded)
panel.port.emit('taps-data', taps_data);
});
In the content script:
self.port.on('taps-data', function(data) {
$('#list').html('');
data.forEach(function(item) {
$('#list').append('<div>'+ item.name +'</div>');
});
self.port.emit('taps-loaded');
});
I do a bit of extra work to make sure I'm only emitting the data once. The data, FYI, is saved from the live beer keg data api from my local pub.

Resources