kunal snehi
kunal snehi

Reputation: 11

Issue with AJAX call

My AJAX call to a JSP works when called with drop down menu, but when called with the submit button the content disappears and the page refreshes.

function najax() {
    $.ajax({
        url:"testjsp.jsp",
        type: "post",
        data: {
            crid: crid,
            sid: sid,
            ttid: ttid
        },
        async: false,
        cache: true,
        error: function(xhr, status, error) {
            alert("error" + error);
            alert("xhr" + xhr);
            alert("status" + status);
        },
        sync: true,
        success: function(responseText) {
            $("#disp_span").html(responseText);
        }
    });
}

Call to the code:

<input type="submit" name="Submit " id="submit"  value="Submit" class="btn"  onClick="najax();" ></input>

If I add a drop down menu then it works .

<select name="select_menu1" onChange="najax();">
    <option value=" ">Select</option>
    <option value="cr_id">SUBMIT</option>
    <option value="sr_id">CANCEL</option>

Upvotes: -1

Views: 77

Answers (5)

guradio
guradio

Reputation: 15555

To avoid submitting of the form change the input type to button

<input type="button" name="Submit " id="submit" value="Submit" class="btn">

Then on button click call the function

$('#submit').click(function() {
    //najax()
        //Or call the ajax directly

    $.ajax({
        url: "testjsp.jsp",
        type: "post",
        data: {
            crid: crid,
            sid: sid,
            ttid: ttid
        },
        async: false,
        cache: true,
        error: function(xhr, status, error) {
            alert("error" + error);
            alert("xhr" + xhr);
            alert("status" + status);
        },
        sync: true,
        success: function(responseText) {
            $("#disp_span").html(responseText);
        }
    });
})

Upvotes: 1

Ramanlfc
Ramanlfc

Reputation: 8354

If you want to make the ajax call with submit button ,then add the submit event to the form.

if you want to prevent the button from submitting the form and perform ajax operation ,then prevent the default action

   $('#submit').click(function(e){
         e.preventDefault();
        ....//ajax call 
    });

Upvotes: 2

You put the ajax request in a function, but you dont call it on the submit button like you do on the drop down menu onChange="najax();"

<input onClick="najax();" type="submit" name="Submit " id="submit"  value="Submit" class="btn"></input>

this should work or use jquery to do that for you. :)

Upvotes: 0

Eugene Kuzmenko
Eugene Kuzmenko

Reputation: 965

or better yet, just use a type="button" button

Upvotes: 0

Partha Sarathi Ghosh
Partha Sarathi Ghosh

Reputation: 11576

Stop the from submit as follows

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

Upvotes: 0

Related Questions