POST array data in php - 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

Related

PHP Static variable reloads after Page Load

This is a simplified version of what I want to accomplish:
In my script I want a static variable x to be incremented every time the submit button is pressed.
<?php
function IncX(){
static $x = 0;
$x++;
echo $x;
}
?>
<body>
<form>
<input type="submit" name="submit" class="next btn btn-primary" value="Submit" />
</form>
</body>
But it initializes to x=0 on every page reload after submit.
You're loading the variable afresh every time the page loads, so it's always going to be the same.
The solution is to store it in a session and then increment it there. Include a conditional to create the variable if it doesn't already exist.
<?php
session_start();
if (!isset($_SESSION['x'])) {
$x = $_SESSION['x'];
} else {
$x = 0;
}
$x++;
echo $x;
$_SESSION['x'] = $x;
?>
<?php
session_start();
$x = 0;
if (isset($_SESSION['x'])) {
$x = $_SESSION['x'];
$x++;
} else {
$_SESSION['x'] = $x;
}
// /$x++;
echo $x;
$_SESSION['x'] = $x;
?>
Apache doesn't keep track of variables in php scrips between clicks, you would have to store it somewhere, be it the $_SESSION or a database.
Moreover, the static keyword doesn't do what you seem to think it does. It would work for successive calls of the function in a single run of the script, but not between clicks.
in any event, you can use the ternary operator to achieve this, would you happen to put it in the session. I've also added a check to make sure the variable is actually a viable count number:
session_start();
$_SESSION['x'] = isset($_SESSION['x']) && is_int($_SESSION['x'])
? $_SESSION['x'] + 1
: 1;
echo $_SESSION['x'];

PHP If / Else statement going directly to the Else without waiting for form input

Ok so I have a form with 1 input and a submit button. Now I am using an if/else statement to make three acceptable answers for that input. Yes, No, or anything else. This if/else is working the thing is the code is kicking out the else function as soon as the page is loaded. I would like there to be nothing there until the user inputs then it would show one of three answers.
Welcome to your Adventure! You awake to the sound of rats scurrying around your dank, dark cell. It takes a minute for your eyes to adjust to your surroundings. In the corner of the room you see what looks like a rusty key.
<br/>
Do you want to pick up the key?<br/>
<?php
//These are the project's variables.
$text2 = 'You take the key and the crumby loaf of bread.<br/>';
$text3 = 'You decide to waste away in misery!<br/>';
$text4 = 'I didnt understand your answer. Please try again.<br/>';
$a = 'yes';
$b = 'no';
// If / Else operators.
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
}
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
?>
<form action="phpgametest.php" method="post">
<input type="text" name="name" /><br>
<input type="submit" name="senddata" /><br>
</form>
You just need to call the code only when the POST value is set. This way it will only execute the code when the form was submitted (aka $_POST['senddata'] is set):
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
}
Just put the validation in the first if statement like this:
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a) {
echo ($text2);
} elseif ($usertypes == $b) {
echo ($text3);
} else {
echo ($text4);
}
}
When you load your page the browser is making a GET request, when you submit your form the browser is making a POST request. You can check what request is made using:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Your form was submitted
}
Put this around your form processing code in order to keep it from being executed on GET request.

Javascript in while loop not changing anything until the loop finished

I have 2 seperate files.
The iframe executes the changePercent command in the parent window, but it doesn't change the number instantly, it is only changed after the loop finished. Is there any way to fix this? Need this for a progress bar thingy.
Thanks in advance!
This is the file I open in my browser
<span id="test">1</span><br />
<iframe src="script.php?league=Nemesis"></iframe>
<script type="text/javascript">
function changePercent(val) {
document.getElementById("test").innerHTML=val;
}
</script>
This is the embedded iframe
<?php set_time_limit(0);
include('../assets/includes/functions.inc.php'); ?>
<?php
$i = 0;
$step = 200;
$end = 15000 - $step;
$league = $_GET['league'];
$found = false;
$status = false;
while ($found == false && $i < $end) {
if($i < $end) { $i = $i + $step; }
$ladder = file_get_contents("http://api.pathofexile.com/ladders/".$league."?limit=".$step."&offset=".$i);
$ladder = str_replace('"online":false', '"online":"no"', $ladder);
$ladder = str_replace('"online":true', '"online":"yes"', $ladder);
$json = json_decode($ladder, true);
foreach ($json['entries'] as $address) {
if($address['online'] = "yes") {
$status = true;
// do something
}
}
?>
<script type="text/javascript">
parent.changePercent('<?php echo $i ?>');
</script>
<?php
}
?>
php is a server side language. when the php runs the while loop, that means the browser is still waiting for page data, and it will be sent to the browser only when the php is finished.
in your changePercent you have a php code that is located AFTER the while loop, so it will run the while loop before it can evaluate the php inside the changePercent
so there is no "fix", you should just learn the basics of web programming
You're exiting out of the PHP loop when you use ?> try the following code segment.
echo '<script type="text/javascript"> parent.changePercent(' . $i .'); </script>';
This will tell PHP to print out that line for each time your loop executes through.

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" ...

My $_SESSION variable will not hold its value. Any Ideas on why?

I want it to increment and decrement the value in $_SESSION['selection'].
Mousedown on next form results in: "The session is 1".
Mousedown on previous form results in "The session is -1".
Here is the code:
<?php
if (isset($_POST['next'])) {
displaynext();
}
else if (isset($_POST['previous'])) {
displayprevious();
}
else {
session_start();
echo "session started";
$_SESSION['selection'] = 1;
}
function displaynext() {
$_SESSION['selection'] = $_SESSION['selection'] + 1;
echo "The session is $_SESSION[selection]";
}
function displayprevious() {
if ($_SESSION['selection'] != 1) {
$_SESSION['selection'] = $_SESSION['selection'] - 1;
}
echo "The session is $_SESSION[selection]";
}
?>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<input type="submit" name="previous" value="Previous">
</form>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<input type="submit" name="next" value="Next">
</form>
Put the session_start() call on the beginning of your file; right after the <?php open tag. You also need to do that on every script that you plan to use sessions.
By the way, instead of writing:
$_SESSION['selection'] = $_SESSION['selection']-1;
$_SESSION['selection'] = $_SESSION['selection']+1;
You can use
$_SESSION['selection']--;
$_SESSION['selection']++;
Read: Increment/Decrement operators
Make sure you're using session_start() on every page you use your session on.
Put the session_start call to the beginning of your code, outside of any conditions.
session_start needs to be called in every script you're using the session in, not just at the very beginning (ie. the first pageload).
You're not calling session_start when moving between pages. Move the call to before the if statements, like this:
session_start();
if(isset($_POST['next'])) {
displaynext();
} else if(isset($_POST['previous'])) {
displayprevious();
} else {
echo "session started";
$_SESSION['selection'] = 1;
}

Categories