Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
This question may have already been answered, but how can I import variables from PHP into a segment of Javascript in HTML? I have the following PHP variables (these are parameters passed into a PHP script):
$user = $GET[user];
$pass = $GET[pass];
And I am trying to access these variables with the following references in my Javascript code:
var user = "<?=$user?>";
var pass = "<?=$pass?>";
However, when I check the values of these variables with console.log I get the following result:
user =
pass =
Where am I slipping up? It seems like I just can't read these variables from PHP.
Multiple bugs:
$user = $_GET['user'];
^----^----^--- missing
var user = "<?=$user?>";
^^^^^^^^^^---nasty and can break JS.
Never dump arbitrary text from PHP into a JS code block. One single JS metacharacter and you've introduced a syntax error and the entire JS block is killed. Always use json_encode():
var user = <?= json_encode($user) ?>;
Change:
$user = $GET[user];
$pass = $GET[pass];
To:
$user = $_GET['user'];
$pass = $_GET['password'];
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have an associative PHP array I need to access in Javascript to check the value of manufacturer. I am currently outputting this inline on the page, then reading in a separate JS file.
<?php
$carsData = array();
foreach ($cars as $car) {
$carsData[] = ['id' => $car->id, 'title' => $car->title, 'manufacturer' => $car->manufacturer];
}
$carsDataString = json_encode($carsData);
?>
<script>
carsData = <?php echo $carsDataString . ';';?>
</script>
This works so far - the source code shows exactly as I'd expect:
carsData = [{"id":2,"title":"Astra","manufacturer":"2"},{"id":3,"title":"Tepee","manufacturer":"3"},{"id":4,"title":"C4 Grand","manufacturer":"4"},{"id":5,"title":"Civic","manufacturer":"5"},{"id":6,"title":"Jazz","manufacturer":"5"}];
In my so far feeble attempts to read this in JS, I have the following:
$.each(carsData, function(key, value) {
console.log(key['manufacturer']);
});
In my console, this is outputting undefined, undefined, undefined, undefined. If I execute carsData in the console, I see the objects exactly as I would expect.
So what am I doing wrong? I need to be able to take this and do the following:
$.each(carsData, function(key, value) {
if (key['manufacturer'] = 5 {
$('#manufacturer' + key['manufacturer'].show();
}
});
Please note I have simplified it as the value of '5', because this value actually comes from another script and is printing 5 there as I expect.
To make the js valid you need to add a ; to the end of this line
carsData = <?php echo $carsDataString;?>;
try this code
$.each(carsData, function(key, value) {
console.log(value['manufacturer']);
});
<script type="javascript">
carsData = new Array(<?php echo implode(",",$carsDataString);?>);
</script>
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
<body>
<h1>Operadores aritméticos</h1>
<h3>+ Adición (102+103)=</h3><p id="suma1"></p>
<h3>- Substracción</h3><p id="resta1"></p>
<h3>* Multiplicación</h3><p id="multi1"></p>
<h3>/ División</h3><p id="div1"></p>
<h3>% Módulo</h3><p id="mod1"></p>
<script>
var suma = (102+103);
var resta = (36-20);
var multiplicación = (27*30);
var división = (900/30);
var módulo = (106%3);
document.getElementById("suma1").innerHTML = suma;
document.getElementById("resta1")innerHTML = resta;
document.getElementById("multi1")innerHTML = multiplicación;
document.getElementById("div1")innerHTML = división;
document.getElementById("mod1")innerHTML = módulo;
</script>
Hello guys, I have a problem, im pretty new at this (programming with HTML, Js, etc.).The issue is that when I try to make my Js variables appear on HTML (with document.getElementById), they do not appear. Nevertheless, if erase every document.getElementById except the one containing "suma1", the browser displays me the result of the sum (205), but if I add even one of them, the browser doesn´t display anything.
I hope I was clear with my problem, it seems very simple but hard to explain.
Any suggestions?
Thanks in advance
The reason you're not seeing anything when you add the statements to populate resta1, multi1, div1, and mod1 is probably because they all have a syntax error. This is likely causing even the first statement (suma1, which is syntactically valid) not to work.
Valid Statement
The 1 statement that is working is document.getElementById("suma1").innerHTML = suma;
Invalid statements
All the other statements follow this pattern:
document.getElementById("id")innerHtml = variable;
Note that you're missing the . between getElementById("id") and innerHtml. If you add the missing . then it should all work as expected.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Inside profuser variable i have string "nick".
echo a href="#" onclick="prof('.$profuser.')">
#UP I DELETED THE SIGN BEFORE a BECOUSE IT WAS DESTROYING WHOLE CODE IN STACK OVERFLOW
It should be sent here:
<script>
function prof(profuser){
var xmlhttp=new
window.XMLHttpRequest(); xmlhttp.open("GET", "user.php?user=" +
profuser, true); xmlhttp.send(); }
</script>
And then to this file called user.php:
$thisuser = $_GET['user']; echo $thisuser;
But this code shows me that string "nick" is not defined.
Could anyone tell me what is wrong about it please?
And if there are more errors in this code tell me please.
As error say nick is treated as undefined variable. It should be seen as string so you need to add quotes:
onclick="prof(\'' . addslashes($profuser) . '\')"
According to #p.s.w.g, you should use addslashes() to escape quotes from php variable in case there were any;)
try this.
onclick="prof('<?php echo $profuser; ?>')"
or
onclick="prof('<?= $profuser; ?>')"
I think you are mixing PHP and javascript? Hard to tell from the limited code that was posted.
Your issue is most likely a quoting one, if you are printing the whole onclick bit try this
echo 'onclick="prof(\''.$profuser.'\')"';
This is because you are probably getting something like this in your source.
onclick="prof(nick)";
And nick is a string not a javascript variable, which will be undefined.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
In my controller, I'm passing the image which is an array in this way:
$this->load->model('site_model');
$data['images'] = $this->site_model->fetch_images();
$data['main_content'] = 'my_view';
$this->load->view('includes/template', $data);
Everything up to know is perfect and even I can have the following in my view which shows the path of the first element:
echo $images[0]['path'];
But in view in script I'm trying to do the following which gives me Uncaught SyntaxError: Unexpected token ILLEGAL"
alert('<?PHP echo $images[0]['path']; ?>');
Why is that? Is not that possible?
Thanks
The path you're outputting contains backslashes, which in JavaScript strings begin an "escape sequence" -- basically a typable representation of a character that otherwise you'd have trouble putting into a string. But when they appear naked in a string, JS often chokes on them.
Rather than echoing the path directly, try this:
alert(<?= json_encode($images[0]['path']) ?>);
That will make PHP format the text in a way that'll cause fewer problems in JS.
(In some versions and configurations of PHP, <?= might not work. You can use <?php echo in its place; it does the same thing. It's just wordier. :P )
Try this
alert("<?php echo $images[0]['path'] ?>");
or try putting you php variable into a Javascript variable
to do so simply:
var data = "<?php echo $images[0]['path'] ?>";
alert(data);
cheers!
Try to JavaScript alert this way to store into $path variable,
$path = echo $images[0]['path'];
Now you print this $path into alert box
echo '<script type="text/javascript"> alert("' . $path . '");</script>';
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Is there any PHP method to do:
var filename = $_POST["filename"];
filename = filename.split(".").pop();
How can I do the same above thing in PHP?
Something like this, perhaps?
$filetype = array_pop(explode('.',$filename));
It will generate an Only variables should be passed by reference notice. If you want to get rid of that, you'd need:
$fileparts = explode('.',$filename);
$filetype = array_pop($fileparts);
However, the best way to get a file's extension is by using pathinfo():
$filetype = pathinfo($filename, PATHINFO_EXTENSION);
You can do unset($filename[count($filename) - 1]);. Which will remove the last element in the array.
You'd want to do this:
$filename = $_POST['filename'];
$file_arr = explode(".",$filename); // may need to escape '.' here, can't remember
$filename = array_pop($file_arr);
In PHP, you probably don't need to convert to an array and pop; get the position of the last character, then get the rest of the string. From http://davidwalsh.name/php-file-extension:
substr(strrchr($file_name,'.'),1);