0

I have a variable in PHP called $total = $db['total'];

now I want to grab that in Jquery so I do

<script>
$(function() {               
  console.log("<?php echo $total; ?>");


});

</script>

but I get some nonsense like console.log("<div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;"> throws error uncaught syntaxError: Unexpected identifier. What am I doing wrong?

2
  • what does it show if you echo it outside the js? Commented Jan 15, 2013 at 23:53
  • @Dagon the correct total. Commented Jan 15, 2013 at 23:54

3 Answers 3

3

Instead of

console.log("<?php echo $total; ?>");

use

console.log(<?php echo json_encode($total); ?>);

because the value of $total needs to be escaped before being handed over to JavaScript.

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

Comments

0

Bit of a kludge and, at the very least, inelegant, but last time I had a problem like this I got so confused I ended up writing the values into a hidden element with php then reading them in jquery.

Not pretty, but it worked. I actually had to deal with an array so dumped the whole thing into a table.

Comments

0

You most likely have an error in your php syntax! I'm sure of it, but hey there's a remote possibility that you actually have that string in your variable, so I'm choosing the safe path of saying most likely.

A simple googling of the string:

<div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">

Gives you a ton of sites which have errors in them, so I'd guess thats your problem. Other than that, but I guess you allready know this, you must be careful that the php-string that you're echoing out doesn't break the JS-string.

So how to solve this? Well, my first guess is that the variable $total doesn't actually exist, so check that first. This is ofcourse just guessing since I haven't seen your php-code.

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.