tags:

views:

467

answers:

2

Does anyone know how can I return the javascript variable to ajax instead of string value while I using ajax to call the php. Please see below example for more 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;
    }
+1  A: 

You wondering how you can return from an AJAX response?

Then check out this jQuery FAQ answer.

Ólafur Waage
I wondering how can I passing 'var ErrorMapping' from php to ajax as variable instead of string
Jin Yong
A: 

What you're trying to do isn't all that great of an idea. What you probably want is to decode the JSON response back into an object from within your success callback and then return that.

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

The better option would be to use jQuery's built-in capabilities:

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

It does all the hard stuff for you. Take some time to read through jQuery's docs. There's a lot of useful stuff there.

note that jQuery's getJSON() uses eval() to decode JSON.
Javier
I wasn't aware of that. In light of that fact just be sure that your data absolutely is not tainted.