3

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"));

?>
jibin dcruz
  • 265
  • 1
  • 4
  • 15
  • try to console.log(data); to view the entire respond.. – Svetoslav Mar 27 '13 at 12:01
  • 2
    very bad coding that vulnerable to SQL injection attack, also note that if more than one row retreived from your query, you only outputting one of them which is the last one –  Mar 27 '13 at 12:01
  • the console.log output is undefined – jibin dcruz Mar 27 '13 at 12:05
  • @Akam I just need the last row, and how can i prevent this from SQL injection could you brief me a little in this matter. – jibin dcruz Mar 27 '13 at 12:06
  • see [1](http://stackoverflow.com/questions/13569/mysqli-or-pdo-what-are-the-pros-and-cons) and [2](http://stackoverflow.com/questions/10703426/php-pdo-and-mysqli), you can start by creating array of tables like `array('1' => 'table1')` then check value from ajax and then substitute it with its value that defined inside an array –  Mar 27 '13 at 12:10
  • please somebody explain ..what does `window['channel']` mean? – Amir Mar 27 '13 at 14:07

5 Answers5

3

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.

Matt Cain
  • 5,638
  • 3
  • 36
  • 45
  • with double quotes also it is returning me only undefined value. – jibin dcruz Mar 27 '13 at 12:11
  • Wow i missed out that part about using single quotes, but that still did not resolve my problem. I am still getting the value as undefined. – jibin dcruz Mar 27 '13 at 12:18
  • Was just solving 1 piece of the puzzle, I'm not bold enough to try and debug ajax code that I can't see or test :) Try manually going to the url that is being requested in your browser and see what is displayed. If it's an error then you know there are still issues with your PHP. If it's json, then you know the issue is with your JS. – Matt Cain Mar 27 '13 at 12:26
  • It not the problem with plugins, and it is not the problem withe PHP script i tried all that, its the problem with the AJAX receiving the value which is passed from PHP script. – jibin dcruz Mar 27 '13 at 12:28
  • Perhaps try using `$.getJSON` instead of `$.ajax` then. [Docs here](http://api.jquery.com/jQuery.getJSON/) – Matt Cain Mar 27 '13 at 12:33
  • it did not help, any help :( – jibin dcruz Mar 27 '13 at 12:40
0

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 `()`
bipen
  • 36,319
  • 9
  • 49
  • 62
  • I am assigning value to channel before the AJAX code using window['channel']="OVERALL"; so how can that send a empty value – jibin dcruz Mar 27 '13 at 12:08
  • see i am using a global variable because i want to dynamically query the values from database and keep tab of which query i am using right now so global variable is a good option for me. The global variable is working fine. Its not having any issue with the php query i tried debugging that part. – jibin dcruz Mar 27 '13 at 12:15
  • did you chnage the method to type in ajax ?? – bipen Mar 27 '13 at 12:18
  • Yes i did change and it still did not help – jibin dcruz Mar 27 '13 at 12:20
  • `echo json_encode(array("a"=>$success,"b"=>$timeout,"c"=>$fail));`... try this.. check if you are geting the channel value or not in php...just `echo $_GET['channel']`... i think the problem lies here – bipen Mar 27 '13 at 12:31
  • I am just passing the value from another page using AJAX, so how can i check on the PHP script because am not running the PHP script directly. – jibin dcruz Mar 27 '13 at 12:33
  • i mean check it in your php code.... not in AJAX.. see if you are getting the value there or not – bipen Mar 27 '13 at 12:35
  • Yea that is what i was asking. See i am running the html in a separate page, there only i am passing the values from AJAX to php. If i run PHP directly i cannot call the AJAX function from there, so how to check that? – jibin dcruz Mar 27 '13 at 12:37
  • how should i verify that the ajax is properly passing the values to php – jibin dcruz Mar 27 '13 at 13:43
  • yes that is what i was trying to explain.. the only way you can verify that is to print the get response in you php code.... – bipen Mar 27 '13 at 13:44
  • i.e ....dash2.php ... and check your console.. firebug using firefox or.. `F12` in chrome and check console – bipen Mar 27 '13 at 13:50
  • i made such a big stupid mistake, the table name was not matching with what i was passing. So that why i was not getting anything. Hey can you help me on how to get the whole dat from database right now i am getting only the last values. I know i should use array but can you show me how in the PHP and AJAX – jibin dcruz Mar 27 '13 at 14:11
0

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);
Jai
  • 74,255
  • 12
  • 74
  • 103
  • try putting `$_GET[]` after db selection. – Jai Mar 27 '13 at 12:14
  • That did not help. Once a variable is set in PHP it will have the value right? so that would not make much difference even if it was inside the mysql queries or not. – jibin dcruz Mar 27 '13 at 12:20
0

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.

Community
  • 1
  • 1
verisimilitude
  • 5,077
  • 3
  • 30
  • 35
0

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;
Anjith K P
  • 2,158
  • 27
  • 35