im trying to convert a json string from my .php file using eval() function but it doesnt work. the browser console says
SyntaxError: expected expression, got '<'...
but when i comment out the line where eval() is, and use document.write(data); the string appears...
here's my code..
<html>
<head>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
var go = function() {
$.get("testjson.php", function(data) {
var obj = eval("(" + data + ")");
document.write(obj.name + "<br />");
document.write(obj.date + "<br />");
});
}
</script>
</head>
<body>
<input type='button' value='go' onclick='go()' />
<body>
</html>
and here's the code of my testjson.php file...
<?php
$msg = array(
"name"=>"hi there Victor!",
"date"=>"Monday 21st Feb 2010"
);
$myMsg = json_encode($msg);
echo $myMsg;
?>
im using latest version of jquery..
There are other suggestions in the comments and answers here about using $.getJSON() instead of eval(), or specifying json as a parameter in $.get(), and these are all good suggestions. But, they aren't the reason this isn't working.
Simply, you're missing a semi-colon in your var go = .... function definition after the closing brace near the bottom.
the code is now fixed! lol i don't know why, but i just removed the commented html code under my .php code... how the heck it affects my code in the first place?? it's just a comment... :/
Related
This is a simple practical but I'm not sure what I'm doing wrong.
I have the following code in my external javascript file:
function myname(){
document.write("Monique");
}
function welcomeW(name){
document.write("Welcome " + name + "!");
}
function welcomeR(name){
return "Welcome " name "!";
}
I added this <script> tag to link to my html file:
<script src="script.js" type="text/javascript"></script>
I tried calling the functions in html using:
<script> myname(); </script>
<script> welcomeW(Monique); </script>
<script> welcomeR(Monique); </script>
when I wrote the function in html it worked, but in the external file nothing happens.
Monique , there is only one issue in your code, please use single quote (i.e 'Monique') or double quote ("Monique") when you are passing argument, i thing you are getting "Uncaught ReferenceError: Monique is not defined" error message.
<script> myname(); </script>
<script> welcomeW("Monique"); </script>
<script> welcomeR("Monique"); </script>
Or use this.
<script> myname(); </script>
<script> welcomeW('Monique'); </script>
<script> welcomeR('Monique'); </script>
If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).
You need to use multiple script elements.
a <script> to load the external script
a <script> to hold your inline code (with the call to the function in
the external script)
You might have put the <script src="<your js file>" type="text/javascript"></script> at the wrong place in your html file. Try putting it in the <head></head> or before your body closing tag </body>.
Another common mistake is in <script src="<your js file>" type="text/javascript"></script> try entering the location of like for example: <script src="./index.js" type="text/javascript"></script> if your index.js file is in the same folder as your index.html.
Hope it helps!
From whay you described, you are calling your functions and linking the js file in Html correctly. There's just a couple things that are causing errors.
The welcomeR function has a littly syntax error. You are likely running into Uncaught SyntaxError: Unexpected identifier 'name' and *uncaught ReferenceError: myname is not defined". You needs to have "+" between the strings and name for the return statement of welcomeR to resolve this error. Use console.log() statements to check that your js file is running as you intended.
When you are calling the functions in your html file with , you should have an uncaught syntax error where Monique is not defined. You just need to change the welcomeW and welcomeR function from
<script> myname(); </script>
<script> welcomeW(Monique); </script>
<script> welcomeR(Monique); </script>
to
<script> myname(); </script>
<script> welcomeW("Monique"); </script>
<script> welcomeR("Monique"); </script>
so you are passing strings in.
With this, you should be able to get "MoniqueWelcome Monique!" for your output.
The last function welcomeR does not output anything into the output file because it is returning a str, and not changing the content of your external file. If you wish to have it also output into you file, write
welcomeR("Monique")
as
document.write(welcomeR("Monique"));
You forgot the + at the return. And you can just call the functions in your script.If you linked it correct then it should work.
And if you didn't know. Return doesn't print/write anything. It just returns.
if you want to write it you just need to do this.
var welcomeR = return "Welcome " + name + "!"; and document.write(welcomeR);
<script>
function myname(){
document.write("Monique");
}
function welcomeW(name){
document.write("<br/>" +"Welcome " + name + "!" + "<br/>");
}
function welcomeR(name){
return "Welcome " + name + "!";
}
myname();
welcomeW("Monique");
welcomeR("Monique");
</script>
Make sure you put the script function calls after the script src tag.
I know there are a lot of questions covering something similar, but I've tried the answers without any luck.
Snippet of PHP:
$usernum_query = "SELECT numPersonID FROM tbllogins WHERE txtUserName='$currentuser'";
if(!$usernumber = $db1->query($usernum_query)){
die('There was an error running the usernumber query [' . $db1->error . ']');
}
while($row = $usernumber -> fetch_assoc()) {
$userIDnum = $row['numPersonID'];
$userIDnum = utf8_encode($userIDnum);
}
Snippet of Javascript:
$(function(){
$("#0").click(function(){
var userIDnum = <?php echo json_encode($userIDnum); ?>;
alert(userIDnum);
The most common answer I've come across says to UTF_encode my variable, which I think I've done correctly. I've also tried:
var userIDnum = <?php echo $userIDnum; ?>;
Which doesn't work.
In my HTML outside of the script,
<?php echo json_encode($userIDnum); ?>
return "90" (with the quotes)
<?php echo $userIDnum; ?>
returns 90 (without the quotes).
Within the script, I get null and no alert box, respectively.
Any ideas as to why the variable isn't passed into the script? Thanks!
edit: tried with quotes and got the same result
[Taken from comments as requested]
If I can make a recommendation, put your value in a data-attribute in the HTML (e.g. <body data-user-id="<?php echo $userId ?>">. This keeps you from mixing code languages together which is hard to read, and would allow your external script to run correctly without making it a PHP page.
As far as IE9, I'll take a quick look. You might want to see how jQuery manages the data attributes. You should, at the least, have access to
domObject.getAttribute('data-user-id').
Yep, just did a quick lookup, and even IE10 doesn't support the dataset feature. So, you'll need to use getAttribute for IE <= 10.
A solution based on a suggestion by calamari:
In the HTML:
<!DOCTYPE html>
<!--[if lt IE 11 ]> <html class="ie10orless"> <![endif]-->
<head>
... more code here ...
And in the script:
var oldIE;
if ($('html').is('.ie10orless')) {
oldIE = true;
}
if (oldIE) {
var x = document.getElementsByTagName("div")[0].getAttribute("data-number");
alert("in IE");
alert(x);
} else {
var userinfo = document.querySelector('#user');
alert("NOT in IE");
alert(userinfo.dataset.number);
}
Hope this helps someone else. Thanks everyone for the other suggestions as well.
There are couple of things to check. Lets say this is your script:
<?php $htmlString= 'testing'; //Lets say this is a snippet of your php
?>
<html>
<body>
<script type="text/javascript"><!-- And this is the snippet of your JS -->
// notice the quotes around the ?php tag
var htmlString="<?php echo $htmlString; ?>"; //Make sure there's double
//quotes around your php
alert(htmlString);
</script>
</body>
</html>
Make sure you have PHP and JS in a file called .php. If its an external .js file, php inside it will not work (you can rename the JS file to a .php extension if you have it set up that way)
Also make sure you have the html, php and js setup the way above. There has to be double quotes around php, for example:
var userIDnum = <?php echo json_encode($userIDnum); ?>;
change this to below:
var userIDnum = "<?php echo json_encode($userIDnum); ?>";
I wanna start by saying that I have absolutely NO knowledge in JS ( which I think I'm gonna learn because I'm over-heating like never before ).
I'm making a website for a friend , and I wanted to add a little more stylish that just plain CSS3 & HTML, So I went on Google and did a little research and I downloaded a free usable jQuery plugin called "Simple Modal".
I want to display a PHP variables inside that Modal.
Here's a screenshot of it:
And here is the minimum required to make the plugin work properly on any page:
> <link rel="stylesheet" href="simplemodal.css" type="text/css"
> media="screen" title="no title" charset="utf-8">
> <script src="assets/javascript/mootools-more-1.3.1.1.js" type="text/javascript charset="utf-8"></script>
> <script src="/js/simple-modal.js" type="text/javascript" charset="utf-8"></script>
> <script src="assets/javascript/demo.js" type="text/javascript" charset="utf-8"> </script>
Now here comes the problem. The content of the Modal is in -> simple-modal.js in the following form:
$("modal").addEvent("click", function(e){
e.stop();
var SM = new SimpleModal({"btn_ok":"Confirm button"});
// Confirm Button
SM.addButton("Confirm", "btn primary", function(){
alert("Action confirm modal");
this.hide();
});
// Cancel button
SM.addButton("Cancel", "btn");
SM.show({
"model":"modal",
"title":"Modal Window Title",
"contents":"<p >Hey , how you doing? Nice weather today!</p>"
});
})
In order to edit the content that is displayed , i need to edit the "contents".
I tried to put my PHP variable in it .. It didn't worked .. Googled it... And I found a solution. Which is putting a JS variable and then, PHP one on the main page.
<?php $content = $user['username']; ?>
<script type="text/javascript"> var name = "<?= $content ?>"; </script>
So after my new found , I tried to do this:
"contents":"<p>Hey" + name + ", how you doing? Nice weather today!</p>"
Didn't work. I then, tried (To see , maybe the variable was the problem ):
"contents": name
And this time it worked. It seems , for an unknown reason to me, that I can't 'combine' 2 things(? if that's a proper way to name them all).
I even tried things such as "Good" + "Morning" but I got the same result.
I'm very confused on why is that.
So, if anybody could be of any help by explaining me why this is happening, how to fix it or at least give a precise path for researches, I would be very graceful.
Thank you.
<?php $content = $user['username']; ?>
<script type="text/javascript">
var name = "<?= $content ?>";
var fullcontent = "<p>Hey" + name + ", how you doing? Nice weather today!</p>";
</script>
and here it will be
"contents":fullcontent
Where as for the modal you can try EXTJS its quite efficient and easy to use.
I have a javascript that works fine
<script>
$(document).ready(function(){
$('.delete').click(function()
{
alert('passed');
});
});
</script>
But when I saved all those script to a PHP variable
$phpVariable = "<script>
\$(document).ready(function(){
\$('.delete').click(function()
{
alert('passed');
});
});
</script>";
and echoed the variable (with or without backslash on dollar '$' sign inside javascript)
echo "$phpVariable";
The problem exists. Javascript doesn't work anymore.
Can we save javascript code to php variable without encountering mulfunction?
$phpVariable = '<script>
$(document).ready(function(){
$(\'.delete\').click(function()
{
alert(\'passed\');
});
});
</script>';
echo $phpVariable;
Basically change all " into ' and then escape any ' within the code.
You can not view Javascript in front end..
View source code of page, It already printed...
try this ...
echo htmlspecialchars($phpVariable);
The right answer is here
adding only
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
above the place where you are going to echo the $phpVariableScript
Sorry for some kind of duplicate question.
I found the right answer after I posted the question.
Should I delete this or link to the right answer?
I'm making a website that has 3 documents. The Php document that has all html structure and script, the css document that has no interest in the question, and the javascript document.
I'm trying to input html contents of a javascript variable through .innerHTML statement. And to do that, I need (of course) to code the HTML content, and so I do the code within the javascript file itself. Like so:
document.getElementById("exp").innerHTML = "<div class=\"cell\">\
<div class=\"project_cell\"><img src=\"img.png\"></div>\
<div class=\"project_cell\">text</div>\
</div>\";
And this works. However, the code is obviously not just this. It's a complex HTML structure that I do not wish to see in the javascript file. So I would like to put the HTML content to be inside this variable into a text file, using PHP, and make that variable on the innerHTML statement instead of all the code.
My PHP file is like this.
<html>
<head>
<title>sample</title>
<?php
$filename = "thisishtml.txt";
$doc = file_get_contents($filename);
?>
<script src="javascriptfile.js" type="text/javascript"></script>
</head>
<body>
...call javascript function...
It seems ok to me, but if I do like:
document.getElementById("exp").innerHTML = "<?php echo $doc ?>"
It doesn't work. I've tried simple text and I've tried with a new project, and it works on a new project, but not in this one. What am I doing wrong? I've looked to many questions and tutorials and didn't help and that's why I'm looking for help in here.
Thank you very much for your time. I hope we could solve this.
Chances are you need to escape the contents of $doc for JS output.
document.getElementById("exp").innerHTML = <?php echo json_encode($doc) ?>;
If your javascript code is in a javascript file, PHP does not process that so you cannot execute PHP code there.
So you can either put the javascript code directly into the PHP page
<script type="text/javascript">
function someFunction()
{
document.getElementById('exp').innerHTML = "<?php echo $doc ?>";
}
</script>
or you can do the follow:
<script type="text/javascript">
var doc = "<?php echo $doc ?>";
</script>
Then in the javascript file do:
function someFunction()
{
document.getElementById('exp').innerHTML = doc;
}