Home  >  Q&A  >  body text

Unable to call function on AJAX success

<p>I cannot successfully use most jQuery with Ajax. I'm trying to get the error message from the response to appear in my notification (toast) div, but in addition to <code>.show()</code> and <code>.hide()</code> Nothing I try will work. </p> <p>I've used <code>console.log()</code> to make sure it does decode the response from the url and everything works as expected, but I can't call the function inside the Ajax success function< ;/ p> <p>This is my current JS that fires on button click. </p> <pre class="brush:php;toolbar:false;">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); } } }) }) )}</pre> <p>It is important to note that there are no errors or warnings in php or jQuery. I'm new to AJAX so I'm not entirely sure if this is something I'd be able to do, although it seems logical enough, no? </p>
P粉020556231P粉020556231383 days ago496

reply all(2)I'll reply

  • P粉038161873

    P粉0381618732023-09-03 13:09:00

    When sending data as JSON, the jQuery method .ajax() requires passing in an object-unique argument in the object's data property. Your jQuery.serialize() function creates the parameter string for the URL. This won't work here. You should 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. For my dummy JSON API, the .status property is not sent back. So there is no point in testing it.

    reply
    0
  • P粉872182023

    P粉8721820232023-09-03 09:36:17

    I hide my toast div ($('.notify')) until there is text in the div. However, I neglected to add a function that displays this (shown below) and did not call it after updating the toast in the AJAX success function using 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');
                });
        }
    }

    reply
    0
  • Cancelreply