views:

46

answers:

2

Hello all,

First try with ajax, please have patience.

<html>
    <script type="text/javascript" src="jquery-1.4.2.min.js"></script>

    <script type="text/javascript">

    $(document).ready(function() {
        function hello() {
            $.post("testCaseAjaxServerSide.php", { ola: "hello"}, function(data){
                if (data) {
                    alert('the data is: '+data);
                }
                else {
                    alert('there were no data');
                }
            });
        }

        $("#inputAmigo").click(function(){
            hello();
        });
    });
    </script>

    <form method="post" action="">
        <input id="inputAmigo" type="submit"/>
    </form>
</html>

On the server side I have:

if (isset($_POST['ola']))
{
  echo "we got a post";
} 
else
{
  echo "no post buddy";
}

I'm always getting "there were no data". Any help please? :)

Thanks a lot, MEM

A: 

Try capturing on the "submit" instead of the "click"

Tim
I have give my form and id of "textCaseForm" - Then, I use: $("#testCaseForm").submit(function(){ hello(); }); No luck, same result. :(
MEM
It may be a PHP problem, maybe try adding a subdirectory name in front of the filename, e.g. "MyScripts/testCaseAjaxServerSide.php"
Tim
I think Matthew is right, you need a "return false" to prevent a standard non-Ajax POST from interfering with your Ajax request.
Tim
+4  A: 

Works for me if I prevent the submit button's default behavior. Try changing the click function to:

$("#inputAmigo").click(function(e){
    e.preventDefault();
    hello();
});

or change your form so that you're not using a submit button. Use a simple <input type='button'> instead.

You could also try using the jQuery form plugin.

villecoder
I would like to avoid the prevent... I believe if I code it right, I have no need to prevent. About the input type='button' is not a standard solution so I believe, so input type='submit' should be used instead. Since I'm fairly newbie into jquery I would prefer to NOT abuse, and have it's usage to the bare minimum, so Jquery form plugin will not be my first choice... I have tried to give the form an id, and use .submit() instead of click. No luck either... (Sorry for being such a pickier... Any other suggestion :s )
MEM
@MEM if you don't prevent the form from being submitted, then there is no point of using ajax, because submitting the form will send your post to the server. If you want to use ajax to post the form the form cannot post, because that will force a page refresh. you should either use input type="button" or "return false" in your click handler.
Matthew J Morrison
So, preventDefault() is not a workaround, it's actually the way we can do, and no one will beat me with a ruler for that? Ok...
MEM
@MEM take a look at this: http://stackoverflow.com/questions/1357118/javascript-event-preventdefault-vs-return-false
Matthew J Morrison
@Matthew Thank you for the followup.
villecoder