user27133
user27133

Reputation: 487

AJAX Request Failed in form send data using php ajax

I need to send form data using ajax.

HTML:

<div class="" id="ajax-msg1"></div>
<form id="ajaxform" action="load.php">
   <input type="hidden" name="csrf_token" id="my_token" value="<?php echo $token; ?>" />
   <button type="submit" name="submit" id="ajax-1">Send</button>
</form>

JS:

$(document).ready(function() {
    $("#ajax-1").click(function() {
        $("#ajax-msg1").html("<img src='loading.gif'/>");
        var formData = $("#ajaxform").serializeArray();
        var URL = $("#ajaxform").attr("action");
        $.ajax({
            url: URL,
            type: "POST",
            data: formData,
            success: function(data, textStatus, jqXHR) {
                $("#ajax-msg1").html('<pre><code class="prettyprint">' + data + '</code></pre>');
            },
            error: function(jqXHR, textStatus, errorThrown) {
                $("#ajax-msg1").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus=' + textStatus + ', errorThrown=' + errorThrown + '</code></pre>');
            }
        });
    });
});

But in action i see this error:

AJAX Request Failed

and not work form. how do fix this error?!

Upvotes: 1

Views: 116

Answers (1)

swidmann
swidmann

Reputation: 2792

Like "Norlihazmey Ghazali" said

change:

$(document).ready(function() {
    $("#ajax-1").click(function() {

to:

$(document).ready(function() {
    $("#ajax-1").click(function( e ) {
        e.preventDefault();// avoid submitting the form here

Upvotes: 1

Related Questions