Luqman Shahzad
Luqman Shahzad

Reputation: 1

Ajax call doesnot work when submit button is used

Below is the simple code to call the ajax but when I click submit button,it doesn't work. I did echo "hello world"; in second file "test.php". Can someone get me out of this?

<html>
        <head>
        <title>AJAX TUTORIAL</title>
        <script src= "jqueryy.js"></script>
        <script>
        $(document).ready(function(){
        $("#sub").click(function(){
        //var user_email=$("#email").val();
        $.post("test.php",function(data){
        $("#result").html(data);
        });
        });
        });
        </script>
        </head>
            <body>
            <div id="box">
            <input type="text" name="email" id="email"/>
            <input type="submit" name="sub" id="sub" value="Submit"/>
            <div id="result">

            </div>
            </div>

            </body>
    </html>

Upvotes: 0

Views: 40

Answers (3)

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26288

Your question already states the answer, Ajax call doesnot work when submit button is used. Because submit button submit the form to the server and it reloads the page, that's why your ajax do not initiates.

So you have to hold the form submission or change button from submit to button.

But there is no form in your code. And you are including jquery like:

<script src= "jqueryy.js"></script>

please check if there is a js file with the name jqueryy.js present in the specified path.

Upvotes: 1

JYoThI
JYoThI

Reputation: 12085

You don't have any form tag .so it will not reload the page when submit is clicked I think your code seems good .

1) May be the problem is jquery included file name typo error jqueryy.js at the end double yy .

or

2) remove that link and replace with this cdn link and try

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Upvotes: 0

fppz
fppz

Reputation: 409

You can prevent the from from submitting by either waiting on the submit event for the form, or click listener for the button

For the button:

$('#sub').on('click', function(e){
    e.preventDefault();

    //Your code here
});

For the form:

1: Wrap your inputs in a tag

2: This code bit

$('form').on('submit', function(e){
    e.preventDefault();
    //Your Code here
})

On both of these, you have the e.preventDefault(); In short, it prevents the default action of your selector. In this case the form submission.

Upvotes: 0

Related Questions