-1

I'm trying to achieve the following: when you click on H1, JQuery GETs info for certain key from the server and sends it back to user, where jquery is showing prompt with this info. PHP in server.php

$link = mysql_connect("mysql.hostinger.com.ua", "_my_login_", "_my_password_") or die("NOOO!");
mysql_select_db("u994953720_db");

$key;
if(isset($_GET['Key'])) {
  $key = $_GET['Key'];

  $selected = mysql_query("SELECT * FROM `Table` WHERE `Key`='".$key."'", $link);
  $selected_row = mysql_fetch_array($selected);

  if($selected_row!=null){
    $response = array(
      "result" => $selected_row['Value']
    );
    echo json_encode($response);
    exit;
  }else{
    $response = array(
      "result" => "Nope."
    );
    echo json_encode($response);
    exit;
  }
}

jQuery in the main page:

$('h1').on('click', function () {
    $.ajax({
      type: 'GET',
      url: '/server/server.php',
      data: {
        'Key': 'Roman'
      },
      success: function(data) {
          alert(data.result);
      },
      dataType: 'json'
    });
});

But I don't have any effect. Could you guys show me how to fix my mistakes? P.S.Working not working example P.S.I am only starting learning PHP, so there can be some really stupid mistakes. UPDATE: I've done everything like you guys said (I don't care about safety yet), but it still doesn't work. In the console there is the following message:

XHR finished loading: GET "http://site0.hol.es/server/server.php?Key=Roman". 

When I include error method to ajax:

error: function(requestObject, error, errorThrown) {
        alert("request objqect: " + requestObject + " . Error: " + error + " . Error thrown: " + errorThrown);
}

, there is an alert: parsing error, unexpected token <

UPDATE 1: I've understood, that my while page is being writed to json result, like here, but I don't have any other echo-s, how can it happen?

UPDATE: I've figured out, that PHP was sending the whole page what it was placed in, so, I simply removed that) But thank you for your comments about safety, I'll correct it

Community
  • 1
  • 1
dddkk
  • 85
  • 1
  • 9
  • 2
    Try doing `console.log(data)` and see how your response is formulated. – Rob Schmuecker Aug 03 '14 at 16:30
  • Are you saying there's no alert at all? If so, open the console and start debugging ? – adeneo Aug 03 '14 at 16:30
  • What happens when you go to /server/server.php?Key=Roman Lalala directly? – Jonathan Crowe Aug 03 '14 at 16:34
  • A couple of things for your php code block: 1. You don't have to declare the variable $key like in Javascript...omit writing $key; 2. Rewrite `Key`='".$key."' AS `Key`='$key' – The One and Only ChemistryBlob Aug 03 '14 at 16:37
  • Why are you specifying a content-type for a GET request? That is no HTTP request body in a GET request, so there is nothing to specify the content-type of. – Quentin Aug 03 '14 at 16:37
  • **Danger**: You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). You are also **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Aug 03 '14 at 16:37
  • Are you using a php framework? – Jonathan Crowe Aug 03 '14 at 16:38
  • What does the JavaScript console show? Are there any errors? – Quentin Aug 03 '14 at 16:39
  • This could also help: in Chrome, after you click and there is no effect, right click and "Inspect Element"...if there is an error in your php file, you will see in red the message: "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" – The One and Only ChemistryBlob Aug 03 '14 at 16:40
  • What does the Net tab in your browser's developer tools show? Can you see the Ajax request being made? Is it formatted the way you would expect? Can you see the response to it? Is it what you expect? – Quentin Aug 03 '14 at 16:40
  • you are sending a lot of other things from `/server/server.php`. You should send only the json, not wrap it in other page html. – bansi Aug 03 '14 at 16:41

1 Answers1

1

By looking at your site I can see that you are returning HTML + JSON. Try throwing an exit after your echo:

echo json_encode($response);
exit;

Also - you are not handling a no data state at all. You should be do something like:

if(isset($_GET['Key'])) {
  // your valid request code
} else {
    echo json_encode(array('result' => false, 'reason' => "You must send a Key"));
}

Furthermore you can debug you php code by hitting the endpoint directly and var_dumping/debugging the code that is run there. For starters, what is the output of $selected_row = mysql_fetch_array($selected); when you go to http://site0.hol.es/server/server.php?Key=Roman

Finally - just little warning, as others have mentioned. You are wide open to SQL injection attacks. Look into using PDO -

What PDO is: http://php.net/manual/en/book.pdo.php

Why to use it: http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059

How to use it: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

Jonathan Crowe
  • 5,793
  • 1
  • 18
  • 28