Facebook share plugin button does not share the right url - javascript

My production site can be found here: http://infinite-brushlands-3960.herokuapp.com/
I have the javascript SDK set up as instructed here: https://developers.facebook.com/docs/javascript/quickstart/v2.5
When the user clicks "Share This Schedule", this code is run:
$('#share_schedule').click(function(){
if ($('#share_url_ul').children().length >= 1){
$('#share_url_ul').empty();
}
// Take care of no classes case "You cannot share an empty schedule."
$.ajax({
method: "POST",
url: "/share/",
data: JSON.stringify(localStorage),
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function(response){
var shared_url = document.createElement('a');
$(shared_url).css('display', 'block');
$(shared_url).attr('href', window.location.href + 'shared/' + response);
$(shared_url).attr('id', 'share_link');
shared_url.innerHTML = window.location.href + 'shared/' + response;
$('#share_url_ul').append(shared_url);
$('#fb_share_btn').attr('data-href', window.location.href + 'shared/' + response);
},
error: function(error){
console.log(error);
}
});
});
But despite the line that sets the facebook button's data-href attribute to the url that I want to share (as described here https://developers.facebook.com/docs/plugins/share-button ), clicking the button still shares my home page to facebook instead of the link I specified there. Inspecting the button in the browser inspector show that it indeed has the correct url as the data-href attribute.
Why isn't the plugin sharing the correct url?

Since you are changing the button url on ajax load, you have to re-initialize the facebook share button after changing the attributes.
Try adding this to the end of success callback
FB.XFBML.parse();
So you should have something like
$('#share_schedule').click(function(){
if ($('#share_url_ul').children().length >= 1){
$('#share_url_ul').empty();
}
// Take care of no classes case "You cannot share an empty schedule."
$.ajax({
method: "POST",
url: "/share/",
data: JSON.stringify(localStorage),
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function(response){
var shared_url = document.createElement('a');
$(shared_url).css('display', 'block');
$(shared_url).attr('href', window.location.href + 'shared/' + response);
$(shared_url).attr('id', 'share_link');
shared_url.innerHTML = window.location.href + 'shared/' + response;
$('#share_url_ul').append(shared_url);
$('#fb_share_btn').attr('data-href', window.location.href + 'shared/' + response);
FB.XFBML.parse();
},
error: function(error){
console.log(error);
}
});
});

Related

Using pushState inside success function of ajax

I want to append one more param at the end of the current url if the ajax call returns successfully. In this context, we can get back the identifier of the object has been persisted into the database, then append this identifier to the url.
The problem is curationNotes of data was lost if the line window.history.pushState({}, null, newHref); is uncommented. It means we cannot get 'params.curationNotes' in controller. The params.curationNotes, which is a map of user provided values on the form, is null when we try to parse it inside the controller.
Below is the snippet I am working on.
$('#btnSave').on("click", function(event) {
if ($('#curationNotesForm')[0].checkValidity()) {
var curationNotes = buildCurationNotesTC();
"use strict";
event.preventDefault();
$.ajax({
dataType: "text",
type: "POST",
url: $.jummp.createLink("curationNotes", "doAddOrUpdate"),
cache: true,
data: {
curationNotes: curationNotes,
model: "${id}"
},
processData: true,
async: true,
beforeSend: function() {
$('#txtStatus').text("The curation notes are being saved. Please wait...");
},
success: function(response) {
var response = JSON.parse(response);
var href = window.location.href;
if (href.indexOf("&cnId=") < 0) {
var newHref = href + "&cnId=" + response['cnId'];
//window.history.pushState({}, null, newHref);
}
$('#txtStatus').text(response['message']);
},
error: function(jqXHR, textStatus, errorThrown) {
// TODO: the error message doesn't show properly
$('#txtStatus').text("Error: ", jqXHR.responseText + textStatus + errorThrown + JSON.stringify(jqXHR));
}
});
} else {
$('#txtStatus').text("Please check required fields and click Save button again...");
}
});
If I comment this line window.history.pushState({}, null, newHref);, the code is working properly.
Notes: this snippet works fine in any web browsers on Linux but cannot work in any web browser of Windows 10. That's actually ridiculous to me.
Have you ever had any experience with this problem?

How to correctly post data with ajax into div?

Script:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").ajax({
type: "POST",
url: "BlockEditor/build.php",
data: 'block_id=' + id + '&building=' + building + '&nick=' + nick,
cache: false,
success: function(response)
{
alert("Record successfully updated");
$.load("#BuildedBox")
}
});
}
build.php:
include_once("$_SERVER[DOCUMENT_ROOT]/db.php");
$block_id = $_GET['block'];
$building = $_GET['building'];
$nick = $_GET['nick'];
echo"$block_id - $building - $nick";
index.php:
<a href=\"#\" onClick=\"buttonBuild(k152, digger, Name);\" >[BUILD]</a>
<div id="BuildedBox"></div>
seems my script wont work. what i have done wrong?
check this out
function buttonBuild(id, building, nick)
{
$.ajax({
type: "POST",
url: "BlockEditor/build.php",
data: 'block_id=' + id + '&building=' + building + '&nick=' + nick,
cache: false,
success: function(response)
{
alert("Record successfully updated");
/***************/
$("#BuildedBox").html(response);
/***************/
}
});
}
var weightd = $("#weight").val();
var user_id = 43;
$.ajax({
type: "POST",
url:"<?php bloginfo('template_directory')?>/ajax/insert.php",
data: { weight:weightd,user_ids:user_id},
success:function(result){
$("#result1").html(result);
});
<div id="result1">Result div</div>
change $.load("#BuildedBox") to $("#BulderBox").html(response).
When you ask the script for data via ajax, the data provided gets into the "response" variable. As you want to write this data into the div, you must use the ".html" method.
Easier using "load" in this way:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").load("BlockEditor/build.php?block_id=" + id + "&building=" + building + "&nick=" + nick);
}
The "load" method loads data from the server and writes the result html into the element: https://api.jquery.com/load/
EDIT:
As #a-wolff says in the comment, to use POST in load, you should construct like this:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").load("BlockEditor/build.php",{
block_id:id,
building:building,
nick:nick
});
}

ajax doesn't update on first click

I have a problem with my code, it's a like button. It shows the number of likes. If user haven't voted yet (cookie) he can click and counter increases. Problem is counter doesn't update on first click (if i deactivate cookie check and vote several times) on next refresh is everything updated. It seems some count happens before insert in the backend. I suppose probem is in JavaScript, ajax post cross domain works but gives error that's why "error: setCookieAndUpdateButton()"
here is my frontend code:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<div><a id="like_button" href="#">Like</a></div>
<script>
var url = "http://thumbs-up.some-server.com/";
var appName = "next_test";
document.write("<script src=\"" + url + "jquery.cookie.js\"><\/script>");
$(document).ready(function(){
updateButton();
$("#like_button").click(function(){
if ($.cookie(appName + "_voted") == "true") {return;}
$.ajax({
type: "POST",
dataType: "json",
crossDomain: true,
url: url + "increase_counter.php",
data: {referrer: appName},
success: setCookieAndUpdateButton(),
error: setCookieAndUpdateButton()
});
});
});
function setCookieAndUpdateButton()
{
updateButton();
$.cookie(appName + "_voted", "true", {expires: 20*365});
}
function updateButton()
{
$.ajax({
type: "GET",
async: false,
contentType: "application/json",
dataType: "jsonp",
jsonpCallback: 'callback4jquery',
url: url + "get_counter_for_referrer.php",
data: {referrer: appName},
success: function (json) {
if ($.cookie(appName + "_voted") != "true"){
$("#like_button").html("<a id=\"like_button\" href=\"#\"><img src=\"" + url + "like.png\">Good to know " + json.count + "x</a>")
}
else{
$("#like_button").html("<span id=\"like_button\"><img src=\"" + url + "like.png\">Good to know " + json.count + "x</span>");
$('#like_button').unbind('click');
}
}
});
}
</script>
In first ajax call change your code like this:
success: setCookieAndUpdateButton,
error: setCookieAndUpdateButton
without () in both of them

jquery $ajax not working as expected

I Have to do a cross-domain request and fetch content from a url using $.ajax function.
But the below code only displays the first alert i.e alert(myUrl),
After that the execution stops.The second alert is not displayed. I don't know what is wrong with the code i have written.
Can somebody tell me what i am doing wrong here?Thanks in advance.
function getContentFromUrl(){
var myUrl="http://icant.co.uk";
alert(myUrl);
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" +
"q=select%20*%20from%20html%20where%20url%3D%22" +
encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: data,
success: function () {
alert("***********"+data.results[0]);
if (data.results[0]) {
var htmlText = data.results[0];
var jsonObject = parseAndConvertToJsonObj(htmlText);
} else {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
},
error: function() {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
});
}
Same Origin Policy:
The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.
You can't use regular JSON for cross-domain requests because of the same-origin policy. Instead, you'll need to use JSONP. In jQuery, you can do so like this:
$.ajax({
dataType: 'jsonp',
crossDomain: true
// other info
});
Note that there are security issues involved with JSONP. Only use JSONP if you trust the host domain.
I assume this is jQuery?
Try the following:
url = "http://query.yahooapis.com/v1/public/yql?" +"q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?";
getContentFromURL(url);
function getContentFromURL(url)
{
$.get(url, function (data) {
console.log(data);
});
}
If it dumps out to the console a response, you can build from there.
The data here is not defined
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" + "q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: data,
and you forget to add a param for the callback function
success: function (data) {
....
}
The finally code should like this
function getContentFromUrl() {
var myUrl = "http://icant.co.uk";
alert(myUrl);
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" + "q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: {},
success: function (data) {
alert("***********" + data.results[0]);
if (data.results[0]) {
var htmlText = data.results[0];
var jsonObject = parseAndConvertToJsonObj(htmlText);
} else {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
},
error: function () { document.getElementById("displayerrors").innerHTML = "Could not load the page."; }
});
}

Cross site HTTP authentication in JQuery

I want to see if it is possible to log into a third site that uses HTTP authentication. Ideally, the browser will store the credentials. Unfortunately this fails every time. Any help would be much appreciated, I'm using the base64 Jquery plugin, which I've tested to work.
So, two questions:
How can I view the HTTP status code?
Will this ultimately work, in principle?
<script>
$("#login_button").click(function() {
var username = 'myFunUsername';
var password = 'myFunPassword';
$.ajax({
url: 'http://remote-site-with-http-auth.com/member_site',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + $.base64.encode(username + ":" + password));
},
success: function(data) { $("#label").text("Logged in, yay!"); }
}).fail(function(){ $("#label").text("It didn't work"); });
});
Thanks!!
var user= 'myFunUsername';
var pwd= 'myFunPassword';
$.ajax({
url: 'http://remote-site-with-http-auth.com/member_site',
crossDomain:true,
username :user,// Keep the variable name different from parameter name to avoid confusion
password:pwd,
xhrFields: { /* YOUR XHR PARAMETERS HERE */}
beforeSend: function(xhr) {
// Set your headers
},
success: function(data, textStatus, xhr) {
alert(xhr.status);// The status code
//Code for success
}
}).fail(function(){
//Fail code here
});
For more details on parameters refer to http://api.jquery.com/jQuery.ajax/

Categories