简体   繁体   中英

how to use ajax to change data in blade template

hey guys i'm trying to make changes in my blade template using ajax , when i press the button it changes the value of data in database and i want to display this data at once on my blade template . that's my java script code :

(function($){
    $('.wishlistForm').on('submit', function(){
        var form = $(this);
        $.ajax({
            url: form.attr('action'),
            data: form.serialize(),
            method: 'post',
            dataType: 'json',
            success: function(response){
                var wishlistButton = form.find("button[type='submit']");
                var x = parseInt($('.wish-btn-count').text());
                if(response.actiondone == 'added') {
                    $('.wish-btn-count').text(x++);
                    console.log(x);
                    wishlistButton.text(response.message);
                } else if(response.actiondone == 'removed') {
                    $('.wish-btn-count').text(x--);
                    console.log(x);
                    wishlistButton.text(response.message);
                }
            }
        });
        return false;
    });
})(jQuery);

and here is the part i want to change in my template :

<div class="wish-btn-count" id="wishlist">
                        {{$wishlistcount}}
                    </div>

so how can i do it ? and for record it returns the value right in the console but don't show it in my view

Prevent the default submit event, so you can trigger the ajax

 $('.wishlistForm').on('submit', function(e){
e.preventDefault();

This may be the solution.

If you are receiving json object response from the ajax call,first you have to parse that object and then use it.


Try this,

(function($){
$('.wishlistForm').on('submit', function(){
    var form = $(this);
    $.ajax({
        url: form.attr('action'),
        data: form.serialize(),
        method: 'post',
        dataType: 'json',
        success: function(response){
           /*Add this in your code*/
            var response = JSON.parse(response.trim());
            var wishlistButton = form.find("button[type='submit']");
            var x = parseInt($('.wish-btn-count').text());
            if(response.actiondone == 'added') {
                $('.wish-btn-count').text(x++);
                console.log(x);
                wishlistButton.text(response.message);
            } else if(response.actiondone == 'removed') {
                $('.wish-btn-count').text(x--);
                console.log(x);
                wishlistButton.text(response.message);
            }
        }
    });
    return false;
});

})(jQuery);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM