VHK
VHK

Reputation: 101

Why do I get [Object, object] returned instead of a string?

I want the success function to pick up the string it should receive from the PHP file.

The PHP complains "mysql_fetch_array() expects parameter 1 to be a resource, boolean given instead". I assume this is why the success function does not fire.

What am I doing wrong?

The jQuery:

var string = "something to be inserted";
$.ajax({
    url: '...',
    type: 'post',
    dataType: 'json',
    data: {toBeInserted: string.toLowerCase()},
    success: function(data) {
        console.log(data);
        // some code that is to work with data
    }
});

The PHP:

include 'serverStuff.php';
// A separate file with $con defined in it. Assume this works.

mysql_query("SET NAMES 'utf8'", $con);

// inserts the $_POST['toBeInserted'] into the database just fine

// assume the following are defined: 
// (string) $user_name, (string) $now, (string) $statement

$sql=("SELECT * FROM table WHERE user_name=$user_name AND date=$now AND statement = $statement");
$result=mysql_query($sql, $con);

if ($row = mysql_fetch_array($result)) {
    $new_id = (int) $row['id'];
}

mysql_close($con);

echo json_encode($new_id.'_'.$now);

Upvotes: 0

Views: 470

Answers (3)

VHK
VHK

Reputation: 101

Alright, I'm still not sure what causes the problem, but the workaround is the following:

  • switched the ajax function's datatype from 'json' to 'html';
  • changed the echo(json_encode("string")) to just echo("string");
  • picked up the string in the success function as follows:

The code:

$.ajax({
    // ...
    success: function(data) {
        console.log(data.responseText);
    }
});

Upvotes: 0

Martin Joó
Martin Joó

Reputation: 325

For the double double quotes problem use this:

echo json_encode(array('result' => $new_id.'_'.$now));

And data.result in JS

Upvotes: 0

Stryner
Stryner

Reputation: 7328

Strings need to be escaped in SQL:

"SELECT * FROM table WHERE user_name='$user_name' AND date='$now' AND statement = '$statement'"

It says "boolean given" because by the specification false is returned if there is an error. (Also consider heeding the deprecation note in the documentation)

Upvotes: 2

Related Questions