Inserting PHP code inside JavaScript [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php in javascript?
I need to check an if condition inside the inner html property of javascript. And so for that I need to use php inside it. So is it possible. I tried the following and it doesn't seem to work.
document.getElementById().innerHTML =
"<?php if ($number == 1) { echo $ex; } else { echo $ey; } ?>";
So please help me out with this problem.

Your PHP is executed at the server. Once the page has been fetched, inserting PHP code into it at the client end via JavaScript, will not cause it to be executed.
You should store $number, $ex, $ey in JavaScript variables and perform the same comparison in JavaScript.
Firstly,
<script type="text/javascript">
var number = <? echo $number ?>
var ex = <? echo $ex ?>
var ey = <? echo $ey ?>
</script>
The above sets the values of JS variables.
Afterwards, you can call:
if (number == 1) { document.getElementById().innerHTML = ex; }

Try this
<?php
if ($number == 1){ ?>
document.getElementById().innerHTML = $ex;
<?php }
else
{ ?>
document.getElementById().innerHTML = $ey;
<?php } ?>

Related

POST array data in php

I'm trying to post array data to another php, but it doesn't work..
here is my code below.
in func.php
function search($x, $y)
{
...
$martx = array();
$marty = array();
foreach($load_string->channel as $channel) {
foreach($channel->item as $item) {
array_push($martx, $item->mapx);
array_push($marty, $item->mapy);
}
}
echo"<form method=post action='map.php'>";
for($i = 0; $i < 8; $i++)
{
//echo $martx[$i]."<br/>";
//echo $marty[$i]."<br/>";
echo "<input type='hidden' name='martx[]' value='".$martx[$i]."'>";
echo "<input type='hidden' name='marty[]' value='".$marty[$i]."'>";
}
echo "</form>";
header("location: map.php?x=$x&y=$y");
}
martx and marty have data from parsed xml $load_string
And I want to post these data to map.php by form with POST. So, I expect that I can use two arrays martx and marty in map.php like $_POST[martx][0]..
But when I run this code, page remains in func.php, instead of redirecting to map.php
Am I make some mistake?
Thanks in advance.
========================================================================
Thank you all for your kind concern and helpful advice!
I edit my code with your advice,
I delete all echo with using javascript
And I add submit code
here is my code below
....
$martx = array();
$marty = array();
foreach($load_string->channel as $channel) {
foreach($channel->item as $item) {
array_push($martx, $item->mapx);
array_push($marty, $item->mapy);
}
}
?>
<form method='post' action='map.php?x=<?=$x?>&y=<?=$y?>' id='market'>
<script language="javascript">
for(i = 0; i < 8; i++)
{
document.write('<input type="hidden" name="martx[]" value="<?=$martx[i]?>">');
document.write('<input type="hidden" name="marty[]" value="<?=$marty[i]?>">');
}
document.getElementById('market').submit();
</script>
</form>
<?php
//header("location: map.php?x=$x&y=$y");
}
With this code, page redirect to map.php successfully.
But I can't get data like $_POST['martx'][i] in map.php
I think document.write line cause problem
when I write code like
document.write('<input type="hidden" name="martx[]" value="$martx[i]">');
result of $_POST['martx'][i] is "$martx[i]"
Is any error in this code?
I want to use POST method but if I can't post data with POST,
then I'll use session-method as #Amit Ray and #weigreen suggested.
thanks again for your concern.
First, You try to use header('location: xxx') to redirect user to another page.
As the result, you are not submitting the form, so you won't get data like $_POST[martx][0] as you expect.
Maybe you should try using session.
I can see some errors that you are making when you are doing header redirect. There should be no output before you call header redirect but you are doing echo before redirect.
use session to tackle this issue
function search($x, $y)
{
...
$martx = array();
$marty = array();
foreach($load_string->channel as $channel) {
foreach($channel->item as $item) {
array_push($martx, $item->mapx);
array_push($marty, $item->mapy);
}
}
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$_SESSION["martx"] = $martx;
$_SESSION["marty"] = $marty;
header("location: map.php"); exit;
then in map.php you can retrieve the session variables
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$martx = $_SESSION["martx"];
$marty = $_SESSION["marty"];
Then you can use a for loop or foreach loop to iterate through the values

calling php using js

ok so I have this in my HTML code:
<script type="text/javascript" src="load2.php"> </script>
I saw somewhere you could call a php file like that and the javascript contained in it will be rendered on the page once echoed.
So in my PHP file i have this:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['DayNum']; }
$length = count($storeArray);
I connected to my database and stuff and pulled those records and stored them in an array. Now my problem is alerting them using js. This is what I have:
echo " function test() {
for(var i = 0; i<$length; i++){
alert($storeArray[i]);
}
}
";
The test() function is being onloaded in my HTML page, but for nothing the values in the array won't alert. Any help please?
echo " function test() {
for(var i = 0; i<$length; i++){
alert($storeArray[i]);
}
}
";
This code is literally writing what you have written above. It's not completely clear, but I believe your intent is to loop over the contents of your database data, and alert that to the browser with alert() function.
You can achieve this in a couple of ways.
Write multiple alert statements
echo "function test() {"; //Outputting Javascript code.
for($i = 0; $i<$length; $i++){ //Back in PHP mode - notice how we aren't inside of a string.
$value = $storeArray[$i];
echo "alert($value)"; //Outputting Javascript code again.
}
echo "}"; //Outputting Javascript code to close your javascript "test()" function.
Write a Javascript array, then loop over it in Javascript
echo "function test() {";
echo " var storeArray = ['" . implode("','", $storeArray) . "'];";
echo " for (var i = 0; i < storeArray.length; i++) {";
echo " alert(storeArray[i]);";
echo " };";
echo "}";
Finally, you could use AJAX and JSON to load the data, rather than outputting a JS file from PHP. That is an entirely different topic, though, and you should search StackOverflow for more examples as there are numerous questions and answers involving it.
Unless your array contains only number, you probably have JS error. You should put your $storeArray[i] in quotes in the alert function so it considered as a string in js.
alert('$storeArray[i]');
Once printed out, the JS will look something like this
alert('foo');
alert('bar');
Whereas with your code, it would've printed it like this
alert(foo);
alert(bar);
in your php file include load2.php
header("Content-Type: text/javascript");
in the in the top. so your browser get what it wants.
$i=0;
$storeArray = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[$i] = $row['DayNum'];
$i++;
}
echo "var arr = Array();";
echo "function test() {";
foreach ($storeArray as $key=>$item) {
echo "arr[".$key."] = ".$item.";";
}
echo "}";
echo "alert(arr);";
actually you can comment out the two echos containing the <script></script> part when including the file as <script src="load2.php" type="text/javascript" ...

How create Json by PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to generate .json file with PHP?
I want to use php to create a json like below. it will return a string json as a response from result sql query. How do I do?
{"Orders":[
{"DeliveryId":"DeliveryId","CustomerName":"CustomerName","PhoneNumber":"PhoneNumber","Address":"Address"},
{"DeliveryId":"DeliveryId","CustomerName":"CustomerName","PhoneNumber":"PhoneNumber","Address":"Address"}
]
}
my code
<?php
mysql_connect("mysql12.000webhost.com","a4602996_longvan","longvan2012");
mysql_select_db("a4602996_lv");
$id=$_POST[user];
$sql=mysql_query("select * from testlongvan where Status = 'PACKED'" );
$json = array();
if(mysql_num_rows($sql)){
while($row=mysql_fetch_row($sql)){
$json['Orders'][]=$row;
}
}
//while($row=mysql_fetch_assoc($sql))
//$output[]=$row;
print(json_encode($json));
mysql_close();
?>
But when use my code i recieve result, don't result i want:
{"Orders":[
["longvan","10/12/2012","Be34433jh","Long Van","115 Pham Viet Chanh, quan Binh Thanh","http://longvansolution.tk/image/sample.jpg","PACKED","0909056788"],
["takeshi","24/12/2012","BF6464633","Vn-zoom","16 nguyen cuu van, quan binh thanh","http://longvansolution.tk/image/hoadon3.jpg","PACKED","098897657"]
]}
Can you help me!
You may use json_encode() function to do that.
And your JSON format is invalid. Use : instead of =
// SERVER SIDE
<?php
//... create array
//....Obviously you would use your own SQL link and query
$animals = array();
$result = #mysqli_query('YOUR DB LINK', 'YOUR QUERY');
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
array_push($animals, array(
'animal' => $row['animal'],
'sound' => $row['sound']
));
}
?>
// CLIENT SIDE
<html>
<script>
// RETURN FROM PHP PAGE ECHO VIA AJAX PERHAPS //
var animals = <?php echo json_encode($animals) ?>;
$.each(animals, function (i, elem) {
console.log(elem.animal + " makes a " + elem.sound);
});
</script>
</html>

PHP function that decides which HTML code to use?

I'm looking for a function like and if else statement for php which will execute certain html code.
For example:
<?php>
$result = 1;
if ($result == 1)
<?>
html code
else
html code
So, based off the result variable gotten from php scripts, a certain html page is output. I've tried echoing the entire html page, but it just displays the html code-> tags and such.
Hopefully you get what I'm trying to get across, ask if you need any clarification questions. Thanks!
That should work:
<?php
$result = 1;
if($result==1) {
?>
html code
<?php
} else {
?>
html code
<?php
}
?>
The problem I'm facing with the if else statement, is in order to display the html, I have to exit php coding. Thus, the if else statement will not work. (Link)
This is not entirely true. You can use the approach below:
<?php
// Do evaluations
if ( $result == "something" )
{
?>
<p>Example HTML code</p>
<?php
} elseif ( $result == "another thing")
{
?>
<span>Different HTML code</p>
<?php
} else {
?>
<h4>Foobar.</h4>
<?php
}
// Rest of the PHP code
?>
Or, if you don't want to exit PHP coding, you can use the echo or print statements. Example:
<?php
// Evaluations
if ( $result == "foo" )
{
echo "<p>Bar.</p>";
} else {
echo "<h4>Baz</p>";
}
// Some else PHP code
?>
Just be careful with proper sequences of ' and " characters. If your HTML tags are to have arguments, you should watch your step and use either of the following approaches:
echo "<span class=\"foo\">bar</span>";
echo '<span class="foo">bar</span>";
If you want to evaluate some PHP and print the HTML results later, you could use something like this
<?php
$output = "";
if ( $result == "something" ) {
$output = '<p>Example HTML code</p>';
} else if ( $result == "another thing") {
$output = '<span>Different HTML code</p>';
} else {
$output = '<h4>Foobar.</h4>';
}
// Output wherever you like
echo $output;
?>
EDIT (because I'm not sure what you;re trying to do so i'm just putting out different ideas):
If you're trying to output an entire page, it may be useful to use header('location: newPage.html'); instead of $output. This redirects the browser to an entirely new web page. Or you can likely include newPage.html as well.
very close:
<?php
$result = 1;
if ($result == 1){
?>
html code
<?php } //close if
else {
?>
html code
<?php
} //close else
?>
you can echo html code something like this
<?php
$result = 1;
if ($result == 1){
echo "<h1>I love using PHP!</h1>";
}
?>
this would output if Result is 1
**I love using PHP!** //but slightly bigger since its H1

How to get the return from php to javascript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Call php from javascript and return an array from php to Javascript function
i am having an php code for verification of User in XML
For Eg: ValLogin.php
<?php
$userName = $_REQUEST["username"];
$password = $_REQUEST["password"];
$iCount = 0;
$loginArray = array();
$xml = simplexml_load_file("Logintest.xml");
for ($i=0;$i<2;$i++)
{
foreach($xml->Username[$i]->attributes() as $a => $b)
{
$loginArray[$iCount] = $b;
$iCount++;
}
if($userName == $loginArray[0] && $password == $loginArray[1])
{
header("Location: EHP_Configuration.html");
return ;
}
$iCount = 0;
}
echo "<SCRIPT LANGUAGE='javascript'>alert('asd')</SCRIPT>";
header("Location: Login.html");
?>
HTML
<form method = "post" action = "ValLogin.php">
</form>
echo does not work as expected. it directly shows redirect to Login
How can i get the message invalid username/Login?
You cannot send HTML/Data before sending the header, so you'll have to send the javascript-alert inside the "Login.html".
Besides that you really should embrace your Javascript code with
<script type="text/javascript">
alert('asd');
</script>

Categories