In javaScript i try to append a data it work but in data url id and close button not working
success: function(response)
{
$.each(response, function () {
$.each(this, function (index, value) {
$('#List').append('' +
'<div class="col-md-12"><div class="alert #if('+value.linkValue+' == 0)alert-danger #else alert-success #endif">'+ value.item +
'<button data-id='+value.id+' data-token="{{ csrf_token() }}" data-url="{{ route("list.delete", '+value.id+') }}" type="button" class="close cls-btn" data-dismiss="alert"><span aria-hidden="true">times;</span></button>'+
'</div>'+
'</div>'
);
});
});
},
the above code data-url="{{ route("list.delete", '+value.id+') }}" show data-url="http://127.0.0.1:8000/delete/+value.id+" and <span aria-hidden="true">times;</span></button>show times;
how to add value in data-url and close button in appending time?
Related
<form id="review" method="post">
{% csrf_token %}
<button type="submit" id="sbtn" class="btn btn-primary btn-icon-split btn-lg" value="{{ Asin }}" >
<span class="icon text-white-50">
<i class="fas fa-poll-h"></i>
</span>
<span class="text">Fetch Reviews</span>
</button>
</form>
This is my html form on a Django rendered page
<script type="text/javascript">
$(document).on('submit','#review'.function(e){
e.preventDefault();
e.stopPropagation();
$.ajax({
type:'POST',
URL:'/reviews/',
data:{
asin:$('#sbtn').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
beforeSend:function() {
$('#loader').removeClass('hidden');
},
complete : function() {
$('#loader').addClass('');
}});
return false;
});
This is the ajax function on the page.
The problem is...the current page is the result of a form on a previous page so as soon as the form-submit event is invoked the page refreshes and data on the page is lost. I tried both
e.preventDefault()
and
e.stopPropagation()
but that doesn't help. I'd like to know if you have some approach or a workaround..Thank you!
To make this work change this part of code:
<button type="submit" id="sbtn" class="btn btn-primary btn-icon-split btn-lg" value="{{ Asin }}" >
Like that:
<button type="button" id="sbtn" class="btn btn-primary btn-icon-split btn-lg" value="{{ Asin }}" >
<button type="submit" id="submit_sbtn" class="d-none">
The submit button is not necessary.
Then change your script to send an ajax request to $('#sbtn') click event. And then submit your form.
$(document).on('submit','#review', function() {
$('#loader').removeClass('hidden');
$.ajax({
method: "POST",
type: "POST",
url: "/reviews/",
data: {
asin:$('#sbtn').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
}
}).done( function( msg ) {
$('#loader').addClass('');
console.log(msg)
}).fail( function(error) {
console.log(error)
})
return false;
})
I have an addtocart button with a quantity input field that is properly functioning in my website (see image below):
When I introduce for example 2 in the input field and push the addtocart button, my cart gets updated with 2 items.
But I want to change the quantity input field by a dropdown field so the visitor can only select one of the allowed quantities in the dropdown list. I can get dropdown field properly configured, but when I click on the addtocart button (see image below), nothing happens.
I suppose I need to change "input" by "select" somewhere in the javascript. Or maybe the quantity or button in the javascript is not correctly transmitted?
I can't get it working after some trials.
Can anybody help me with this? I would be very pleased (always struggling with javascript)
Thanks.
The html code for the input field (working) is:
<input type="hidden" value="<?=$product['product_id']?>" size="2" name="product_id" />
<input type="hidden" value="<?=$product['gift_products_id']?>" size="2" name="gift_products_id" />
<? if($product['quantity']!==$product['total']){ ?>
<input type="text" value="1" size="2" name="quantity" />
<a class="btn btn-primary addtocart" lang="<?=$product['product_id']?>" href="javascript:void(0)" ><span><?=$_['gr_m_add_to_cart']?></span></a>
<? } ?>
The html code for the "select option" field, properly configured but not working is:
<input type="hidden" value="<?=$product['product_id']?>" size="2" name="product_id" />
<input type="hidden" value="<?=$product['gift_products_id']?>" size="2" name="gift_products_id" />
<? if($product['quantity']!==$product['total']){ ?>
<select name="quantity" class="form-control_cart" id="input-quantity" value="1" >
<?php foreach (range(1, $product['quantity'], 1) as $stap) {
if ($stap == 1) {
echo "<option value='$stap' selected>$stap</option>";
} else {
echo "<option value='$stap'>$stap</option>";
}
} ?>
</select>
<a class="btn btn-default addtocart" style="margin-top:-4px" lang="<?=$product['product_id']?>" href="javascript:void(0)" data-toggle="tooltip" title="<?=$_['gr_m_add_to_cart']?>"><i class="fa fa-shopping-cart"></i></a>
<? } ?>
The javascript code that is used for the addtocart button:
$('.addtocart').click(function() {
id = $(this).attr('lang');
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: $('#row_'+id+' input[type=\'text\'], #row_'+id+' input[type=\'hidden\']'),
dataType: 'json',
beforeSend: function() {
//$('#button-cart').button('loading');
$('.addtocart').button('loading');
},
complete: function() {
//$('#button-cart').button('reset');
$('.addtocart').button('reset');
},
success: function(json) {
$('.alert, .text-danger').remove();
$('.form-group').removeClass('has-error');
if (json['error']) {
if (json['error']['option']) {
for (i in json['error']['option']) {
var element = $('#input-option' + i.replace('_', '-'));
if (element.parent().hasClass('input-group')) {
element.parent().after('<div class="text-danger">' + json['error']['option'][i] + '</div>');
} else {
element.after('<div class="text-danger">' + json['error']['option'][i] + '</div>');
}
}
}
if (json['error']['recurring']) {
$('select[name=\'recurring_id\']').after('<div class="text-danger">' + json['error']['recurring'] + '</div>');
}
// Highlight any found errors
$('.text-danger').parent().addClass('has-error');
}
if (json['success']) {
if (!Journal.showNotification(json['success'], json['image'])) {
$('.breadcrumb').after('<div class="alert alert-success success">' + json['success'] + '<button type="button" class="close" data-dismiss="alert">×</button></div>');
}
$('#cart-total').html(json['total']);
$('html, body').animate({ scrollTop: 0 }, 'slow');
$('#cart ul').load('index.php?route=common/cart/info ul li');
}
}
});
});
you should change this line of code :
data: $('#row_'+id+' input[type=\'text\'], #row_'+id+' input[type=\'hidden\']'),
to :
data: $('#row_'+id+' input[type=\'text\'], #row_'+id+' input[type=\'hidden\'], #row_'+id+' select'),
just add the select element to the data , with ever class or id you want.
I'm trying to upload a file. The problem is I want to add a JSON variable to the form.
I will be needing that variable to my php file.
Here's my html:
<div id = "progress-div-closeoutfile"><div id="progress-bar-closeoutfile"></div></div>
<form method="POST" id='closeoutfile_form' class = "upload_form" action = "{{ url('/store-files-closeout') }}">
<input type="hidden" class="form-control" id = "closeoutfile_hidden" value = "none">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<label>Closeout file:</label>
<input id="closeoutfile_input" type="file" name="closeoutfile_input[]" class="form-control file_upload" style="margin-right:10px;">
<button type="submit" style="color:gray; margin-top:10px; margin-right:5px;" class="btn btn-default btn-sm pull-right save_btn" id = "closeoutfile_save" disabled> Save <i class="fa fa-floppy-o"></i></button>
</form>
Here's my jquery AJAX
$('.upload_form').on('submit',function(e){
id_value = $(this).attr('id').replace('_form','');
formdata = new FormData($(this));
formdata.append('id_value',JSON.stringify(id_value)); // i want to add this variable
$(this).ajaxSubmit({
beforeSubmit: function() {
$("#progress-bar-"+id_value).width('0%');
},
uploadProgress: function(event, position, total, percentComplete) {
$("#progress-bar-"+id_value).width(percentComplete + '%');
$("#progress-bar-"+id_value).html('<div id="progress-status">' + percentComplete + ' % </div>')
},
success: function() {
}
});
});
I have managed to dynamically/programically create a modal form using bootstrap classes etc. But when I try to access the data from the input boxes I get no console.log(). Its asif the form is not present on the dom and none of the input can be gathered.
I tried this previously with same 'getFormData' function on a hardcoded modal form. The console.log() are called and the inspector shows a 'element highlight option' on the console output of the dom object, unlike the new dynamic form.
How can I get this data with the dynamically created form modals?
JQUERY
//create form modal
function getMessageTemplate(message, instance)
{
var styles =
{
success:{alert: 'alert-success', icon: 'glyphicon glyphicon-ok-sign'},
error:{alert: 'alert-danger', icon: 'glyphicon glyphicon-remove-sign'},
warning:{alert: 'alert-warning', icon: 'glyphicon glyphicon-question-sign'},
default:{alert: 'bg-primary', icon: 'glyphicon glyphicon-cog'}
};
var header =
'<div class="modal-header no-scroll '+ styles[message.style]['alert'] +'">'+
'<i class="'+ styles[message.style]['icon'] +'"></i>'+
'<h4 class="message"><strong>'+ message.title +'</strong></h4>'+
'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>'+
'</div>';
var body = '';
var footer = '';
if(message.form !== undefined)
{
body = $('<div class="modal-body"></div>');
form = body.append('<form id="form-' +message.form.name+ '" class="form"></form>');
$(message.form.input).each(function(index,value)
{
input = form.append(
'<div class="row">'+
'<div class="col-xs-2">'+
'<label>' +value.label+ ':</label>'+
'</div>'+
'<div class="col-xs-9">'+
'<div class="input-group add-on col-xs-2">'+
'<div class="input-group-btn">'+
'<a class="btn btn-default" data-toggle="popover-input" data-html="true" title="Item Name" data-content=" Name of the item, multiple names allowed for different container sizes. <br/>Only: characters (A-Z)."><span class="glyphicon glyphicon-question-sign"></span></a>'+
'</div>'+
'<input name="' +value.name+ '" class="form-control red-tooltip" placeholder="...." title="" type="text" >'+
'</div>'+
'</div>'+
'<div class="col-xs-1">'+
'<a class="valid-icon small fail glyphicon glyphicon-remove"></a>'+
'</div>'+
'</div>');
});
}
if(message.submit !== undefined)
{
footer =
'<div class="modal-footer msg-footer">'+
'<input class="form-input" type="hidden">'+
'<div class="row text-center">'+
'<button id= "close" class="btn btn-default btn-msg" type="button" data-dismiss="modal"> Back</button>'+
'<button id= "'+ message.submit.id +'" name= "'+ message.submit.name +'" class="btn btn-default btn-msg '+ message.submit.class +'" type="button" data-dismiss="modal"> Submit</button>'+
'</div>'+
'</div>';
}
var container = $('<div id="alert'+ instance +'" class="msg modal fade" tabindex="-1" data-focus-on="input:first" style="display: none;"></div>')
.append(header)
.append(body)
.append(footer);
return container[0].outerHTML;
}
//gather form infomation
function getFormData(form)
{
console.log(form); //dom object
var formName = form.attr('id');
$('body #'+formName+' input').each(function(inputKey, inputObj)
{
var inputName = $(inputObj).attr('name');
var inputValue = $(inputObj).val();
//none of this is displayed
console.log('------[input-start]-----');
console.log(inputName);
console.log(inputValue);
});
}
//submit button event for modal form
$('body').on('click', '.btn-form', function(e)
{
var sourceForm = $(this).closest('.modal').find('form');
var formData = getFormData(sourceForm);
//do stuff with formData etc
}
There's more these functions do, so I edited to show the core form features.
Fiddle Me
As given in Fiddle form.append is appending to $('<div class="modal-body"></div>') set as body variable and not to form element. Basically
<form id="form-..."> ..</form>
needs to contain <input> element and hence there is nothing in console.
Change form.append to form.find('form').append
Updated Fiddle
I have a button
<span class="btn btn-primary" id="open-label"><i class="icon-plus icon-white"></i> Add label</span>
which open modal window (http://twitter.github.com/bootstrap/javascript.html#modals)
<div id="ajax-labels"></div>
<div id="labels-modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="header">Add label</h3>
</div>
<div class="modal-body">
<div class="control-group">
<label class="control-label" for="name">Name</label>
<div class="controls">
<input type="text" id="name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="color">Color</label>
<div class="controls">
<input type="text" id="color" name="color" value="#a5f3d4" size="6" class="iColorPicker" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="submit-label"><i class="icon-ok icon-white"></i> Add label</button>
</div>
</div>
<script>
function append_labels() {
$("#ajax-labels").empty();
$.ajax({
url: "/ajax",
type: "POST",
cache: false,
data: {
type: "get_labels"
},
success: function (html) {
labels = $.parseJSON(html);
$.each(labels, function () {
$("#ajax-labels").append('<span class="label" id="' + this.id + '" style="background-color: ' + this.color + '">' + this.name + '<i id="edit-label" class="icon-pencil icon-white"></i></span> ');
});
}
});
}
$('span#open-label').click(function () {
$('#labels-modal').modal('show');
$('#labels-modal #submit-label').click(function () {
$('#labels-modal #submit-label').prop('disabled', true);
var name = $('#labels-modal #name').val().trim();
var color = $('#labels-modal #color').val().trim();
if (name != '' || color != '') {
$.ajax({
url: "/ajax",
type: "POST",
cache: false,
data: {
type: "add_label",
name: name,
color: color
},
success: function () {
$('#labels-modal').modal('hide');
append_labels();
}
});
} else {
return false;
}
});
});
</script>
After filling labels, user click on "Add label" and jquery send request, after sending, script close modal and refresh (on ajax) labels list. Question - if user quick clicks on "Add label", script send form repeatedly and i responce doubles in database. How I Can prevent this?
Try using one
$('span#open-label').one('click', function () { //...
This will guarantee your modal/ajax function will execute only once.
Disable the form and button on the first click so that the UI does not allow additional clicks. You can do this manually, or use the jQuery Block UI plugin.
Here is another post on how to do this: jquery disable submit button on form submission
Edit:
You are defining a event handler inside of a click handler. So what jQuery is doing is assigning that event handler each time the containing click is fired. So depending on how many times the top level click was executed, will be how many times your AJAX call will fire. Even though it is only 1 click of your button, the previous clicks are the culprit. Extract that click handler definition to outside of the other and you should be good to go.
$('span#open-label').click(function () {
$('#labels-modal').modal('show');
});
$('#labels-modal #submit-label').click(function () {
$('#labels-modal #submit-label').prop('disabled', true);
var name = $('#labels-modal #name').val().trim();
var color = $('#labels-modal #color').val().trim();
if (name != '' || color != '') {
$.ajax({
url: "/ajax",
type: "POST",
cache: false,
data: {
type: "add_label",
name: name,
color: color
},
success: function () {
$('#labels-modal').modal('hide');
append_labels();
}
});
} else {
return false;
}
});
Add this to the click handler
$('span#open-label').click(function () {
if( ($(this).attr('clicked') == '1') ) {
/* do something else then */
return;
}
$(this).attr('clicked', '1');
$('#labels-modal').modal('show');
This way, the next time you click you could show an alert.
If you want to "re-activate" the "open-label", you just do this :
$('span#open-label').attr('clicked', '0');