简体   繁体   中英

How to return false in javascript function from JQuery calling [web method] in asp.net

So in default.aspx I have the code

 <script type="text/javascript">
    function validateForm() 
            {     

        test();
        //here should return true or false and exit validateForm so not to run InsertUpdateData()

    InsertUpdateData()

        }

  </script>     


<script language="javascript" type="text/javascript">

(function test() {
    var areaId = 98;
    $.ajax({
        type: "POST",
        url: "GridViewData.aspx/GetRegions",
        data: "{areaId:" + areaId + "}",
        //data:99 ,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function artybones(data) {
            // alert(data.d);
            if (data.d == "Foo 98")
            { alert("its true"); }
            else
            { alert("its false"); }

        }
    });
});     

</script>

in GridViewData.aspx I have

<script runat="server">     

    [WebMethod]     
    public static string GetRegions(int areaId)     
    {        
        return "Foo " + areaId;     
    } 

    </script> 

When I call test() from javascript i want it to return false but cant seem to geta value from test. Can someone post the code to do this? I know i am close..thanks in advance to those who post..

Don't wrap your test function in a DOM ready. You also don't name the function for your ajax success because you are defining the function at the time you create it. Finally, you have your data: parameter on your ajax call messed up. You have the curly braces in quotes, when they should be outside the JSON data. Like { areaId: areaId } With this you are setting a parameter on a JSON object. You are calling that parameter "areaId" and you are setting it equal to a variable you have also called areaId. There is nothing wrong with this, but if it's confusing to set areaId to areaId then change your variable name in the javascript var clientAreaId = 98; then it would be easier to read and understand { areaId: clientAreaId }

Do this:

<script language="javascript" type="text/javascript">

function test() {
    var areaId = 98;
    var isTrue = false;
    $.ajax({
        type: "POST",
        async: false,
        url: "GridViewData.aspx/GetRegions",
        data: { areaId: areaId },
        //data:99 ,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            // alert(data.d);
            if (data.d == "Foo 98")
            { alert("its true");
              isTrue = true; }
            else
            { alert("its false");
              isTrue = false; }
        }
    });
    return isTrue;
}    

</script>

Then in your call to test do this:

if (test() == true)
    InsertUpdateData();

You don't need to wrap named functions in DOM ready because they aren't executed until they are called. However, if you were calling test() when the page loaded then I would wrap that call in a DOM ready:

$(test);

Lastly, follow Guffa's suggestion of turning your request into a synchronous request by adding async: false to the parameters in your ajax call.

The AJAX call is asynchronous, so the function ends before the result arrives. The success function runs later, when the result arrives.

Change the AJAX request to be synchronous, to get the result before the function exists, by adding an async property to the ajax call:

async: false,

You could try a slightly different approach. When i do ajax calls using jquery i use the success and the error functions.

To make your ajax call end up in the error function you should make asp return a different http status code. I use status code 400 for this which means,

400 Bad Request

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

Explanation status code can be found here

Here's and example i used today inside a colorbox:

$.ajax({
  type: 'POST',
  url: url,
  data: $(formSelector, '#cboxLoadedContent').serializeArray(),
  success: function() {
    $.colorbox.close();
    window.location.href = successurl;
  },
  error: function(jqXHR, textStatus, errorThrown){
    $('ul.errors', '#cboxLoadedContent').html(errorThrown);
    $.colorbox.resize();
  }
});

I'm not familiar with asp but this is how my php + symfony template error handling looks like (this sets the 400 and add errors which will be catched by my ajax call)

<?php
if ($sf_request->hasErrors()) {
  $errors = array();
  foreach ($sf_request->getErrors() as $error) {
    $errors[] = msI18N::translate($error);
  }

  sfContext::getInstance()->getResponse()->setStatusCode(400, '<li>' . implode('<li></li>', $errors) . '</li>');
}
?>

Hope this example give's you and idea how you could pull it off using asp.

Presumably, you want to return true where you have alert("its true") . Based on that premise, you will want to do one of two things:

Option 1. Use a synchronous ajax call. You would set a variable in your success function indicating the return value, and then return that value after the ajax call:

function test() {
    var areaId = 98;
    var returnVal;
    $.ajax({
        async: false,     //  Make it synchronous here
        type: "POST",
        url: "GridViewData.aspx/GetRegions",
        data: "{areaId:" + areaId + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function artybones(data) {
            returnVal = data.d == "Foo 98";  // set the return value
        }
    });
    return returnVal;   // return true or false
}

Then, check the result of test() to determine whether to call InsertUpdateData() :

if (test())
{
    InsertUpdateData();
}

Option 2. Call InsertUpdateData() from the success callback. You can either pass it to test() as a parameter or hard code it in test() . Here's the hard coded technique:

function test() {
    var areaId = 98;
    var returnVal;
    $.ajax({
        type: "POST",
        url: "GridViewData.aspx/GetRegions",
        data: "{areaId:" + areaId + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function artybones(data) {
            if(data.d == "Foo 98")
            {
                InsertUpdateData();
            }
        }
    });
}

Here's passing it as a parameter:

function test(fnDataMatch) {
    var areaId = 98;
    var returnVal;
    $.ajax({
        type: "POST",
        url: "GridViewData.aspx/GetRegions",
        data: "{areaId:" + areaId + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function artybones(data) {
            if(data.d == "Foo 98")
            {
                fnDataMatch();
            }
        }
    });
}

Then, call test() like so:

test(InsertUpdateData);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM