skip to Main Content

I am unable to use most jQuery in Ajax success. I am trying to have an error message from the response appear in my notify (toast) div, but anything I try except .show() and .hide() will not work.

I have used console.log() to ensure it is definitely decoding the response from the url and everything is as it should, however I am unable to call functions inside the Ajax success function

This is my current JS which triggers at the click of a button.


function errMsg(code, msg) {
    const eCode = '<b>E-NS: ' + code + ' </b> </br>' + msg;
    const eMsg = '<span class="err" style="color: red;">' + eCode + '</span>';
    
    $('.notify').empty().html(eMsg);
}

$(document).ready(function() {
    $('#next-1').click(function(e) {
        e.preventDefault();
            $.ajax({
                url:'../data.php',
                method: 'POST',
                data: $('#form-1').serializeArray(),
                dataType: 'JSON',
                success:function(response){
                    if(response.status === true){
                        $('#form-1').hide();
                        $('#form-2').show();
                    } else {
                        console.log(response.status);
                        console.log('Response = ' + response.code + response.error);
                        errMsg(response.code, response.error);
                        var eCode = '<b>E-NS: ' + response.code + ' </b> </br>' + response.error;
                        var eMsg = '<span class="err>' + eCode + '</span>';

                        $('.notify').empty().html(eMsg);
                        
                    }
                }
            })
    })
)}

It should be noted that there are no errors or warnings in the php or the jQuery appearing. I am new to AJAX, so I’m not entirely sure if this is something I am able to do, although it seems logical enough, no?

2

Answers


  1. Chosen as BEST ANSWER

    I was hiding my toast div ($('.notify')) until there was text inside the div. However, I neglected to add my function that showed this -- Which can be seen below -- and did not call it after updating the toast in the AJAX success function with errorCheck()

    function errorCheck() {
        if ($('.notify').text().trim().length == 0) {
            $('.notify').hide();
        } else {
            var time =  setTimeout(function() {
                            $('.notify').fadeOut('200');
                        }, 5000);
            $('.notify')
                .show()
                .mouseout(function () {
                    time;
                })
                .mouseover(function () {
                    clearTimeout(time);
                })
                .click(function() {
                    $('.notify').fadeOut('100');
                });
        }
    }
    

  2. When sending data as JSON the jQuery method .ajax() expects an object in the data property of the object that is passed as the only argument. Your jQuery.serialize() function creates an argument string for a URL. This will not work here. You should instead use jQuery.serializeArray():

    function errMsg(code, msg) {
        const eCode = '<b>E-NS: ' + code + ' </b> </br>' + msg;
        const eMsg = '<span class="err" style="color: red;">' + eCode + '</span>';
        
        $('.notify').html(eMsg);
    }
    
    $(document).ready(function() {
        $("#form-2").hide();
        $('#next-1').click(function(e) {
            e.preventDefault();
            // console.log("this will be sent to the server:",$('#form-1').serializeArray());
                $.ajax({
                    url: 'https://jsonplaceholder.typicode.com/posts', // '../data.php',
                    method: 'POST',
                    data:  $('#form-1').serializeArray(),
                    dataType: 'JSON',
                    success:function(response){
                        // console.log("this came back from the server:",response);
                        if(response){
                            $('#form-1').hide();
                            $('#form-2').show();
                            errMsg(response.id, JSON.stringify(response))
                        } else {
                            console.log(response.status);
                            console.log('Response = ' + response.code + response.error);
                            errMsg(response.code, response.error);
                        }
                    }
                })
        })
    })
    .notify {border: 1px solid grey}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <form id="form-1">
    First form ... <br>
    <input type="text" name="title" value="my very own title"><br>
    <input type="text" name="size" value="XL"><br>
    <input type="number" name="quantity" value="3"><br>
    <button id="next-1" type="button">OK</button>
    </form>
    
    <form id="form-2">
    Second form ... <br>
    <input type="text" name="title" value="some other product title"><br>
    <input type="text" name="size" value="M"><br>
    <input type="number" name="quantity" value="5"><br>
    <button id="next-2" type="button">OK</button>
    </form>
    
    <div class="notify">This is the place for messages ...</div>

    You should also check what the server will send back. In the case of my dummy JSON API there was not .status property being sent back. So it did not make sense to test for it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search