ajax doesn't update on first click - javascript

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

Related

Facebook share plugin button does not share the right url

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);
}
});
});

Load variable from URL

My example page url is http://example.com/itemurl/?23 where 23 is the item number.
On that page, I need to pull that 23 and make it a variable so I can append it to the url in an Ajax call to get an xml file:
Here is my script:
<script>
$(document).ready(function () {
$.ajax({
type: "Get",
url: "https://example.com/getxml/",
dataType: "xml",
success: xmlParser
});
});
function xmlParser(xml) {
$(xml).find("product").each(function () {
$(".prod_title").append('<h1>' + $(this).find("item_name").text() + '</h1><span>' + $(this).find("short_description").text() + '</span><ol class="breadcrumb"><li>Browse Products</li><li>Your Dashboard</li></ol>');
$(".category").append('<div class="cat">'+ $(this).find("category_name").text() +'<div>');
$(".product-rating").append('<i class="icon-star3">'+ $(this).find("no_of_units").text() +' Units Available</i>');
$(".product-price").append('<ins>ARV: $'+ $(this).find("item_price").text() +' </ins>');
$(".product-image").append('<img src="'+ $(this).find("image_url").text() +'" alt="example_product"/>');
$(".exp-date").append('<li><i class="icon-caret-right"></i> Expires On: '+ $(this).find("prod_exp").text() +'</li></div>');
$(".posted_in").append('Category: '+ $(this).find("category_name").text() );
$(".prod_description").append('<p>'+ $(this).find("full_description").text() +'</p>');
});
}</script>
I need the url in the script to be https://example.com/getxml/23 but I'm not sure how to accomplish this.
The line with url should look like this:
url: "https://example.com/getxml/"+window.location.search.substr(1),

detect which button has been clicked and submit with ajx

I need help getting a value of a clicked button and send this information using AJAX. the two scripts work individually. but i need the "buttonvalue" to be passed to AJAX "data" value "action". what i am using is below.
$("document").ready(function(){
$(".js-ajax-php-json").on("click", "button[name=mysqljob]", function (){
var buttonvalue = $(this).attr("value");
alert(buttonvalue);
});
$(".js-ajax-php-json").submit(function(){
var data = {"action": buttonvalue};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "phpVars/ajaxUpload.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html(
data["form"]
);
// alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
I would prevent the form from submitting do what you want then post the data via an ajax call. Try the following:
$("document").ready(function(){
$(".js-ajax-php-json").on("click", "button[name=mysqljob]", function (e){
e.preventDefault();
var buttonvalue = $(this).attr("value");
var data = {"action": buttonvalue, "formData": $(this).serialize() + "&" + $.param(data) };
$.ajax({
type: "POST",
dataType: "json",
url: "phpVars/ajaxUpload.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html(
data["form"]
);
// alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
Not tested.

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
});
}

$find doesn't work in external javascript file

I have a jQuery code that when click on a button in page, show some information (from database) in a asp:RadEditor.
My code work properly when it's inserted internally in page inside tag , but not working in .js file!
function setShowRow(btn, url) {
$.ajax({
type: "POST",
url: "../" + url + "/EditMessage_JQ",
data: "{ 'key':" + "'" + btn + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Data) {
if (Data.d[0] != null) {
$("#MainContent_TextBoxMain").val(Data.d[0]);
}
if (Data.d[1] != null) {
$find("#MainContent_TextRadEditorAbst").set_html(Data.d[1]);
}
if (Data.d[2] != null) {
$find("#MainContent_RadEditorText").set_html(Data.d[2]);
}
$("#insert").css("display", "none");
$("#DiveditBtn").css("display", "block");
$("#DivcancelBtn").css("display", "block");
}
});
}
$ is an object, so you have to use the dot-notation: $.find(...)

Categories