Pages loaded by AJAX from the PHP back-end - javascript

What I'm tring to do is to load information from different pages, without having to refresh the whole main page...
Could you tell me how to adapt this code for loading files with different names (like about.html and project.html?
Note: this code is made just for loading 'page_.html' files.
var default_content="";
$(document).ready(function(){
checkURL();
$('ul li a').click(function (e){
checkURL(this.hash);
});
default_content = $('#pageContent').html();
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
if(hash=="")
$('#pageContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url)
{
url=url.replace('#page','');
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
$('#loading').css('visibility','hidden');
}
}
});
}
Here is the php file:
if(!$_POST['page']) die("0");
$page = (int)$_POST['page'];
if(file_exists('pages/page_'.$page.'.html'))
echo file_get_contents('pages/page_'.$page.'.html');
else echo 'There is no such page!';

You can make multiple ajax requests this is the jquery load method:
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});
do that 2x and your well off!
Keep in mind for this to work you'll need the jquery library.
I was doing a similar thing on my site here is my code:
window.setInterval("check()",60000);
//request information notice is inside a function called check() (it's not required to put inside function I only do this if I will be making the same request multiple time throughout the program)
function check() {
var request = $.ajax({
url: "file.php",
type: "POST",
dataType: "html"
});
request.done(function(msg) {
//when request is done:
$(".wheretoputnewdata").html(msg);
});
request.fail(function(jqXHR, textStatus) {
//if request failed do this:
alert( "Request failed: " + textStatus );
});
}

Replace this line
if(file_exists('pages/page_'.$page.'.html'))
with this
if(file_exists('pages/'.$page.'.html'))

Related

html() not updated before alert() is shown

I've got a problem since I've migrated from jQuery 1.11 to jQuery 3.0. I'm running a jQuery POST request and before the migration it first finished the html(data.responseText) and then moved on with the code that follows. Like this:
$.ajax({
type: "POST",
url: "/files/" + url,
data: $("#entryForm").serialize() + '&journal_id=' + journalId,
complete: function(data) {
$('#saveResults').html(data.responseText);
alert("function done");
}
});
In the data.responseText there is an alert which runs first and after complete the function html() the other alert("function done") was running.
After the migration the alert("function done") is running first so it appears the function html() is not finished at this point because the alert from the responseText is coming after the alert("function done"). So I tried this:
$.ajax({
type: "POST",
url: "/files/" + url,
data: $("#entryForm").serialize() + '&journal_id=' + journalId,
complete: function(data) {
$('#saveResults').html(data.responseText).promise().done(function() {
alert("function done");
});
}
});
Unfortunately this didn't fix my problem. Anyone an idea how to fix it?
Try this.
.html is set when response is back and when success is completed, complete is ran
success: function(data){
$('#saveResults').html(data.responseText);
},
complete: function(data)
{
alert("function done");
}

AJAX in WordPress only returns 0

I'm trying to utilize WordPress's admin-ajax feature in order to build a dynamic admin panel option-set for a plugin. Essentially, once an option is selected from a dropdown (select/option menu), PHP functions will sort through and display more dropdown menus that fall under the dropdown above it. I began with a simple return that I was hoping to utilize later down the line, but I can't seem to get the text to print out without running into unidentified issues.
The AJAX I set up puts out a 200 status but the response never builds, and I'm left with 0 as my result. Here's the code:
JS/jQuery built into PHP function ajax-action()
$ = jQuery;
$('#platform').change(function(e) {
var data = {
action: 'action_cb',
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl, data, function(data) {
$('#user_id').val(data);
});
e.preventDefault();
});
PHP functions and add-actions
add_action('wp_ajax_action_cb','action_cb');
add_action('admin_footer','ajax_action');
function action_cb() { $platform = 'test'; echo json_encode($platform); wp_die(); };
My question is: how can I fix this and prevent it from continuing to happen? I'd like to return the actual results and not 0.
As per the wordpress documentation:
https://codex.wordpress.org/AJAX_in_Plugins (Reference "Error Return Values")
A 0 is returned when the Wordpress action does not match a WordPress hook defined with add_action('wp_ajax_(action)',....)
Things to check:
Where are you defining your add_action('wp_ajax_action_cb','action_cb');?
Specifically, what portion of your plugin code?
Are you logged into wordpress? You mentioned the admin area, so I'm assuming so, but if you are not, you must use add_action('wp_ajax_nopriv_{action}', ....)
Additionally, you didn't share the function this is tied to:
add_action('admin_footer','ajax_action');
And lastly, why are you using "json" as the data type? If you are trying to echo straight HTML, change data type to 'html'. Then you can echo directly on to page (or as a value as you are doing). Currently, you are trying to echo a JSON object as a value in the form...
So your code would look like so:
function action_cb() { $platform = 'test'; echo $platform; p_die(); };
...and your AJAX could be:
<script type = "text/javascript">
jQuery.ajax({
url: ajaxurl,
type: 'post',
data: {'action' : 'action_cb'},
success: function (data) {
if (data != '0' && data != '-1') {
{YOUR SUCCESS CODE}
} else {
{ANY ERROR HANDLING}
}
},
dataType: 'html'
});
</script>
Try This:
<script>
$ = jQuery;
$('#platform').change(function(e) {
var data = {
data: {'action' : 'action_cb'},
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl, data, function(data) {
$('#user_id').val(data);
});
e.preventDefault();
});
</script>
Probably you need to add
add_action('wp_ajax_nopriv_action_cb', 'action_cb');
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
just make small change in your AJAX. I am assuming you're logged in as admin.
replace action in data object with data:"action=action_cb",
var data = {
data:"action=action_cb",
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl,data,function(data){
$('#user_id').val(data);
});
To prevent WP adding zero into response i always using die(); insted of wp_die();
and registering function:
add_action( 'wp_ajax_action_cb', 'action_cb_init' );
add_action( 'wp_ajax_nopriv_action_cb', 'action_cb_init' );
function action_cb_init() {
}
When calling to function with AJAX use action: 'action_cb'
Hope this helps. I have already explained standard way of using ajax in wp.
Wordpress: Passing data to a page using Ajax
Ok, I have been recreating your code now in my own project and noticed that the javascript you shared returned the ajax-object and not the results. So what I come up with is a bit rewriting, but is worked fine when I tried it.
$j = jQuery.noConflict();
$j('#platform').change(function(e) {
$j.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'action_cb',
}
}).done(function( data ) {
// When ajax-request is done.
if(data) {
$j('#user_id').val(data);
} else {
// If 0
}
}).fail(function(XMLHttpRequest, textStatus, errorThrown) {
// If ajax failed
console.log(errorThrown);
});
e.preventDefault();
});
I hope the comments explain good enough how it is working. Note how I'm using $j instead of just $ for the jQuery.noConflict mode.
For those by the "Load More" problem.
Normally "0" is used instead of false.
I found such a solution.
So that 0 does not come. Try this code with false.
PHP
ob_start(); // start the buffer to capture the output of the template
get_template_part('contents/content_general');
$getPosts[] = ob_get_contents(); // pass the output to variable
ob_end_clean(); // clear the buffer
if( $read == $articles->found_posts )
$getPosts[] = false;
JS
if( posts[i] == false )
$(".load_more_button").fadeOut();

Javascript method similar to php file_getcontents

Is there any mehtod similar to file_getcontents in javascript or jquery.
<?php $html = file_get_contents('http://m.uploadedit.com/b037/1405919727889.txt');
echo ($html);?>
This works fine but i dont want to use php i want to jquery or javascript i have tried this method
$(document).ready(function () {
$.ajax({
url:"http://m.uploadedit.com/b037/1405919727889.txt",
type: "Get",
success: function (data) {
alert(data)
}
});
});
But i get nothing. Any recommendations?
You cannot do cross domain requests, you need to setup a php proxy, like, create a php file in your server say get_contents.php,
$html = file_get_contents('http://m.uploadedit.com/b037/1405919727889.txt');
echo ($html);
and in jquery, access your php, as:
$(document).ready(function () {
$.ajax({
url:"http://your_server.com/get_contents.php",
type: "GET",
success: function (data) {
alert(data)
}
});
});
Javascript cant get content of a file, but as you can see, php can. What I suggest to you is to work with togeter
$(document).ready(function () {
$.ajax({
url:"http://m.uploadedit.com/content/somehash",
type: "Get",
success: function (data) {
alert(data)
}
});
});
And in '/content/somehash' put a php file:
<?php echo file_get_contents('http://m.uploadedit.com/content/somehash');
I suggest you to hide the real name of filename. If you expose information like that, what do you expect if some malicious user try to http://m.uploadedit.com/content/../../.htaccess (for example). The risk is to give too many information. And it's not a good idea.
Exists an alternative and its name is NodeJs:
fs.readFile('/content/somehash', function (err, data) {
if (err) throw err;
// here you can output the content ...
});
Here is a solution. I found this and working fine
$( document ).ready(function() {
$.ajaxPrefilter(function(options) {
if(options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
$.get(
'http://m.uploadedit.com/b037/1405919727889.txt',
function(response) {
$("#content").html(response);
alert(response);
});

How access data in JavaScript arrays using $.ajax

This is a script when the script is executed I want to load the data into the div of id #trial. The script is an external array with three names the second I am trying to call is 'sarah'. Whats wrong?
<script>
$(document).ready(function(){
$("#trial").click(function(){
var attempt=$.ajax({
url: "names.js",
dataType: "script"
});
var msg=names[1];
attempt.done(function( msg ) {
$( "#trial" ).html( msg );
});
});
});
</script>
Change your code to this:
<script>
$(document).ready(function(){
$("#trial").click(function(){
$.ajax({
url: "names.js",
dataType: "script",
success: function(res){
//todo something with res
}
});
});
});
</script>

ajax load image not working second time on popup jquery

I am working on site where i show fancybox for contact us form.i submit form using ajax.on process state i show ajax loading image.On first click it show the image but clicking again image doesn't show.My ajax code is this :
<script type="text/javascript">
function submitForm()
{
jQuery(".ajax-content").show();
var str = jQuery( "form" ).serialize();
jQuery.ajax({
type: "POST",
url: 'myurl',
data: str,
format: "json",
beforeSend: function( xhr ) { alert('hi'); jQuery(".ajax-content").show();},
success: function(data) {
var obj = JSON.parse(data);
if( obj[0] === 'error')
{
jQuery("#error").html(obj[1]);
jQuery(".loading-gif").hide();
}else{
jQuery(".loading-gif").hide();
jQuery("#result").html(obj[1]);
setTimeout(function () {
jQuery.fancybox.close();
}, 2500);
}
}
});
}
</script>
ajax-content class is that div contains ajax image
Any help or pointing to error will be appreciated.Thanks
I think the image is hidden the second time. Can you try
beforeSend: function( xhr ) {
alert('hi');
jQuery(".loading-gif").show();
jQuery(".ajax-content").show();
},

Categories