tags:

views:

86

answers:

4

Hi,

I am sending username and password to some target file (auth.php) using jquery ajax. In auth.php file, i have many variables "var a1", "var b1".

If authentication success, the variable "a1" set to pass(a1='pass').

My problem is how to access the only the "a1" variable from "auth.php" using the ajax response.

small code is below:

$.ajax({
          url: "auth.php", 
          type: "POST",
          data: "dataString",
          success: function (txtBack) { 

           -- here i need to check the variable "a1" from auth.php
          }

Thanks in advance.

+1  A: 

Your JS snippet...


$.ajax({
  url: "auth.php", 
  type: "POST",
  data: "dataString",
  dataType: "json",
  success: function (txtBack) { 
    // here i need to check the variable "a1" from auth.php
    alert(txtBack.a1);
  }
});

PHP Snippet...


echo json_encode(array('a1'=>'whatever'));
jtp
Thanks.. works fine. but in the auth.php file other than json response, i have some other "echo " statements.so, my js snippet not able to display the json response too. Any ideas?
Ra
Each case is different, but I usually pack everything into an associative array prior to running the json_encode statement. $rtnpack = array(); And there are usually keys for a status, a message, and the actual content returned whether it is an HTML table or otherwise. Sometimes I'll use buffering or writing to an array and then use implode("",array) and assign it to one of the $rtnpack keys. Hope that helps.
jtp
A: 

assuming your php returns JSON objects i.e. {'a1' : 100, 'a2' : 200}

your call back function would just access a1 via txtBack.a1

You can also use the PHP function json_encode() to convert an Associative Array to json then echo it out

your php script:

<?php
$arr = array ('a1'=>1,'a2'=>2,'a3'=>3);
echo json_encode($arr);
?>

Heres the manual for json_encode() http://php.net/manual/en/function.json-encode.php

And in case you're not familiar with JSON, check Wikipedia out: http://en.wikipedia.org/wiki/JSON

KennyCason
Thanks.. works fine. but in the auth.php file other than json response, i have some other "echo " statements.so, my js snippet not able to display the json response too. Any ideas?
Ra
yes, first you should only have the one `echo json_encode($arr);` So lets say throughout your script you have been echoing 5 different things. instead, at the beginning of your script define an array, `$arr = array();`, then every where you typeed `echo "sometext"`, change it to `$arr['msg1'] = "sometext", $arr['msg2'] = "somemoretext", ...`. So as a result you will have an associative array containing the various messages (or in your case, the data you were wanting to echo), of which you can just echo the json_encoded array as I demonstrated in the above example code.
KennyCason
Let me know if that helps. Also, to clarify further, `echo json_encode($arr);` echos out `{'a1' : 1, 'a2' : 2, 'a3' : 3}`, and as far as the php script is concerned, it is just a string of text, it is the JavaScript that interprets that as a JavaScript Object. So when you are printing out other text before the `echo json_encode($arr);` it is likely going to look something like `a bunch of stuff 23423{'a1' : 1, 'a2' : 2, 'a3' : 3}`, which is not <b>valid</b> notation for JSON
KennyCason
and if you still can't get that to work, try making a simple example first.
KennyCason
A: 

If you are returning an object you need to reference it.

txtBack.a1 or sometime I have seen txtBack.d.a1.

Though if you are returning an object like, and this is c#, this;

return new MyObject{ a1 = 10 };

then I think you need to do either txtBack.MyObject.a1 or txtBack.d.MyObject.a1

You might also consider returning the result as a JSON object.

Also use FireBug Firfox adding to see what is coming back.

griegs
A: 

You have to use jQuery + JSON combination something like this:

login.php:

<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>

<form action='auth.php' method='POST' class='ajaxform'>
 <input type='text' name='username' value='TestUsername'>
 <input type='password' name='password' value='TestPassword'>
 <input type='submit' value='submit'>
</form>

auth.php:

<?php
      if( $_POST['username'] and $_POST['password'] are authenticated ) {
         $arr = array( 'a1' => "Pass" );
      } else {
         $arr = array( 'a1' => "Fail" );
      }
      echo json_encode( $arr );
?>

jsFile.js:

jQuery(document).ready(function(){

    jQuery('.ajaxform').submit( function() {

        $.ajax({
            url     : $(this).attr('action'),
            type    : $(this).attr('method'),
            dataType: 'json',
            data    : $(this).serialize(),
            success : function( data ) {
                        for(var id in data) {
                            alert( data[id] ); // It will alert all json outputs
                        }
                      }
        });

        return false;
    });

});
NAVEED
Thanks..it works.... but other than json response i have some other html tags in the auth.php file (ex: some html table / some other echo statements).so, my js file did not display any values/responces. Is there any way to solve this?
Ra
Your `auth.php` file should only echo `JSON` string to work properly. You can pass all your echo's data and HTML code in array and convert this array into JSON using json_encode(). After that you can append that HTMLs in different DIVs using your jQuery code. Look at this question for more help: http://stackoverflow.com/questions/3656321/form-submition-with-jquery-is-not-working-correctly-with-ie8
NAVEED
`jQuery('#DivId').html( 'your html data' );` will load your HTML data into DIVs.
NAVEED
I think that he is likely mixing up .load() and .post(). if you are trying to do something like get some HTML form a script via AJAX and place it into a DIV then you should be using load(). <b>However</b>, In your case auth.php should not be printing any HTML, but simply processing your information and echoing ONE JavaScript Object (JSON), then, on successfull callback you can do things like display a success/failure message or generate other HTML i.e. `jQuery('#onReturn').html( "auth status:"+data.a1 );`
KennyCason
@KennyCason: Yes, You are right.
NAVEED
ya.... thanks all of you.... i got the point
Ra