0

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!

4
  • Can't you just cast it as an int? (int)data[d]["x"]+offset_x; Commented Mar 6, 2012 at 21:17
  • Could you post the PHP where you set the value? Are you using ajax? Commented Mar 6, 2012 at 21:18
  • No, i tried that but i got Unexpected identifier as an error. Commented Mar 6, 2012 at 21:18
  • Yes both produce Unexpected identifier error Commented Mar 6, 2012 at 21:22

4 Answers 4

3
abposx = parseInt(data[d]["x"], 10) + offset_x;
Sign up to request clarification or add additional context in comments.

2 Comments

can you inspect the value of data[d]["x"]? What is it? Unless it is not a number, this code should work.
Glad to know there is no miracle in this case :)
1

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

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

Comments

0

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

1 Comment

Don't forget the radix, parseInt(string, 10)
0

Try using type conversion:

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

1 Comment

This should be JavaScript code, there is no typecasting in JavaScript, nor int type...

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.