Switch form on submit - jQuery (Ajax) - javascript

I have a form to add item to favorites, and also to delete it.
Let's say this is form for adding and deleting:
#if($checkIfFavIsAdded == 0)
{!! Form::open(['id' => 'ajax-form-add', 'style' => 'float:right']) !!}
...
<button class="fa fa-star-o fa-2x" tool-tip-toggle="tooltip-demo" id="addFavbutton" title="Add item to favorites" style="color:#fd8809"></button>
{!! Form::close() !!}
#else
{!! Form::open(['id' => 'ajax-form-delete', 'style' => 'float:right']) !!}
...
<button class="fa fa-star-o fa-2x" tool-tip-toggle="tooltip-demo" id="addFavbutton" title="Delete item from favorites" style="color:grey"></button>
{!! Form::close() !!}
#endif
Here, I am checking if the item is added to favorites, and if so, the appropriate form should be shown.
It works on page reload, but how can I do this in Ajax?
I've tried to hide and show but without success. It just hides the form and don't display another one.
<script type="text/javascript">
$("#ajax-form-add").submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: form.serialize(),
success: function(data){
$("#ajax-form-add").hide();
$("#ajax-form-delete").show();
},
error: function(data){
swal("Error!", "error")
},
complete: function (data) {
}
});
});
</script>
<script type="text/javascript">
$("#ajax-form-delete").submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: "post",
url: "{{ url('deleteFavorites') }}",
dataType: "json",
data: form.serialize(),
success: function(data){
$("#ajax-form-delete").hide();
$("#ajax-form-show").show();
},
error: function(data){
swal("Error!", "Item is not available!", "error")
}
});
});
</script>

Blade templates are rendered server side, what you're trying to do is client side.
If you have that conditional in your blade template, the markup that gets rendered and sent to the browser will not include the other form.
You'll need to return the markup you want to display (IE the new form) in the ajax response.

For the second ajax you have written:
$("#ajax-form-show").show();
No, id with ajax-form-show is present. It should be:
$("#ajax-form-add").show();

Related

dynamic button(s) (generate by ajax ) not clickable

i try to create a shop cart using ajax (add working 100% )
but when i try to remove item(s) i found button not clickable
this is the code of delete :
$(document).on('click', '.delete', function() {
var product_id = $(this).attr("id");
var action = "remove";
console.log('something'); // show nothing
$.ajax({
url: "action.php",
method: "POST",
dataType: "json",
data: {
product_id: product_id,
action: action
},
success: function(data) {
$('#order_table').html(data.order_table);
$('#order_footer').html(data.order_footer);
$('.badge').text(data.cart_item);
}
});
})
Button code :
<button class="text-danger delete" id="<?php echo $values["product_id"]; ?>" >
<i data-feather="x"></i>
</button>

AJAX form submission in Django

I keep receiving 'Not Ajax' as a response during my form submission. I have to be missing something small but I cannot see it...
class VideoLikeView(View):
def post(self, request):
if request.is_ajax():
message = 'Ajax'
else:
message = 'Not Ajax'
return HttpResponse(message)
The AJAX code looks like this:
$(function () {
$("#like-form").submit(function (event) {
$.ajax({
type: "POST",
url: form.attr('action'),
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: {'pk': $(this).attr('value')},
success: function(response) {
alert('Video liked');
},
error: function(rs, e) {
alert(rs.responseText);
}
}
});
});
});
And my HTML:
<form id="like-form" action="{% url 'video-like' %}" method="post">
{% csrf_token %}
<input name="like"
type="hidden"
value="{{ video.id }}">
<button type="submit">
<span class="video-options ml-auto fas fa-heart fa-2x m-2"></span>
</button>
</form>
One question to add to this; how can I use an <input> in my form without using a <button>? I would like to use fontawesome icons but it seems I have to use a button to get the form to submit.
I found one answer on the internet that seems to work but I don't understand what the issue was. Seems like some type of serialization needed (?)... Anyways, here is what worked:
var frm = $('#like-form');
frm.submit(function () {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log('success');
},
error: function(data) {
console.log('failed');
}
});
return false;
});
Would love to hear from people why this works and not the previous..
try change your btn type button and add ID for event click :
since putting the submit button goes directly to view.py without going through AJAX
<form id="like-form" action="{% url 'video-like' %}" method="post">
{% csrf_token %}
<input name="like"
type="hidden"
value="{{ video.id }}" id="id_pk">
<button type="button" id="id_btn">
<span class="video-options ml-auto fas fa-heart fa-2x m-2"></span>
</button>
in your script
$("#id_btn").click(function() {
$.ajax({
url:window.location.origin + 'your url'
type: 'POST',
data: {'pk':$(#id_pk).val(), 'accion':'guardar'},
success: function (data) {
console.log('success');
},
error: function(data) {
console.log('failed');
}
});
});
and your view.py
def post(self, request):
if 'guardar' in request.POST['accion']:
print("")

Laravel & Ajax - Insert data into table without refreshing

First of all, I have to say that I'm beginner with using Ajax... So help me guys.
I want to insert the data into db without refreshing the page. So far, I have following code...
In blade I have a form with an id:
{!! Form::open(['url' => 'addFavorites', 'id' => 'ajax']) !!}
<img align="right" src="{{ asset('/img/icon_add_fav.png')}}">
<input type="hidden" name = "idUser" id="idUser" value="{{Auth::user()->id}}">
<input type="hidden" name = "idArticle" id="idArticle" value="{{$docinfo['attrs']['sid']}}">
<input type="submit" id="test" value="Ok">
{!! Form::close() !!}
And in controller I have:
public function addFavorites()
{
$idUser = Input::get('idUser');
$idArticle = Input::get('idArticle');
$favorite = new Favorite;
$favorite->idUser = $idUser;
$favorite->idArticle = $idArticle;
$favorite->save();
if ($favorite) {
return response()->json([
'status' => 'success',
'idUser' => $idUser,
'idArticle' => $idArticle]);
} else {
return response()->json([
'status' => 'error']);
}
}
I'm trying with ajax to insert into database:
$('#ajax').submit(function(event){
event.preventDefault();
$.ajax({
type:"post",
url:"{{ url('addFavorites') }}",
dataType="json",
data:$('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
}
error: function(data){
alert("Error")
}
});
});
Also in my web.php I have a route for adding favorites. But when I submit the form, it returns me JSON response like this: {"status":"success","idUser":"15","idArticle":"343970"}... It actually inserts into the db, but I want the page not to reload. Just to display alert box.
As #sujivasagam says it's performing a regular post action. Try to replace your javascript with this. I also recognized some syntax error but it is corrected here.
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
You could just replace <input type="submit"> with <button>instead and you'll probably won't be needing event.preventDefault() which prevents the form from posting.
EDIT
Here's an example of getting and posting just with javascript as asked for in comments.
(function() {
// Loads items into html
var pushItemsToList = function(items) {
var items = [];
$.each(items.data, function(i, item) {
items.push('<li>'+item.title+'</li>');
});
$('#the-ul-id').append(items.join(''));
}
// Fetching items
var fetchItems = function() {
$.ajax({
type: "GET",
url: "/items",
success: function(items) {
pushItemsToList(items);
},
error: function(error) {
alert("Error fetching items: " + error);
}
});
}
// Click event, adding item to favorites
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
// Load items (or whatever) when DOM's loaded
$(document).ready(function() {
fetchItems();
});
})();
You are using button type "Submit" which usually submit the form. So make that as button and on click of that call the ajax function
Change your button type to type="button" and add onclick action onclick="yourfunction()". and just put ajax inside your funciton.
Replace input type with button and make onClick listener. Make sure you use this input id in onclick listener:
So:
$('#test').on('click', function(event){
event.preventDefault()
... further code
I would also change the id to something clearer.

$this->input->post() is always empty in codeigniter

I am trying to get a value from an AJAX post that always seems to be empty. I already tried printing the value before doing the post and it works fine but I cannot get the value via $this->input->post()
HTML
<?php if ($product_info->stock > '1'){?>
<button class="btn btn-lg btn-primary" product_id = "<?php echo $product_info->id;?>" id = "addtocart"><i class="fa fa-shopping-cart"></i>Add to Cart</button><?php}?>
Javascript
$(document).ready(function(){
$("#addtocart").click(function(){
var productid = $(this).attr('product_id');
$.ajax({
type: "POST",
url: "<?php echo base_url();?>shoppingcart",
data: productid,
cache: true,
success: function(productid){
$("#cartstatus").html('<div class="alert alert-success"><strong>Success! </strong>Item has been added to the cart.</div>');
}, error: function(productid){
$("#cartstatus").html('<div class="alert alert-danger"><strong>Opps! </strong>Something went wrong.</div>')
}
});
});
});
Controller
$productcart = array();
if($this->session->userdata('cartsession')){
$cartsession = $this->session->userdata('cartsession');
foreach($cartsession as $id=>$val){
$productcart[$id] = $val;
}
}
$productcart[$this->input->post('productid')] = 50; -->sample value
$this->session->set_userdata('cartsession', $productcart);
$cartsession = $this->session->userdata('cartsession');
data params have certian format for sending values to the server using ajax.
Try this ...
$(document).ready(function(){
$("#addtocart").click(function(){
var productid = $(this).attr('product_id');
$.ajax({
type: "POST",
url: "<?php echo base_url();?>shoppingcart",
data: {productid : productid},
cache: true,
success: function(productid){
$("#cartstatus").html('<div class="alert alert-success"><strong>Success! </strong>Item has been added to the cart.</div>');
}, error: function(productid){
$("#cartstatus").html('<div class="alert alert-danger"><strong>Opps! </strong>Something went wrong.</div>')
}
});
});
});
Instead having your own attribute 'product-id', use HTML5's data attribute like 'data-product_id', so the HTML code looks like:
<button class="btn btn-lg btn-primary" data-product_id="<?php echo $product_info->id;?>" id="addtocart"><i class="fa fa-shopping-cart"></i>Add to Cart</button><?php}?>
Also, assign class name to the elements if you have more than one 'Add to Cart' buttons to group them, so it looks like:
<button class="btn btn-lg btn-primary" data-product_id="<?php echo $product_info->id;?>" class="addtocart"><i class="fa fa-shopping-cart"></i>Add to Cart</button><?php}?>
It's time to make use of the data attribute using jQuery:
var product_id = $(this).data('product_id');
Now, the whole code looks like
$(document).ready(function(){
$(".addtocart").click(function(){
var product_id = $(this).data('product_id');
$.ajax({
type: "POST",
url: "<?php echo base_url();?>shoppingcart",
data: product_id,
cache: true,
success: function(response){
$("#cartstatus").html('<div class="alert alert-success"><strong>Success! </strong>Item has been added to the cart.</div>');
}, error: function(response){
$("#cartstatus").html('<div class="alert alert-danger"><strong>Oops! </strong>Something went wrong.</div>')
}
});
});
});
Hope it works.

What is a solution for ajax post when I want to post a variable but have 1 js?

In my page I have the following code, that each add-to-favor- is followed by a unique hash to distinguish my multiple results.
<a class="btn btn-default btn-sm m-t-10 add-to-favor-'.$active[hash].'">
<i class="text-danger fa fa-heart"></i>
</a>
The problem is that I do not know how to have one universal solution for my problem. I want to pass the active[hash] to the ajax post.
Shall i use data-attributes? If yes, how ?
$(function(){
$('body').on('click', '.add-to-favor', function (){
$.ajax({
cache: false,
type: 'POST',
url: ,
data: ,
success: function(data) {
$('#show_the_favor').html(data);
}
});
});
});
Yes, you should use data-* attribute.
You specify data attribute as data-some-name="value". To get that value use .data('some-name')
<a data-hash="<?= $active['hash']; ?>" data-target="#show_the_favor" class="add-to-favor"></a>
$(document).ready(function () {
$(document).on('click', '.add-to-favor', function () {
var el = $(this);
$.ajax({
cache: false,
type: 'POST',
url: 'someUrl',
data: {hash: el.data('hash')},
success: function(data) {
$(el.data('target')).html(data);
}
});
});
});
Yes, use custom attributes. For your <a> elements, add the class add-to-favor but don't append the hash to that class. Then, add another attribute, data-hash="' . $active[hash] . '":
<a class="btn btn-default btn-sm m-t-10 add-to-favor" data-hash="' . $active[hash] . '">
<i class="text-danger fa fa-heart"></i>
</a>
JS:
$(function() {
$('body').on('click', '.add-to-favor', function() {
var hash = $(this).attr('data-hash');
$.ajax({
cache: false,
type: 'POST',
url: "script.php", // Enter the AJAX script URL
data: {
hash: hash
},
success: function(data) {
$('#show_the_favor').html(data);
// If you want to show the hash inside #show_the_favor, replace `data` above with `hash`
}
});
});
});
You can use this:
$('body').on('click', '[class*="add-to-favor"]', function (){
var hash = $(this).attr('class').match(/add-to-favor-([^ ]+)/)[1];
$.ajax({
cache: false,
type: 'POST',
url: SomeUrl,
data: {hash:hash},
success: function(data) {
$('#show_the_favor').html(data);
}
});
});
or simply use data attribute:
<a class="btn btn-default btn-sm m-t-10" data-hash="'.$active[hash].'">
<i class="text-danger fa fa-heart"></i>
</a>
and get the hash using $(this).data('hash').
Why don't you simply make your own Javascript Function to do this?
HTML:
<a class="btn btn-default btn-sm m-t-10" onclick="add_to_favor('.$active[hash].');">
<i class="text-danger fa fa-heart"></i>
</a>
Javascript/JQuery:
<script type="text/javascript">
function add_to_favor(hash){
alert("pass it to your ajax: "+hash);
$.ajax({
cache: false,
type: 'POST',
url: ,
data: ,
success: function(data) {
$('#show_the_favor').html(data);
}
});
}
</script>

Categories