I want to show the Facebook "Like box" plugin and some other FB code in a ajax loaded page.
When I load it in a ordinary html page it works as it should, but when I try to put it in a ajax load page it only loads the first time, when I click on the link to load the page the second time it is not loading the page? It is only loading the page if I clear the cache.
The index file init the fb code.
FB.init({
appId : '277065222', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true
});
I load the ajax page with this code:
function loadFacebook(){
$('#container').load('http://www.manmade.se/manmade/guiden/facebook_onweb.html');
FB.XFBML.parse();
}
And in the ajax loaded page I have the facebook code, eg the facebook Like box.
you can call fb par script in your page load after calling fb script
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=11111code";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
$(document).ajaxComplete(function () {
try {
FB.XFBML.parse();
} catch (ex) { }
});
reloadlike.html
<div class="fb-like fltLeft" data-href="http://yrl_like" data-send="false" data-layout="button_count" data-width="87" data-show-faces="false"></div>
this should work every time.
I guess your callback is not right.
$('#container').load('reloadlike.html', function() {
FB.XFBML.parse();
});
Varying a little bit the example code from bugrasitemkar, at the end of the ajax code, I include this jquery script and it works:
<script type="text/javascript">
$(document).ready(function() {
try {
FB.XFBML.parse();
} catch (ex) { }
});
</script>
Related
I am porting an application to WordPress. It uses a form to select what attributes the customer is looking for in an Adult Family Home via checkboxes and drop-downs. It re-searches the database on each onchange and keyup. Originally I had the application standalone in PHP, but when I migrated it to WordPress I started having issues.
Currently in WP I have the code conditionalized ($DavesWay == 1) to do ajax the normal no-WordPress-way and ($DavesWay == 0) to do it the WordPress-way.
In the non-WordPress-way, the ajax works fine EXCEPT that I get a WP header and menu between the search form and the results-div that Ajax puts the data in. I get no errors from WP or in the JS console. In the WP-way The search form displayed, but nothing happens when I check any of the checkboxes. The JS console displays
POST http://localhost/demo4/wp-admin/admin-ajax.php 400 (Bad Request)
But I don't see any way to tell exactly what it is complaining about. How should I troubleshoot this?
Troubleshooting = Examine the HTML output, lots of echos and exits in PHP code, look at JS console.
function submitPg1(theForm) {
// Used with onChange from "most" form elements, but not on those that change the page
// rather than the select criteria. Such as rowsPerPage, pageNumber etc.
setById("pageNo", "1"); // set inital page
mySubmit();
}
function mySubmit(theForm) { // The actual ajax submit
// DO NOT set page number
jQuery.ajax({ // create an AJAX call...
data: jQuery("#asi_search_form").serialize(), // get the form data
type: jQuery("#asi_search_form").attr("method"), // GET or POST
url: jQuery("#asi_search_form").attr("action"), // the file to call
success: function (response) { // on success..
jQuery("#result").html(response); // update the DIV
}
})
}
function setById(id, value) { // Used to set vales by Id
x = document.getElementById(id).value;
x.value = value;
}
// 1st submit with blank selection
jQuery(document).ready(function () { submitPg1(this.form) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Code fragments: (from the displayed page source)
<div id="asi_container" class="asi_container" >
<noscript><h2>This site requires Javascript and cookies to function. See the Help page for how to enable them.</h2></noscript>
<div id="searchForm">
<form id="asi_search_form" name="asi_search_form" method="post" action="http://localhost/demo4/wp-admin/admin-ajax.php">
<input type="hidden" name="action" value="asi_LTCfetchAll_ajax" style="display: none; visibility: hidden; opacity: 0;">
<table id="greenTable" class="asi_table" title="The Green areas are for site administration, not typical users">
<tbody>
PHP code:
$DavesWay = 0;
if ($DavesWay == 1){ //echo "Daves Way Setup"; // Dave's way, which works but prints the menu twice
if( $operation == "submit"){
require("asi_LTCfetchAll.php"); // for each onchange or onkeyup
}else{
add_filter( 'the_content', 'asi_tc_admin', '12' ); // Initial page refresh # must be >12
}
}else{
// The WordPress way that I could't get to work -- asi_LTCfetch never gets called
function asi_LTCfetchAll_ajax(){
//echo "<br /> Goto to Submit function"; // DEBUG
require($asi_plugin_dir . "/includes" . '/asi_LTCfetchAll.php');
}
add_action( "wp_ajax_asi_LTCfetchAll_ajax", "asi_LTCfetchAll_ajax" ); // admin users
add_action( "wp_ajax_nopriv_asi_LTCfetchAll_ajax", "asi_LTCfetchAll_ajax" ); // non-logged in users
add_filter( "the_content", "asi_tc_admin", "12" ); // Initial page refresh # must be >12
}
Try changing the JavaScript to the way WordPress recommends it in their documentation:
var data = {
'action': 'my_action',
'whatever': 1234
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
I suggest trying following URL: https://codex.wordpress.org/AJAX_in_Plugins
Also you can use the plugin: https://wordpress.org/plugins/ajax-search-lite/
I have a codeigniter project where data is fetched from the database and shown in a tabular form in a view inside a div. The div is auto refreshed using ajax every 5 seconds.
The problem I am facing is after about 2-5 minutes, the browser starts to lag, and hangs. I have to then force quit my browser, clean up my memory to bring the system back to normal.
My Controller code
function view_data()
{
$this->load->model('site');
$data['list'] = $this->site->get_data()
$this->load->view('data',$data);
}
Model Code
function get_data()
{
$query = $this->db->get('data');
return $query->result_array();
}
View Code
<script>
var auto_refresh = setInterval(
function()
{
$.ajaxSetup({ cache: false });
$('#loaddiv').empty().load(window.location.href);
}, 1000);
</script>
<body>
<div id="loaddiv"><table>.....DATA...</table></div>
im really breaking my head with this one, so i hope anyone can take a look and help.
Im buildinf ajax-ed web page with pushState and fb comments. The problem is, that whenever i load new content and fb comments, i get an error about setting the href attribute.
Here is the code:
First, i async call fb init:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'MY_APP_ID',
channelUrl : 'http://promplac.si/channel.php',
status : true,
cookie : true,
xfbml : true
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +'//connect.facebook.net/en_US/all.js';document.getElementById('fb-root').appendChild(e);
}());
</script>
On content change i call:
<script>
function showComment($currentUrl) {
document.getElementById('theplace').innerHTML='<fb:comments id="fbcomment" href="'+document.URL+'" width="510" num_posts="3"></fb:comments>';
console.log(document.getElementById('theplace').innerHTML);
FB.XFBML.parse();
console.log(document.getElementById('theplace').innerHTML);
}
</script>
HTML:
<div id="theplace" class="fb-comments"><fb:comments href="" numposts='3' height='150' id="fbcomment" width="510" num_posts="3"></fb:comments></div>
I made an example, i put in console.log the html for comments before and after FB.XFBML.parse() call. As you can see on this example: http://promplac.si/nagradne-igre/nagradna-igra/izberi-oblacila-v-vrednosti-200EUR/
The comments are normaly shown, but when you click on any other entry i get the warning about setting href attribute. But if you check the console, the href attribute is totaly OK? The effect doesnt happen when there is at least one comment...
Any idea what is wrong?
I appreciate any and all help. I am a beginner with little jQuery/AJAX experience and I have been going crazy trying to figure out why I can't figure this out.
I'm writing a Facebook page application that has the user grant permissions and upload a video to the page. All of this works fine and dandy. This is not so much a Facebook API related issue as it is an ajax issue (at least I think).
Basically, I am trying to gain control of the page IN SOME WAY after the user uploads a video. I am using the [malsup jQuery Form Plugin][1] to have the resulting page (which is a page on Facebook displaying returned JSON values) load in a hidden iframe.
I am able to get ajaxStart to fire, and I've tested this by having it change the background color or print an alert message when I click "Upload". However, when the upload completes (and it does complete successfully), NOTHING ELSE HAPPENS. The returned JSON values load in the hidden iframe and the page sits there. I have tried getting ajaxComplete, ajaxStop and ajaxSuccess to fire, but none of them do for whatever reason.
So overall, here is what I am trying to accomplish:
- I want to redirect the user or make some hidden content appear after the file upload completes. I don't even care if there's errors. I just need SOMETHING to happen.
- I am using the jQuery Form Plugin because I am not unfortunately not advanced enough to figure out how to use that value and do something with it, but if anyone can steer me in the right direction, that would be appreciated.
And finally, here is my code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.js"></script>
<script type="text/javascript" src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
target: '#output2', // target element(s) to be updated with server response
iframeTarget: '#output2',
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
};
// bind form using 'ajaxForm'
$('#theform').ajaxForm(options);
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
return true;
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
alert(responseText);
}
</script>
<script type="text/javascript">
jQuery().ready(function(){
$('body').ajaxStart(function() {
$(this).css("background-color","red");
});
$('body').ajaxSend(function() {
$(this).css("background-color","blue");
});
$('body').ajaxComplete(function() {
$(this).css("background-color","green");
});
$('body').ajaxStop(function() {
$(this).css("background-color","purple");
});
});
</script>
</head>
<body>
<?php
$app_id = "xxxxxxx";
$app_secret = "xxxxx";
$my_url = "xxxxxx";
$video_title = "xxxxxxxxx";
$video_desc = "xxxxxxxxx";
$page_id = "xxxxxxxx";
$code = $_REQUEST["code"];
if(empty($code)) {
// Get permission from the user to publish to their page.
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&display=popup&scope=email,publish_stream,manage_pages";
$current_url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($current_url != $dialog_url)
{
echo('<script>window.location ="' . $dialog_url . '";</script>');
}
} else {
// Get access token for the user, so we can GET /me/accounts
$token_url = "https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code;
$access_token = file_get_contents($token_url);
$accounts_url = "https://graph.facebook.com/me/accounts?" . $access_token;
$response = file_get_contents($accounts_url);
// Parse the return value and get the array of accounts we have
// access to. This is returned in the data[] array.
$resp_obj = json_decode($response,true);
$accounts = $resp_obj['data'];
// Find the access token for the page to which we want to post the video.
foreach($accounts as $account) {
if($account['id'] == $page_id) {
$access_token = $account['access_token'];
break;
}
}
// Using the page access token from above, create the POST action
// that our form will use to upload the video.
$post_url = "https://graph-video.facebook.com/" . $page_id . "/videos?"
. "title=" . $video_title. "&description=" . $video_desc
. "&access_token=". $access_token;
// Create a simple form
echo '<form action=" '.$post_url.' " method="POST" enctype="multipart/form-data" id="theform">';
echo 'Please choose a file:';
echo '<input name="file" type="file">';
echo '<input type="submit" value="Upload" id="button-upload" />';
echo '</form>';
}
?>
<iframe id="output2" name="output2"></iframe>
</body></html>
Thank you for your help!!
It seams you are getting an Ajax Error. I don't see any error handler in your code. Could you try to add an error handler as follows
<script>
$(document).ready(function(){
$(document).ajaxError(function(e, jqxhr, settings, exception) {
alert(exception);
})
})
</script>
I have played around with file uploads, and there are a complicated beast because of all the security that browsers have for protecting users file systems and whatnot.
On to your problem, I think that there is a good chance that your AjaxForm jQuery plugin doesn't connect properly to the global Ajax state for Jquery. Even if it did, I would say that tapping into the global Ajax state is a bad design. If you add any other ajax requests to this page, then your ajaxComplete, ajaxStop, etc. functions are going to start getting called.
Your better approach is to use the callbacks provided by the AjaxForm plugin. Lets focus on this first part of your code.
Does this work?
success: showResponse // post-submit callback
...
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
alert(responseText);
}
If so, could you replace this:
$('body').ajaxComplete(function() {
$(this).css("background-color","green");
});
With this:
function showResponse(responseText, statusText, xhr, $form) {
$(this).css("background-color","green");
}
I believe that using the success: callback is the intended use of the AjaxForm plugin.
The jquery ajaxSend or ajaxStart throws some kind of an error and the document does not execute ajaxComplete. I tried to fix the bug for quite a while and was only able to find a workaround:
function hideAjaxIndicator() {
$('#ajax-indicator').hide();
}
$(document).ready(function () {
setTimeout(hideAjaxIndicator, 1000);
});
You can add this to .js file.
I would like to use javascript (JQuery) to ask the server for XFBML code via ajax.
The XFBML code will then attached to the DOM.
Here it is the php code:
echo "
<fb:serverFbml>
<script type=text/fbml'>
<fb:fbml>
<fb:request-form
action='http://myserver.com/invited.php'
method='post'
type='myserver'
invite='true'
content='yo you...'>
<fb:request-form-submit uid=12312312label='Send to %n ' import_external_friends=false />
</fb:request-form>
</fb:fbml>
</script>
</fb:serverFbml>
";
and here is the javascript:
function clickME() {
$.ajax(
{
url:'http://myserver.com/fbml_ajax.php',
success:attachData,
type:'GET',
dataType:'html',
global:false
}
);
}
function attachData(data) {
var myData = data;
$('#attachnow').html(data);
}
I can't make it work.. it is not attached.
If I just put the XFBML staticly on the HTML page, it works. but if I attach to DOM it doesn't.
Is it because of the tag? or is it because of the data that contains \r\n when return from from server?
You need to use FB.XFBML.parse on any new content. FBML is only parsed on page load by default. According to the second example in the page I linked, the exact code would be
FB.XFBML.parse(document.getElementById('attachnow'));
added as the last line of your attachData function.