[jquery] jquery ajax function not working

my html goes like this ,

<form name="postcontent" id="postcontent">
    <input name="postsubmit" type="submit" id="postsubmit" value="POST"/>
    <textarea id="postdata" name="postdata" placeholder="What's Up ?"></textarea>
</form>

The jquery code is as follows

$("#postcontent").submit(function(e) {
    $.ajax({
        type:"POST",
        url:"add_new_post.php",
        data:$("#postcontent").serialize(),
        beforeSend:function(){
            $(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
        },success:function(response){   
            //alert(response);
            $("#return_update_msg").html(response); 
            $(".post_submitting").fadeOut(1000);                
        }
    });
});

When I click on the submit button , my ajax request is not working , it looks as if the control is being passed to the JQuery submit function , but the ajax request is not executing/working properly,what is wrong ?

This question is related to jquery html ajax

The answer is


For the sake of documentation. I spent two days working out an ajax problem and this afternoon when I started testing, my PHP ajax handler wasn't getting called....

Extraordinarily frustrating.

The solution to my problem (which might help others) is the priority of the add_action.

add_action ('wp_ajax_(my handler), array('class_name', 'static_function'), 1);

recalling that the default priority = 10

I was getting a return code of zero and none of my code was being called.

...noting that this wasn't a WordPress problem, I probably misspoke on this question. My apologies.


you need to prevent the default behavior of your form when submitting

by adding this:

$("#postcontent").on('submit' , function(e) {

  e.preventDefault();

  //then the rest of your code
}

I am doing a code like this

_x000D_
_x000D_
<!-- Optional JavaScript -->_x000D_
<!-- jQuery first, then Popper.js, then Bootstrap JS -->_x000D_
<script_x000D_
    src="http://code.jquery.com/jquery-3.3.1.min.js"_x000D_
    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="_x000D_
    crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>_x000D_
<script>_x000D_
    $(document).ready(function () {_x000D_
_x000D_
        $(".work-category a").click(function (e) {_x000D_
            e.preventDefault();_x000D_
            var id = $(this).attr('data-id');_x000D_
            $.ajax({_x000D_
                url: 'process.php',_x000D_
                method: 'POST',_x000D_
                data: {_x000D_
                    clickCategoryID : id_x000D_
                },_x000D_
                dataType: 'JSON',_x000D_
                success: function (data) {_x000D_
                    $("#content-area").html(data.Content);_x000D_
                    $(".container-area").animate({top: '100px'}, 1000);_x000D_
                    $(".single-content").animate({opacity:1}, 1000);_x000D_
                }_x000D_
            });_x000D_
        });_x000D_
_x000D_
    });_x000D_
</script>
_x000D_
_x000D_
_x000D_

But the code is not running and the console saya process.php not found though I have the code on it.


I think you have putted e.preventDefault(); before ajax call that's why its prevent calling of that function and your Ajax call will not call.

So try to remove that e.prevent Default() before Ajax call and add it to the after Ajax call.


I was having this issue and none of these answers were able to help me with the issue. For anyone else who happens to have the same problem, here is a possible solution that worked for me. Simply reformat the code to be the following:

$("#postcontent").submit(function(e) {
  $.ajax({
    type:"POST",
    url:"add_new_post.php",
    data:$("#postcontent").serialize(),
    beforeSend:function(){
      $(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
    },
    success (response) {   
      //alert(response);
      $("#return_update_msg").html(response); 
      $(".post_submitting").fadeOut(1000);                
    },
    error (data) {
      // handle the error
    }
  });
});

The difference in the code is that this code has an error handler. You can choose to handle the error however you wish but it is best practice to have the error handler in case of an exception. Also, the formatting of the success and error functions within the ajax function are different. This is the only format for success/error that would work for me. Hope it helps!


try this code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<Script>
$(document).ready(function(){

$("#postcontent").click(function(e) {

        $.ajax({type:"POST",url:"add_new_post.php",data:$("#postcontent").serialize(),beforeSend:function(){
            $(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
        },success:function(response){   
                    //alert(response);
                    $("#return_update_msg").html(response); 
                    $(".post_submitting").fadeOut(1000);                
            }
        });
   });
});
   </script>

<form name="postcontent" id="postcontent">
              <input name="postsubmit" type="button" id="postsubmit" value="POST"/>
              <textarea id="postdata" name="postdata" placeholder="What's Up ?"></textarea>
 </form>

Give this a go:

<form name="postcontent" id="postcontent">
    <input name="postsubmit" type="submit" id="postsubmit" value="POST"/>
    <textarea id="postdata" name="postdata" placeholder="What's Up ?"></textarea>
</form>
<script>
    (function() {
        $("#postcontent").on('submit', function(e) {
            e.preventDefault();
        $.ajax({
            type:"POST",
            url:"add_new_post.php",
            data:$("#postcontent").serialize(),
            beforeSend:function(){
                $(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
            },success:function(response){   
                //alert(response);
                $("#return_update_msg").html(response); 
                $(".post_submitting").fadeOut(1000);                
            }
        });
   });
})();
</script>

Try this

    $("#postcontent").submit(function() {
  return false;
};

$('#postsubmit').click(function(){

// your ajax request here
});

my html and js code

<script>
$(".editTest23").change(function () {

        var test_date = $(this).data('');id
        // alert(status_id);    

        $.ajax({
            type: "POST",
            url: "Doctor/getTestData",
            data: {
                test_data: test_date,
            },
            dataType: "text",
            success: function (data) {
                $('#prepend_here_test1').html(data);
            }
        });
        // you have missed this bracket
        return false;
    });
</script>

in php code

    foreach($patitent_data as $result){

        $result_html .="<tr class='test_record'>\
        <td><input type='text' name='test_name' value='$result->test_name' class='form-control'></td>\
        <td><textarea class='form-control' name='instruction'> $result->instruction </textarea>\
        </td>\
        <td><button class='close remove_test_record' aria-hidden='true'>&times;</button></td>\
     </tr>";
    }

    echo json_encode($result_html)

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios