Sir
Sir

Reputation: 8280

PHP data passed as string instead of integer

I have a slight issue with parsing data in an array from PHP to JavaScript.

My JavaScript is thinking the data is a string and not an integer. Resulting in the wrong answer with the maths.

My JS maths is this:

abposx = data[d]["x"]+offset_x;

If data[d]["x"] was 20 and offset_x was 0

The answer becomes 200 instead of 20.

I'm wondering how I can get JavaScript to use data[d]["x"] as an number and not a string?

This jist of my php:

$get = mysql_query("SELECT x,y,sid FROM $table WHERE uid='1'") or die(mysql_error());
while($row = mysql_fetch_assoc($get)) {
    $data[] = $row;
}
$data = json_encode($data);

The json Encode looks like this:

[{"x":"283","y":"99","sid":"1"}]

Hope you can help!

Upvotes: 0

Views: 108

Answers (4)

Keith Frey
Keith Frey

Reputation: 691

Try using type conversion:

var absData = data[d]["x"] - 0;
abposx = absData+offset_x;

Upvotes: 0

parseInt can be used javascriptside, if you want do this phpside use as;

while($row = mysql_fetch_assoc($get)) {
    $data[] = array_map('intval',$row);
}

Upvotes: 1

Derek Harrington
Derek Harrington

Reputation: 467

use parseInt(string), which returns the string as an integer

Upvotes: 0

Alexander Pavlov
Alexander Pavlov

Reputation: 32286

abposx = parseInt(data[d]["x"], 10) + offset_x;

Upvotes: 3

Related Questions