JS: Changing variable wont apply on next - javascript

I have this:
$('#albumPhotoNext').live('click', function () {
var currentDate = '<?php echo $grab["date"]; ?>';
$.ajax({
url: "photo.php",
type: "post",
data: { currentDate : currentDate },
success: function(r){
currentDate = r.date;
}
});
});
I want to set currentDate for the r.date, on success, so next time you click on #albumPhotoNext, the currentDate is the r.date.
Right now it gives me the $grab["date"]; when i click, no matter if i did set the currentDate to r.date or not.
I only want to have $grab["date"]; as "default" if it hasnt been set to r.date
How can I do this?

currentDate is a local variable, so its value gets reset every invocation.
You will need to make the variable exist in an outer scope for your changes to persist.
The easy way of doing this:
$(function() {
var currentDate = '<?php echo $grab["date"]; ?>';
$('#albumPhotoNext').live('click', function () {
$.ajax({
url: "photo.php",
type: "post",
data: { 'currentDate' : currentDate },
success: function(r){
currentDate = r.date;
}
});
});
});

You have to define currentDate in a scope that is reachable from the scope you want to use it. Currently, currentDate is local to the event handler, so only the code inside the event handler can see the value and it gets reassigned to $grab["date"] every time the handler is called.
Define it in some scope above, e.g. in the document ready handler:
$(function() {
var currentDate = '<?php echo $grab["date"]; ?>';
$('#albumPhotoNext').live('click', function () {
$.ajax({
url: "photo.php",
type: "post",
data: { currentDate : currentDate },
success: function(r){
currentDate = r.date;
}
});
});
});

I would approach this in a slightly different way. Instead of assigning "currentDate" to a variable, just use another jQuery selector to set the current date on the page itself.
$.('#albumPhotoNext').live('click', function () {
$.ajax({
url: "photo.php",
type: "post",
data: { currentDate : currentDate },
success: function(r){
$.('#dateOnPage').html(r.date);
}
});
});

Related

How to attach javascript to a font awesome icon

I have a fontawesome icon in my HTML as a button and i'd like to use javascript and trigger it AJAX style
<i id="heart" class="jam jam-heart-f"></i> Like
Here is the attempt at javascript to trigger it - but I dont get any errors to follow up on. I try to post the like attempt to a PHP page like.php to add the link to a database.
$(document).ready(function()
{
$('body').on("click",'#heart',function()
{
var videoId = "<?php echo $video_id; ?>";
var A=$(this).attr("id");
var B=A.split("like");
var messageID=B[1];
var C=parseInt($("#likeCount"+messageID).html());
$.ajax({
method: 'POST',
url: 'like.php',
data: {videoId: videoId},
cache: false,
success: function(result){
likeInfo = JSON.parse(result);
$("#likeCount1").html("Likes:" + likeInfo.likeCount);
//document.getElementById("likeCount1").value = likeInfo.likeCount;
//$("#likeCount1").html(likeCount);
}
});
}
});
I dont think #heart seems to be triggered in JS by the id="heart" with the font awesome icon. Any ideas how I can rig this together
You forgot to add closing parenthesis and semicolon for your $('body').on... statement
Try this:
$(document).ready(function()
{
$('body').on("click",'#heart',function()
{
var videoId = "<?php echo $video_id; ?>";
var A=$(this).attr("id");
var B=A.split("like");
var messageID=B[1];
var C=parseInt($("#likeCount"+messageID).html());
$.ajax({
method: 'POST',
url: 'like.php',
data: {videoId: videoId},
cache: false,
success: function(result){
likeInfo = JSON.parse(result);
$("#likeCount1").html("Likes:" + likeInfo.likeCount);
//document.getElementById("likeCount1").value = likeInfo.likeCount;
//$("#likeCount1").html(likeCount);
}
});
});
});
Your code triggers the post-request correctly, but you are not closing your functions and scopes correctly.
I tried it out here:
http://jsfiddle.net/4cohrz5p/
And code to keep stackoverflow happy:
$(document).ready(function() {
$('body').on("click", '#heart', function() {
var videoId = "<?php echo $video_id; ?>";
var A = $(this).attr("id");
var B = A.split("like");
var messageID = B[1];
var C = parseInt($("#likeCount" + messageID).html());
$.ajax({
method: 'POST',
url: 'like.php',
data: {
videoId: videoId
},
cache: false,
success: function(result) {
likeInfo = JSON.parse(result);
$("#likeCount1").html("Likes:" + likeInfo.likeCount);
//document.getElementById("likeCount1").value = likeInfo.likeCount;
//$("#likeCount1").html(likeCount);
}
});
});
});
Besides, the javascript console shows Uncaught SyntaxError: missing ) after argument list for your code. And you open the network-tab when you click the heart to see outgoing requests and can inspect them to see that they send the correct data (and the response too!).
Any decent js editor would have shown this error before even running the code. Try VS Code. Free and lightweight and pretty great overall.

jQuery clearinterval / stopinterval doesn't work

I have an autorefresh function that gets called if a checkbox is checked and a button clicked. I want to stop the autorefresh when the checkbox is unclicked:
var refreshId = null;
$("#disINFRAlive").click(function(infralivefun) {
event.preventDefault(infralivefun);
var category_id = {};
category_id['datumanf'] = $("#datumanf").datepicker().val();
category_id['datumend'] = $("#datumend").datepicker().val();
$.ajax({ //create an ajax request to display.php
type: "POST",
url: "infratestomc.php?id=" + Math.random(),
dataType: "html",
data: category_id,
success: function(response) {
$("#resulttabelle").show().html(response);
}
});
if ($('#autorefcheck').is(':checked')) {
var refreshId = setInterval(function() {
var category_id = {};
category_id['datumanf'] = $("#datumanf").datepicker().val();
category_id['datumend'] = $("#datumend").datepicker().val();
$.ajax({ //create an ajax request to display.php
type: "POST",
url: "infratestomc.php?id=" + Math.random(),
dataType: "html",
data: category_id,
success: function(response) {
$("#resulttabelle").show().html(response);
}
});
}, 5000);
}
});
The autorefresh works if the checkbox #autorefcheck is checked and the button #disINFRAlive is clicked. However, I can't make it stop by unchecking the checkbox:
function stopinterval(){
clearInterval(refreshId);
return false;
}
$('#autorefcheck').click(function() {
stopinterval();
});
I tried to use clearInterval in various ways and none worked so far.
Remove the var keyword from the initialization of refreshId.
if ($('#autorefcheck').is(':checked')) {
refreshId = setInterval(function() {
The way you have it, you are redeclaring the variable in a different scope. That way, you cannot access it from stopInterval().

Set the function itself to the url in AJAX?

I am new to AJAX. Recently, I read a block of code that set url to the function itself. In this case, it is get Path. Normally, we will set url to other pages to get data or something. I do not know what it means to set url to the calling function itself. Could you help answer my question?
<script type="text/javascript">
function getPath()
{
var startLat = $('#startLat').val();
var startLng = $('#startLng').val();
var desLat = $('#desLat').val();
var desLng = $('#desLng').val();
var departure = $('#departure').val();
$.ajax({
type: "POST",
url: "getPath",
dataType: "json",
data: { "startLat": startLat, "startLng": startLng, "desLat": desLat, "desLng": desLng, "departure": departure},
success: function (response) {
if(response.success) {
$('#result').val(response.data);
console.log('Reponse.success is true');
}
else {
console.log('Response.success is false');
}
},
error: function(e) {
}
});
}
</script>
function getPath() <-- function
url: "getPath", <-- string
They are not related. Only thing in common is the developer had the same name. The page will post to some location called getPath on the server.
It doesn't mean anything other than the fact that the url the POST request is being sent to happens to be "getPath". The function is probably named according to the route name on the server side, but renaming that function (and updating every place it is called accordingly) would have no effect, and you would have to leave the url: "getPath" as is. Changing that part would likely break something.
That getPath would be a relative url, so the request goes to something like: http://example.com/path/to/parent/of/current/page/getPath
suppose your HTML input URL
<input type="url" id="web_url" value=""></input>
Then you can get your URL
<script type="text/javascript">
function getPath()
{
var startLat = $('#startLat').val();
var startLng = $('#startLng').val();
var desLat = $('#desLat').val();
var desLng = $('#desLng').val();
var departure = $('#departure').val();
var url = $('#web_url').val(); // getting input URL by User
$.ajax({
type: "POST",
url:url ,
dataType: "json",
data: { "startLat": startLat, "startLng": startLng, "desLat": desLat, "desLng": desLng, "departure": departure},
success: function (response) {
if(response.success) {
$('#result').val(response.data);
console.log('Reponse.success is true');
}
else {
console.log('Response.success is false');
}
},
error: function(e) {
}
});
}
</script>

How to check json response taken longer than 5 seconds?

Below is the sample code of my function. in the for loop one by one product id is pass in the ajax function and get product price from the php file as response and write it and html.
for(var i=0; i < data.products.length; i++){
var doc = data.products[i];
$.ajax({ // ajax call starts
url: 'product.php',
data: { product_id: doc.id },
dataType: 'json',
success: function(data)
{
document.getElementById('price_price'+data.product_id+'').innerHTML = data.products_price;
}
});
}
I have found that sometimes it takes a more time for price to display. i want to check which record is taking time to load. how can check to detect when it takes longer than 5 seconds for the price to load?
Something like this....
var ajaxTime= new Date().getTime();
$.ajax({
type: "POST",
url: "some.php",
}).done(function () {
var totalTime = new Date().getTime()-ajaxTime;
// Here I want to get the how long it took to load some.php and use it further
});
Also, by the way, if you want to prevent sending (i+1) request, before (i) is completed, you'd maybe want to use syncronous ajax request instead of async.
Try to log timestamp beforesend and success or error
$.ajax({ // ajax call starts
url: 'product.php',
data: { product_id: doc.id },
dataType: 'json',
beforeSend: function() {
console.log(new Date().getSeconds());
}
success: function(data)
{
console.log(new Date().getSeconds());
document.getElementById('price_price'+data.product_id+'').innerHTML = data.products_price;
}
});
Use setTimeout, like this:
var timeoutTimer = setTimeout(function() {
// time out!!!.
}, 5000);
$.ajax({ // ajax call starts
url : 'product.php',
data : {
product_id : doc.id
},
dataType : 'json',
success : function(data) {
document.getElementById('price_price' + data.product_id + '').innerHTML = data.products_price;
},
complete : function() {
//it's back
clearTimeout(timeoutTimer);
}
});

Select previous "this" element

I have a piece of javascript code where I am trying to get to the previous element declared. Currently I have two onclick functions within eachother.
$('#formIngredient').on("click", '.newIngredient', function() {
value = $(this).attr('data-name');
$(this).attr('data-isactive', 'true');
$('#newIngredientInput').val(value);
$('#newIngredient').modal('show')
$('#createNewIngredient').click(function() {
inputName = $('#newIngredientInput').val();
inputCategory = $('#newIngredientCategory').val();
var newIngredient = $.ajax({
type: "GET",
url: '/content/includes/ajax/createNewIngredient.php',
data: {name: inputName, id_category: inputCategory}
});
newIngredient.done(function(result) {
//PAI.showPage(PAI['PAGE']);
$(this).parent().replaceWith('Hello');
$('#newIngredient').modal('hide');
});
});
});
I am trying to use the previous element with this code.
$(this).parent().replaceWith('Hello');
Any ideas?
The scope of $(this) seems to be your issue here... you need to correct your code.
$('#createNewIngredient').click(function() {
var self = this; // This is the #createNewIngredient element
inputName = $('#newIngredientInput').val();
inputCategory = $('#newIngredientCategory').val();
var newIngredient = $.ajax({
type: "GET",
url: '/content/includes/ajax/createNewIngredient.php',
data: {name: inputName, id_category: inputCategory}
});
newIngredient.done(function(result) {
//PAI.showPage(PAI['PAGE']);
// $(this).parent().replaceWith('Hello'); // $(this) scope is lost to current function... so
$(self).parent().replaceWith('Hello'); // This is now the scope you need
$('#newIngredient').modal('hide');
});
});
Use the below code:
$(this).parent().prev().replaceWith('Hello');
I'll pass about your code logic (nested click events), but your problem seems to by about 'this' reference (scoping):
var self = this;
var newIngredient = $.ajax({
type: "GET",
url: '/content/includes/ajax/createNewIngredient.php',
data: {name: inputName, id_category: inputCategory}
});
newIngredient.done(function(result) {
//PAI.showPage(PAI['PAGE']);
$(self ).parent().replaceWith('Hello');
$('#newIngredient').modal('hide');
});
This was the simplest way, but better would be to use closure:
(function(self){
var newIngredient = $.ajax({
type: "GET",
url: '/content/includes/ajax/createNewIngredient.php',
data: {name: inputName, id_category: inputCategory}
});
newIngredient.done(function(result) {
//PAI.showPage(PAI['PAGE']);
$(self ).parent().replaceWith('Hello');
$('#newIngredient').modal('hide');
});
})(this);

Categories

Resources