I have a statement within my php-json-jquery object code that looks like so:
echo "{'year':'".$tree."'}";
i want to make the $tree variable a link so that a user can be able to click on it!
I have tried giving the variable an anchor [<a href></a>] tag but it hasnt worked.
As you want to echo json then you must do it with json_encode method available in php:
<?php
$anchor = "<a href='#'>".$tree."</a>";
$arr = array('year' => $anchor);
echo json_encode($arr); // prints {"year":"<a href='#'>date</a>"}
?>
Related
I have a variable named $path. I want to pass this variable from PHP to a javascript function.
<button onclick='myFunctionContact(\"" . $row1['id'] . "\")'>
<img border='0' alt='Contacts' src='".$imgpth."peoplesmall.png'>
</button>
<script>
function myFunctionContact(id) {
window.open('!!!$path should go here!!!'+id, '', 'toolbar=no,scrollbars=yes,resizable=yes,top=200,left=500,width=400,height=400');
}
</script>
How do I get the URL in path to display inside of the function, in the desired place?
I tried printing the variable into a javascript variable and then placing that variable into the function, but the popup window no longer works when I do that.
function myFunctionContact(id) {
var test1 = <?php echo $path; ?>;
window.open(test1 +id, '', 'toolbar=no,scrollbars=yes,resizable=yes,top=200,left=500,width=400,height=400');
}
I Know I am doing it wrong, but I have no idea how. Any advice would be greatly appreciated.
I think the problem is how you are echo the path:
Instead of:
var test1 = <?php echo $path; ?>
i think it should be
var test1 = <?php echo '"'.$path.'";'; ?>
You can always use a hidden input field, and set it's value to whatever you need to be used in your JS code, then grab that value of in your JS, or maybe try an ajax call to get the value you need.
json_encode() fixed the problem.
var myValue = <?php echo json_encode($path); ?>;
The path needs to be a quoted string. The end result of your echoed string has to, itself, contain quotes.
Assuming $path is a string, window.open is expecting a quoted string as the parameter.
function myFunctionContact(id) {
window.open(' . $path . ' + id, '', 'toolbar=no,scrollbars=yes,resizable=yes,top=200,left=500,width=400,height=400');
}
</script>
I'm making a form that is supposed to create a javascript alert when some fields aren't filled out or filled out properly. I want to be able to take the error messages I've put in a php variable and display them in the javascript alert window.
The following code does not work:
function died($error) {
echo '<script type="text/javascript"> alert('.$error.')</script>';
die();
}
How can I add the string contained in $error between the two "script" strings so it will output properly as a javascript alert?
Thank you!
You only forgot quotations that are required for the JavaScript alert.
If you passed 'hello' to the function, your current code would create alert as:
alert(hello)
instead of doing:
alert("hello")
Therefore, change your line to the following (two double quotes are added before and after concatenating $error):
echo '<script type="text/javascript">alert("'.$error.'");</script>';
and you can use your function:
died('error on whatever');
Display variable php in alert javascript
<?php
function died($error) { ?>
<script>alert("<?php echo $error; ?>")</script>
<?php die();
} ?>
You can use function follow this:
function died($error) {
echo '<script> alert("'.$error.'")</script>';
die();
}
<?php
echo "<script type='text/javascript'>alert('{$_SESSION["success"]}');</script>";
unset($_SESSION["success"]);
?>
Use this code it would work correctly
Once again I'm posting for something that I've never dealt with or have not found the answers with my google searches.
I have a web app, that I want to turn on a "logging" section.
I want an empty DIV to have data written to it (they're array CURL requests and json responses).
I have found how to Jquery write to a div, but this doesn't work with arrays. Does anyone have a better suggestion for me?
Code:
<script>
function updateProgress(progress){
$("#progress").append("<div class='progress'>" + progress + "</div>");
}
</script>
<div id='progress'></div>
in PHP:
echo "<script language='javascript'>parent.updateProgress('$response');</script>";
Error: Array to string conversion
use .html() to write in to div
<script>
function updateProgress(progress) {
$("#progress").html("<div class='progress'>" + progress + "</div>");
}
</script>
PHP:
echo "<script>";
echo "$(document).ready(function() {";
echo "updateProgress(" . $response. ");";
echo "});";
echo "</script>";
The problem is inside your PHP code. The variable $response is an array and you're attempting to convert it to (cast it as) a string, hence the error, "Array to string conversion".
Basically, you're doing this:
echo (string)array('value1', 'value2'); // Notice: Array to string conversion
If this is just a basic array (as the above example is), you can easily fix this by using implode. For example:
echo "<script language='javascript'>parent.updateProgress('" . str_replace("'", ''', implode(', ', $response)) . "');</script>";
If it's more complex (multi-dimensional array), you'll need to do some further processing to get only the values you want to show on the page.
The way you call this function parent.updateProgress('$response'); is wrong, you need not remove parent from invoking statement something like this.
echo "<script language='javascript'>updateProgress('".$response."');</script>";
//-----------remove parent from here^
Now this function updateProgress will be invoked successfully.
If $response is an array, and you want to display this as string then you can use it.
$response = implode(", ", $response);
echo "<script language='javascript'>updateProgress('".$response."');</script>";
I am very new to PHP and JavaScript. I am currently using echo in PHP to run some JavaScript on the page. I need to make a new javascript array and a new variable that are equal to an existing PHP array and variable, so I did this:
var messages = <?php print_r($messages)?>
var list = <?php echo $message['user_name'].': '.$message['text'].' ('.date('d/m/Y H:i:s', $message['date']).')'.'<hr />'; ?>
However, there is a problem caused by my using echo to echo script containing echo. How would I solve this. I would like to echo it because it is only about 4 lines long, so is there an alternative.
Thank you in advance.
Edit: This is the whole JavaScript. It is for a messaging system. $messages is declared from another PHP function, and the basic aim of this code is to 'refresh' the echo every few seconds so that the user can see new messages without having to refresh their page:
echo '<script type="text/javascript">;';
echo 'var messages = <?php print_r($messages)?';
echo 'var list = <?php echo $message['user_name'].': '.$message['text'].' ('.date('d/m/Y H:i:s', $message['date']).')'.'<hr />'; ?>';
echo 'setInterval(function(){console.log("hello")},3000);';
echo '</script>';
Not getting what you want,but if you want to use php array in javascript than make it javascript array
<script>
<?php $test_arr = array('apple','banana','mango');?>
var js_array = <?php echo json_encode($test_arr);?>;
</script>
output
<script>
var js_array = ["apple","banana","mango"];
</script>
Your Javascript will execute on the client, not on the server. This means that foo is not evaluated on the server side and therefore its value can't be written to a file on the server.
The best way to think about this process is as if you're generating a text file dynamically. The text you're generating only becomes executable code once the browser interprets it. Only what you place between <?php tags is evaluated on the server.
By the way, making a habit of embedding random pieces of PHP logic in HTML or Javascript can lead to seriously convoluted code. I speak from painful experience.
In my php i'd like to redirect via javascript/jquery a url with a php variable via js function.
My js function
function Redirect(url){
document.location.href=url;
}
In my php page i try in this way but I fear there is a problem with the syntax in the $url.
if ($opz = 1){
$url = "index.php?opz=OK#PG2&id=" . $_GET['id'];
echo "<script>";
echo "$(function(){ Redirect($url); });";
echo "</script>";
}
If I try to redirect in this way everything works perfectly (no Redirect function).
echo "<script>
document.location.href='index.php?opz=OK#PG2&id=$_GET[id]'
</script>";
Can anyone suggest me what is the correct syntax to pass my php variable via the js Redirect function? Thanks.
Just change echo "$(function(){ Redirect($url); });"; to
echo "$(function(){ Redirect('$url'); });";
Notice the quotes. the url is to be passed to the Redirect function as a string. So enclose it in single quotes. like Redirect('$url');
your problem is simple:
echo "$(function(){ Redirect($url); });";
should be replaced with
echo "$(function(){ Redirect('$url'); });";
Why you are trying to redirect your webpage using javascript.
You can do it with PHP also. Use PHP header() function to redirect your page.
if ($opz = 1){
$url = "index.php?opz=OK#PG2&id=" . $_GET['id'];
header("Location:".$url);
}
Assuming the Javascript code being generated is OK try window.location
try like below
if ($opz = 1){
$param = 'opz='.urlencode("OK#PG2").'&id='.$_GET['id'];
$url = "index.php?".$param;
echo "<script>";
echo "$(function(){ Redirect($url); });";
echo "</script>";
}
and pick up opz using urldecode();
The problem is caused by the fact that your generated HTML looks like this:
Redirect(index.php?opz=.....);
As you can see, you're missing quotes.
To put a variable from PHP into JavaScript, I always use json_encode. This ensures that, no matter what I pass it, JavaScript will see the same thing. It takes care of quoting, escaping, even iterating over arrays and objects.