I am a "first-timer" and "self-taught" but have found stackoverflow invaluable in researching innumerable other questions, however I am stymied on this one. I am sure the solution is simple and can be handled in a number of ways. Apologies if I did not format or pose the question properly.
HTML
<div id="message">
<a id="date" href="ajax1.php?postreply=1368479602">Topic</a>
</div>
JQuery
ahref="";
timestamp="";
time="";
$(document).ready(function(){
$('a').click(function(){
ahref = $(this).attr('href');
timestamp = ahref.split('=');
time = timestamp[1];
alert(time); //this works
})
alert(time) //this does not work
$.post('ajaxpost.php', {'timestamp' : time} , function(result) {;
alert(result);
})
})
</script>
I am able to parse href into an array and and set the second value in the array to the time variable, however I can't pass that variable to the post request. The post request works but only when I set the variable outside of the click event. I researched other posts here, and I thought the answer would be the use of global variables, even though I now understand that is not good practice, but that does not seem to be the solution although maybe I am not declaring the variables correctly.
Move the Ajax request to inside the click event..
$(document).ready(function () {
$('a').click(function () {
ahref = $(this).attr('href');
timestamp = ahref.split('=');
time = timestamp[1];
$.post('ajaxpost.php', {
'timestamp': time
}, function (result) {;
alert(result);
})
})
alert(time); //this works
})
The alert which does not work runs, when the page loads for the first time when it is empty. But you are assigning the value to it when you click event is fired.
So you need to move the Request to inside the Click event so that the correct value of time is passed to the request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With