1

What I'm trying to do is calling some database data via ajax and php. But the ajax call doesn't work, and I can't find out a solution on the web.

So here is my code:

test.php

<?php

include_once 'db_class.php';

$cat = $_GET['cat'];  

$dbconn = new dbconn('localhost', 'root', 'somepsw', 'blog');

 $dbconn->set_query("select * from posts where category = '".$cat."'");

 echo '<br/>'.$dbconn->query.'<br/>';

 $result = $dbconn->result;

 $num = $dbconn->num_results;

 $array = mysqli_fetch_assoc($result);

 echo json_encode($array);
?>

If i type that url on browser: http://127.0.0.1:82/blog/ws/test.php?cat=css

The data returned via jsonEncode is correct, but when i'm loading it on a html page with jquery he can't read the data.

test.html

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
function ajaxCall() {

var css;

$.ajax({                                      
      url: 'test.php',
      type: "GET",     
      data: {cat: css},              
      dataType: 'json',    
      success: function(rows)         
      {

     alert(rows);

      },
      error: function() { alert("An error occurred."); }

    });

    }

    ajaxCall();

</script>
</head>
<body></body>
</html>

Thanks in advance.

7
  • The ajax call is using '/test.php'. The browser is using '/blog/ws/test.php'. Unless you're doing some rewriting that you're not showing. Commented May 19, 2013 at 16:57
  • You will not get pure json data from your test.php because you have printed some echo '<br/>'.$dbconn->query.'<br/>'; remove all echo from your code except only json_encode. Commented May 19, 2013 at 17:00
  • 2
    Do what @ManishJangir has suggested then change var css; to var css = "css"; and it will work. Commented May 19, 2013 at 17:01
  • You know that this is super-dangerous, right? You should never add user-input data like GET to an SQL statement. Commented May 19, 2013 at 17:01
  • Solved removing the others echo statements, and setting the var css to var= "css"; Thanks all for the support. @likeitlikeit Anyway, if that is very dangerous, how should i write the same functionality in safe way? Any advice? Commented May 19, 2013 at 17:17

2 Answers 2

1

I just rewrote the php code using PDO, should be more safe now.

db.php

<?php

$dbhost = "localhost";  

$dbuser = "root";

$dbpsw = "somepsw";    

$dbname= "blog"; 

try {

    @$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpsw);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);  
}

catch(PDOException $e) {

    echo "Connection failed, an error occured! Please contact server administrator."; //user friendly message
    getErrorsLog($e->getMessage());
 }

 function closeDbConn () {

    $dbh = null;

 }

 function getErrorsLog($message) {

    $file = 'dberrors.log';
    $date = date("d/m : H:i :");

    // Open the file to get existing content
    $current = file_get_contents($file);
    // Append a new error message to the file
    $current .= $date.$message;
    $current .= "\r\n";
    // Write the contents back to the file
    file_put_contents($file, $current);
    exit();

 }

?>

blogdata.php

<?php

include_once "db.php";

$tableName = "posts";
$data = array();
@$view = $_GET["view"];

if (isset($_GET["view"])) { 

    $stmt = $dbh->prepare("SELECT * FROM $tableName WHERE category =? ORDER BY created DESC"); 
 }
 else {  

    try {

    $stmt = $dbh->prepare("SELECT * FROM $tableName ORDER BY created DESC");

    }

    catch (PDOException $e) {

        getErrorsLog($e->getMessage());

    }

 }

$stmt->bindValue(1, $view, PDO::PARAM_STR);

$stmt->execute();

$affected_rows = $stmt->rowCount(); //Rows count

 if ($affected_rows == 0) {

     echo "The data you looking for no longer exist, please contact the administrator.";
     exit();
 }

foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {

    $data[] = $row;

 }

echo json_encode($data);

closeDbConn();

?>
Sign up to request clarification or add additional context in comments.

Comments

0

Your variable css has no value. You wanted to use the string 'css'. Maybe you want to be able to load other categories, too. So change your ajaxCall function to

function ajaxCall(category)
{
    $.ajax({
        url: 'test.php',
        type: "GET",
        data: {cat: category},
        dataType: 'json',    
        success: function(rows) {
           alert(rows);
        },
        error: function() {
           alert("An error occurred.");
        }
    });
}

and call it using

ajaxCall('css');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.