Kynan Pacheco
Kynan Pacheco

Reputation: 207

Button and AJAX not responding

Im working on trying to get a button to run a php script with AJAX. To be clear I am really new to javaScript and PHP so my code might be completely wrong. I think that the problem is in my button click code not so much the ajax code. Any help is great

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
    $(".submit").click(function myCall() {
        var subdata = $("#form").serializeArray();
        var request = $.ajax({
            url: "construct_new.php",
            type: "GET",
            data: subdata
        });
        return false;
    });
    </script>
    <div>   
        <form id="form">
            Name of Product: <input type="text" name="productName" value="Enter Here">
            <input type="button" name="submit" value="Submit" class="submit">
        </form>
    </div>  

Upvotes: 1

Views: 47

Answers (2)

MrCode
MrCode

Reputation: 64526

You need a DOM ready wrapper around the jQuery because it executes before the element exists (or is rendered by the browser).

You can use either $(function(){ }) or $(document).ready(function(){ });.

$(function(){
    $(".submit").click(function myCall() {
         var subdata = $("#form").serializeArray();
         var request = $.ajax({
             url: "construct_new.php",
             type: "GET",
             data: subdata
         });
         return false;
     });
});

In this case, you don't need serializeArray() but simply serialize().

There is no success or complete function defined and so you wouldn't see anything when submitting this, unless of course you watch the developer console/net tab.

Also, using a form's submit event is preferred to the submit button's click event.

$(function(){
    $("#form").submit(function myCall() {
         var subdata = $(this).serialize();
         var request = $.ajax({
             url: "construct_new.php",
             type: "GET",
             data: subdata,
             success : function(response){
                 console.log("success!");
             }
         });
         return false;
     });
});

Upvotes: 2

delboy1978uk
delboy1978uk

Reputation: 12365

Put your jQuery inside a document ready like this, and prevent the default action (to submit the form):

 <script type="text/javascript">
    $(document).ready(function(){
            $(".submit").click(function(e) {
                e.preventDefault();
                var subdata = $("#form").serializeArray();
                $.get("construct_new.php",{data: subdata}, function(){
                     console.log(data); // whatever returned by php
                });
            });
        });
    </script>

Document ready makes sure page has finished loading everything. e.preventDefault() stops the default action (for a form, submission, for an a tag, following the link).

Upvotes: 0

Related Questions