How do I return a javascript variable in Ajax?

Does anyone know how I can return a javascript variable in ajax instead of a string value and I am using ajax to call php. See below for details:

Ajax:

    //Ajax Param 
    var paramList = "Action=make_process";

    ajaxRequest = $.ajax({
            url: "admin.php",
            type: 'POST',
            data: paramList,
            error: function(){
                  //error message here
            },
            success: function(data){
                 //read return javascript variable here;
            }   
        });   

      

PHP:

public function validationChk()
    {
        $error_msg['error_msg'][] = array("msg"=>"hello");
            $error_msg['error_msg'][] = array("msg"=>"hi");

        echo "var ErrorMapping = " . json_encode($error_msg). ";\n\n";          
        exit;
    }

      

0


a source to share


2 answers


Are you wondering how you can get back from the AJAX response?



Then check out the answer to this question in jQuery.

+1


a source


What you are trying to do is not such a big idea. You will probably need to decode the JSON response back into an object from your success callback and then return that .

Decoding a JSON string involves going through eval and hoping you don't have bad / malicious data. The safest way to do this is to parse JSON to Javascript. If you have to walk this route on your own, then at least try to use something already written. Search Google Code for "json-sans-eval".

Your best bet would be to use the built-in jQuery features:



jQuery.getJSON( url, [data], [callback] )

      

He does everything for you. Spend some time reading the jQuery docs. There is a lot of useful material.

0


a source







All Articles