I have the following code:
<script type="text/javascript">
$(document).ready(function(){
$('#writeReview').click(function(){
var id = $('.ajaxsend').attr('id');
var link = 'writereview/' + id;
console.log(id);
console.log('In the click');
})
$('.login_form').on('submit', function(e) {
$.post( 'writereview/' , $(this).serialize(), function(response) {
$("#login_message").html( response );
});
// disable default action
e.preventDefault();
});
});
</script>
How can I get the var link in the HREF for the post? The link starts always with writereview/
and then an ID. Anyone that can help me?
You need to define the variables in the right scope (so outside any functions) like this:
var id;
var link;
$(document).ready(function () {
$('#writeReview').click(function () {
id = $('.ajaxsend').attr('id');
link = 'writereview/' + id;
console.log(id);
console.log('In the click');
})
$('.login_form').on('submit', function (e) {
if (!link)
return;
$.post(link, $(this).serialize(), function (response) {
$("#login_message").html(response);
});
// disable default action
e.preventDefault();
});
});
So if you click the #writeReview
button first and then do the submit it should work.
As long as the variables are defined in the right scope it is fine (so you could place them, as A. Wolff mentioned inside the document ready)
Try something like this:
<script type="text/javascript">
$(document).ready(function(){
$('.login_form').on('submit', function(e) {
var id = $('.ajaxsend').attr('id');
var link = 'writereview/' + id;
$.post( 'writereview/'+link , $(this).serialize(), function(response) {
$("#login_message").html( response );
});
// disable default action
e.preventDefault();
});
});
</script>
Or like this(make link outside the function):
<script type="text/javascript">
$(document).ready(function(){
var link='';
$('#writeReview').click(function(){
var id = $('.ajaxsend').attr('id');
link = 'writereview/' + id;
console.log(id);
console.log('In the click');
})
$('.login_form').on('submit', function(e) {
$.post( 'writereview/'+link , $(this).serialize(), function(response) {
$("#login_message").html( response );
});
// disable default action
e.preventDefault();
});
});
</script>