0

I have a form that sends out to php which have a few text fields and image fields. But my javascript is not receiving the echo back from php. It redirects me to a php with the data echoed on there. Wondering why my javascript does that. Thanks for your time!

<script type="text/javascript" >


    $("button#signinbutton").click(function() {
    if ($("#list").val() == "") {
        $("p#result").html("Please enter both userna");
    } else {

        $.post($("#submitform").attr("action"), $("#submitform").serializeArray(), function(data) {

             var reply = data.replace(/\s+/, "");
           if($.trim(data) == 'success'){
            location.replace("account.html")

           }
            else   
            {

            $("p#result").html(data);
            }
        });
    }
});

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

    </script>
Benyaman
  • 451
  • 2
  • 10
  • 25

1 Answers1

0

It sounds like your form is doing a standard form submission where the browser reloads the page. Most likely caused by not wrapping your event handlers in the DOM ready function. Either use a DOM ready wrapper, or move your code to the end of the page, before the closing </body>. The form and button don't exist in the DOM at the time of assigning events, so they are never fired.

$(function(){
    $("button#signinbutton").click(function() {
        ...
    });

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

This will get AJAX submitting and will prevent the page refresh. If you have file upload inputs then you can't use serializeArray(). See this question for AJAX file uploads.

Community
  • 1
  • 1
MrCode
  • 63,975
  • 10
  • 90
  • 112
  • I just tried moving the code to the end before the end body tag. But its not allowing the image to be uploaded. It gives Undefined index: file in error, but if i remove the javascript, the image can upload but the echo moved to a blank php page. – Benyaman Jul 10 '14 at 08:40
  • If its anything i need to include in the script tag? To allow both text and images? – Benyaman Jul 10 '14 at 08:42
  • 1
    This has solved your first problem because now the ajax is now submitting, but jQuery's serializeArray() with $.post() won't upload a file, it will only post standard form input elements (not files). For AJAX file uploads see http://stackoverflow.com/questions/2320069/jquery-ajax-file-upload – MrCode Jul 10 '14 at 08:47
  • I am just wondering if its possible to just detect the result/echo from the php with .get? Because i am running all the verifying the images in the php already. But if i just do .get when button is clicked, then it won't wait til the php has been ran through tho. – Benyaman Jul 10 '14 at 11:40