1

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?!

6
  • you should specify the data type that the response will send back Commented Sep 18, 2015 at 7:00
  • Try logging the formData. Commented Sep 18, 2015 at 7:00
  • @Pekka : dataType is optional. Commented Sep 18, 2015 at 7:07
  • At where you see the errors? You're using submit type for button, and never return false will lead normal behavior submit. Commented Sep 18, 2015 at 7:15
  • Am I wrong, or are you submitting a form with only a hidden field 'crsf_token', that originally comes from the server, only to POST it again to the server via Ajax? Commented Sep 18, 2015 at 7:20

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Or he could easily use regular <input type="button"/> instead of submit one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.