I am newbie in ajax.i want to send a normal ajax request when i will click the search button.i write some code the search onclick function..

$(document).ready(function() {
    $("#Search").click(function() {
        $.ajax({
            "dataType": 'json',
            "type": "POST",
            "url": "../test/loginform_details.do",
            "data": {

                username: $('#username').val().toString(),
                password: $('#password').val().toString(),

            },
            "success": function(data) {
                fnCallback(data);
            }
        });
    });
});

will that be ok??sholud i add fnCallback(data) in the success :function(data)??plz give some idea..

Dani AI

Generated

The AJAX structure shown in the first post is fine as a starting point. Call a central handler (eg. fnCallback) from the success path only if that function exists and is intended to process the server response. If the search control is a form submit button, stop the normal submit (use event.preventDefault()) so the page does not reload. Note that $('#...').val() already returns a string for typical inputs, so toString() is usually unnecessary.

Keep a small, robust success/error flow and inspect the response in DevTools (console/network) rather than relying only on alerts — this is what was hinting at. For login-like actions follow ’s advice: provide clear success/error feedback and let the server set any session cookie; redirect or UI changes belong in your callback after you verify the JSON response.

A compact pattern that avoids common mistakes:

$(document).on('click', '#Search', function(e) {
    e.preventDefault();
    var payload = { username: $('#username').val(), password: $('#password').val() };
    $.ajax({ url: '../test/loginform_details.do', method: 'POST', data: payload, dataType: 'json' })
      .done(function(resp) {
          if (typeof fnCallback === 'function') fnCallback(resp);
          else console.log('AJAX response:', resp);
      })
      .fail(function(xhr, status, err) {
          console.error('AJAX failed:', status, err);
      });
});

Quick checklist: ensure jQuery is loaded before this script, confirm the server returns valid JSON with the proper Content-Type (or remove dataType: 'json' while debugging), use HTTPS for credentials, and add an error handler to catch parse/network/CORS problems.

Recommended Answers

All 2 Replies

Member Avatar for Member #120589

In order to see if your Ajax transport works as expected, you can do this - quick n dirty:

"success": function(data) {
     alert(JSON.stringify(data));
}

Once you're satisfied that the data response is what you're expecting, sure pass it to a function of your choice - or write inline code within the function(data).

If you are using this script to log someone into a session, then I would think you would want to use a call back to notify the user of success or failure. Also, you would want to redirect the set a cookie for the user. All will require a callbackfunction.

For instance:

success: function(json){
    if( json.success ){
        window.location.href="/my_account";
        return false;
    }

    if( json.error ){
        alert(json.error);
        return false;
    }

    if( json.has_message ){
        html = '<div id="msg" style="display:block; border:1px solid red; background-color:pink; color:red; padding:5px 10px;>'+json.has_message+'</div>';
        $(html).prependTo('body');
        return false;
    }
}

Above is just and example of the top of my head. not tested. The point is, getting a json return and doing something with it for the user.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.