Can you help me add the failure part of the ajax?

<script type="text/javascript">
            $("#form").on('submit',function(event) {
                event.preventDefault();
                var dataString = $(this).serialize();

                $.ajax({
                    type:"post",
                    url:"formulario-mob.php",
                    cache:false,
                    data:dataString,
                    success: function(data){
                        $('#form')[0].reset();}
                }).done(function(data){
                    setTimeout(function () {
                         Swal.fire('Enviado!','Entraremos em contacto em breve!','success');
                    },1000);
                });
				});
        </script>

Well, what do you want the script to do when it fails?

You just want to tack on a fail method, same as you’ve already got with .done:

$.ajax({
    type:"post",
    url:"formulario-mob.php",
    cache:false,
    data:dataString,
    success: function(data){
        $('#form')[0].reset();}
    }).done(function(data){
        setTimeout(function () {
        Swal.fire('Enviado!','Entraremos em contacto em breve!','success');
        },1000);
    }).fail(function(data) {
        console.log('Failed! ' + JSON.stringify(data));
    });
});

Tell us if that works, or if not, what happens.

What version of JQuery are you using?

I want to display that Swal.fire script alert

I’m using 3.4.1 version

I turned off the Mysql database but it keeps showing that the form was sent.

Hm, I’m not sure what your backend page is doing - I don’t know how it would matter if your database is on or off. So I’m not sure what formulario-mob.php is supposed to return to the frontend.

But I built a little sample which simply does what your source code does, with a backend php file which just sends a little json blob. This blob is not used by the frontend.

Here’s the demo: https://www.fullstackoasis.com/test-ajax.php

If you click that, and then click the button, you’ll see the alert pop up after a brief wait.

You can view the source for that page if you want - it’s basically what you have, different post url.

The backend page for the post is simple:

<?php
echo "{ 'color' : 'blue... no I mean yellow!' }";
?>

So - “it works for me” :slight_smile:

There are a couple of things you may want to do: check your JavaScript console to see if there are any errors. If you don’t see anything, post to a simple script (like the above one) to see if that one works. If that works, then it suggests that perhaps there’s something wrong with your back end code. If you can find the error logs for php on the server, maybe that will be helpful.

FWIW I didn’t actually look to see if the success property in the config to ajax is in conflict with the .done function. It could be worth looking into, but in any case, it works for me.

1 Like