简体   繁体   中英

AJAX POST success and error firing

I checked many posts here regarding same issue but nothing was working, and more or less it behaves like a glitch:

function onbtnclick(){


    var user_email=$('#user_email').val();
    var send_data = {email:user_email};

$.ajax({
        type: 'POST',
        url: 'someURL.php',
        crossDomain: true,
        data:send_data,
        dataType: 'text',
        success: function(responseData, textStatus, jqXHR) {
            alert("Thank you for the mailing list");
        },
        error: function (responseData, textStatus, errorThrown) {
            alert('Your email is already in our mailing list.');
            console.log('log e:'+responseData);
            console.log('log e:'+textStatus);
            console.log('log e:'+errorThrown);
        }
    });

        return false;

 }
};


<form name="myform">
    <input  id="user_email" type="email" name="email" placeholder="Your Email Here" style="width:300px" required><br>
    <br><button type="submit" class="leka-button button-style2 offer_button" onclick="onbtnclick()"><h5>SIGN UP</h5></button>
</form>

Simply i'm trying to alert the proper message if the user new to fire success or if he registered to fire error, I tried to remove dataType:'text' or adding 'json' and\\with removing crossDomain attribute as well but all didn't give me the reason. In case this was useful, here is where I fire the AJAX script.

You call the JavaScript when you click on a submit button.

The JavaScript runs. The Ajax request is prepared. The JavaScript finishes. The submit button's default behaviour submits the form. The page unloads. The Ajax request is canceled . The regular form submission takes place.

Get rid of the onclick attribute. Bind your event handlers with JavaScript instead.

$(function () {
    var $form = $([name="myform"]); // `name` is obsolete for form elements, give it an ID instead
    $form.on('submit', onbtnclick);

    function onbtnclick(event) { // Give this function a better name
        event.preventDefault(); // Don't submit the form normally
        // Then put the rest of your existing code
    }
});

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