jibin dcruz
jibin dcruz

Reputation: 273

AJAX showing retrieved values as undefined

I am using AJAX to send values to PHP and retrieve the values from PHP. The problem is the value i am getting from PHP is viewed as undefined in AJAX. Please help me solve this issue.

AJAX code:

var channel;

function overall() {
    $(".one").show();
    $(".two").hide();
    $(".three").hide();
    $(".four").hide();
    window['channel'] = "OVERALL";
    $.ajax({
        type: "GET",
        url: "dash2.php",
        data: ({channel: channel}),
        success: function (data) {
            console.log(data.a);
            console.log(data.b);
            console.log(data.c);
        }
    });
}

PHP code:

<?php

$channel=$_GET['channel'];
$host="192.168.0.29";
$username="root";
$password="root";
$dbname="realcl";

mysql_connect($host,$username,$password) OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db($dbname);

$query = 'select * from '.$channel;
$masterresult = mysql_query($query);

while($row1 = mysql_fetch_array($masterresult))
{
    $success=$row1[1];
    $timeout=$row1[2];
    $fail=$row1[3]; 
}
echo json_encode(array("a"=>"$success","b"=>"$timeout","c"=>"$fail"));

?>

Upvotes: 3

Views: 863

Answers (5)

Anjith K P
Anjith K P

Reputation: 2158

Please try this. 1. Use output buffering so that only json data will recieve in ajax response 2. Provide json datatype in ajax

<script type='text/javascript'>
    overall();
    function overall() {
        var channel = 1;
        $.ajax({
            method: "GET",
            url: "http://localhost",
            data: ({channel: channel}),
            dataType: 'json',
            success: function(data) {
                console.log(data.a);
                console.log(data.b);
                console.log(data.c);
            }
        });
    }
</script>

Php Code

   //empty the current contents of the output buffer
    ob_end_clean();

    // Turns on output buffering
    ob_start();

    // print output
    echo json_encode(array("a" => "success", "b" => "timeout", "c" => "fail"));

    // Turn off buffering and print the contents
    ob_end_flush(); // Turn off buffering and print the contents
    exit;

Upvotes: 0

verisimilitude
verisimilitude

Reputation: 5108

Set the dataType parameter as json.

$.ajax({
   type:"GET",
   url:"dash2.php",
   dataType: 'json',
   data:{channel:channel},
   success:function(data){
   }
 });

Quoting the jQuery.ajax documentation

dataType defines the type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response.

Few observations from your code.
1) As discussed in some of the above posts, your code is vulnerable to SQL injection attacks.
2) The mysql_* functions have been DEPRECATED and the extension will be removed in the future. DO NOT RELY ON THEM. I used CAPITAL CASE to emphasize my point.

For both the above points, try using either PDO or MySQLi. Either PDO or MySQLi could be used to shield your code from SQL injection attacks.

Here's a post on how to write code that protects your code from SQL injection attacks.

3) Shift your DB configuration details to a separate config.php so that you don't have to put in the same code in every file, you'd want to put an SQL query in.

Upvotes: 0

Jai
Jai

Reputation: 74738

Because you are encoding your data in json.

Try adding dataType:"json" in your ajax and ajax has type not method so change to type data should be in {} only:

$.ajax({
   type:"GET",
   url:"dash2.php",
   dataType: 'json',
   data:{channel:channel},
   success:function(data){
      console.log(data.a);
      console.log(data.b);
      console.log(data.c);
   }
 });

Try putting this line:

$channel=$_GET['channel'];

after db selection:

mysql_select_db($dbname);

Upvotes: 0

bipen
bipen

Reputation: 36541

again!!! anyways let me explain...

first you are sending channel by get method in ajax...

data:({channel:channel}),  //here which is just a vairable global variable 
                           //and not assigned any value in your given code... 

so this send channel as empty... and hence your quesry won't work coz that becomes..

$query = "select * from '' "; <-- here you have a singe quote `'` which also gives error

secondly..ajax has type properties and not method..

 type:"GET" //here type is get not method

seeing your php and query .. $channel looks like a tbalename and if it is OVERALL then you can just pass the string in you ajax and if not then you have to assign a tablename to channel in ajax

 type:"GET" //here type is get not method
 data:{channel:"OVERALL"}, //note you don't need an extra bracket here `()`

Upvotes: 0

Matt Cain
Matt Cain

Reputation: 5768

Just a point no-one else has covered yet: you need to use double quotes or concatenation here:

'select * from $channel'; // no
"select * from $channel"; // yes
'select * from '.$channel; // yes

Variables won't be resolved inside single quotes so you are trying to select from a table that is literally called $channel.

Also please use some kind of validation on $channel as what you have is very vulnerable to SQL injection attack.

Upvotes: 3

Related Questions