$ .ajax POST问题

I am trying to use ajax POST method to validate course number on my page. The helper.html sends back correct value of i (true or false); that sets ValidCourse to true when it is a valid course. But when I check the value of ValidCourse after the ajax call; it always remains 'false'. Why?

if (EnrollmentsCount == 0) { // validate course 
    var crsNum = "'" + $j("#course_number").val() + "'";
    var ValidCourse = false;
    // Ajax call to determine if course is valid course 
    $.ajax({
        type: 'POST',
        url: 'helper.html?crsNum=' + crsNum,
        async: false,
        success: function(i) {
            if (i === 'true') {
                ValidCourse = true;
            }
        }
    });

    if (!ValidCourse) { //it is always false whether it is a valid or invalid course        
        var errorMsg = "Please enter valid course number";
        scroll('#course_number');
    }
}

can i see source code in helper.html ?

maybe this problem you use

var crsNum = "'" + $j("#course_number").val()  + "'";

try to use

var crsNum = $("#course_number").val();

Intuitively, your problem might be the === operator which you're using.

I think your html page's return value of true is being treated as boolean by javascript, then i has a boolean value, but you're checking against a string in 'true'. So try your test as if(i === true)

Need the contents of html page for further debugging mate!

the scope of the variable end when the callback method has done its execution. you might want to consider other option to check the value or put the program logic in the success callback function. this way you will achieve what you want.

The return value from helper.html had line feed and space. The following took care of it. Thanks everyone!

if ( i.replace(/\s+/g, ' ').trim()  === 'true' ) {  
    ValidCourse = true;
            }
        }
    });