Passing javascript array via POST to PHP does not working - javascript

I need to pass a javascript array, via POST, to a PHP file.
I've tried to semplify my original business trying to explain my troubles ...
This is my first PHP file, in which I declare a javascript array and I set each element to 1 value (not a great business I know, but it doesn't matter, it's only to explain ....)
<?php
echo '<form action="testPhp-2.php" method="POST" target="testPhp-2">';
echo '<script type="text/javascript">';
echo 'var arr_selections = [];';
echo 'for(i=0; i < 10; i++)';
echo ' {';
echo ' arr_selections[i] = 1';
echo ' }';
echo 'arr_selections_json = JSON.stringify(arr_selections);';
echo 'alert (arr_selections[2]);';
echo 'document.write("<br/>");';
echo ' ';
// echo 'document.write("<input type="hidden" />");';
echo 'document.write("<input type=\"hidden\" name=\"arr_selections_json\" value=\"arr_selections_json\" />");';
echo ' ';
echo '</script>';
echo ' <input type="submit" value="Controlla">';
echo ' </form>';
?>
.... and here you are the code of testPhp-2 file ...
<?php
if(isset($_POST['arr_selections_json']))
{
echo "OK, array exist !! ";
echo '</br>';
echo '</br>';
$arr_selections = json_decode($_POST['arr_selections_json'], true);
echo $arr_selections[0];
}
else {
echo "NO; array does not exist !! ";
echo '</br>';
echo '</br>';
}
?>
Now, if you try to execute the code you'll see the OK, array exist !! message but no array value is printed about the echo $arr_selections[0]; line of code in testPhp-2.php file.
Any suggestion will be appreciated! Thank you in advance!
Cesare

Problem is that you're setting the value of the input to the litteral string "arr_selections_json" instead of to the contents of that variable.
Change
echo 'document.write("... value=\"arr_selections_json\" />");';
To
echo 'document.write("... value=\""+arr_selections_json+"\" />");';

Related

define javascript variable from php variable within php code

I am trying to define javascript variable from php variable in the running php code.
Here is my code:
echo "<script>";
echo "var s1 = '<?php echo isset($s1) ? $s1 : '' ?>';";
echo "getAirdrop();";
echo "</script>";
But this code not defining the javascript variable.
You don't need php tags again.
Try it like this:
echo "<script>";
echo "var s1 = '";
echo isset($s1) ? $s1 : '';
echo "';";
echo "getAirdrop();";
echo "</script>";
You can do it in one line, just concatenate all yours echo :
echo "<script> let s1 = ".isset($s1) ? $s1 : ''." getAirdrop(); </script>"

cant echo javascript alert from php

I've looked for an answer already, but I understand how to achieve an alert from php I just don't know what I am doing wrong on this particular piece of code.
I had this working until I added the if statement.
if ($errors) {
echo "<script type='text/javascript'>";
echo "alert('Records Were Uploaded');";
echo "window.location.href = 'EmployeePicker.php';";
echo "</script>";
} else {
echo "<script type='text/javascript'>";
echo "alert('There was a problem with your file');";
echo "window.location.href = 'csvUpload.php';";
echo "</script>";
}
It worked fine when it was just .
echo "<script type='text/javascript'>";
echo "alert('Records Were Uploaded');";
echo "window.location.href = 'EmployeePicker.php';";
echo "</script>";
If comment everything out and just do
echo "<script type='text/javascript'>";
echo "alert('There was a problem with your file');";
echo "window.location.href = 'csvUpload.php';";
echo "</script>";
this will not work. I'm so confused. It doesn't make sense why the second alert doesn't work.
I forgot to mention, In the if statement from above the first alert will work, it's that second alert that I can't get to fire.
Sorry about the confusion, the $error is a bool. If it is true a filw was uploaded, if false it wasn't.
I think you are doing the opposite of what you want:
Your if case doesn't match the action performed inside.
Maybe you should do:
if (!$errors) {
echo "<script type='text/javascript'>";
echo "alert('Records Were Uploaded');";
echo "window.location.href = 'EmployeePicker.php';";
echo "</script>";
} else {
echo "<script type='text/javascript'>";
echo "alert('There was a problem with your file');";
echo "window.location.href = 'csvUpload.php';";
echo "</script>";
}
and you can also save up on echo words - and make it more readable - doing sth like:
echo <<<HTML
<script type='text/javascript'>
alert('Records Were Uploaded');
window.location.href = 'EmployeePicker.php';
</script>
HTML;
just if you want :)
[EDIT] Note that according to what $errors hold (either integer or array), you can check that there is no error by either !$errors if integer or !count($errors) if array.
[EDIT] Trying your second piece of code as a standalone
If you need to trace what is wrong you need to isolate bit by bit!
first try code 1 as a new php file if it does not alert and redirect on your system then something is wrong in your configs.
If it works something is wrong in your code logic.
I could also run code 2 with no pb by first setting the $errors var to 1 or 0.
code 1
<?php
$errors = 1;
echo "<script type='text/javascript'>";
echo "alert('There was a problem with your file');";
echo "window.location.href = 'csvUpload.php';";
echo "</script>";
?>
code 2
<?php
$errors = 1;
if ($errors) {
echo "<script type='text/javascript'>";
echo "alert('Records Were Uploaded');";
// echo "window.location.href = 'EmployeePicker.php';";
echo "</script>";
} else {
echo "<script type='text/javascript'>";
echo "alert('There was a problem with your file');";
// echo "window.location.href = 'csvUpload.php';";
echo "</script>";
}
?>
And about your $errors var, if true means no error you should definitely rename it to sth less tricky like $uploadSuccessful. ;)
It should echo out good. Try checking your php error log file to see if there are any clues as to the issue in there.
Just a small most like likely personal preference of mine that may help you is to separate out the logic a bit. Please see below.
<?php
// STATUS
$errors = true;
// OUTPUTS
$upload_success = "<script type='text/javascript'>";
$upload_success .= "alert('Records Were Uploaded');";
$upload_success .= "window.location.href = 'EmployeePicker.php';";
$upload_success .= "</script>";
$upload_fail = "<script type='text/javascript'>";
$upload_fail .= "alert('There was a problem with your file');";
$upload_fail .= "window.location.href = 'csvUpload.php';";
$upload_fail .= "</script>";
//LOGIC
if ($errors) {
echo $upload_success;
} else {
echo $upload_fail;
}
?>

Wordpress - Unable to use variable

Testing out Wordpress on WAMP by creating a basic plugin.
Scenario:
Created an Admin panel with a form that just contains a text area and button. The form will be used to insert JavaScript code and this code will be placed in the header of all pages. I'm having issues trying to access the text area value within function post_tag. Code below:
<?php
add_action('admin_menu', 'setup_menu');
function setup_menu(){
add_menu_page( 'Tag Menu', 'Tag Menu', 'manage_options', 'tag-menu', 'html_form' );
}
function html_form(){
echo '<h1>JavaScript Tag</h1>';
echo '<form action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post">';
echo '<p>';
echo 'Paste your code below: <br/>';
echo '<br/>';
echo '<textarea rows="10" cols="150" name="tag"></textarea>';
echo '</p>';
echo '<p><input type="submit" name="tag-submit" value="Submit"></p>';
echo '</form>';
if(isset($_POST['tag-submit'])){
$tag = esc_textarea(stripslashes($_POST["tag"]));
echo '<p>Your tag has been placed on all pages!</p>';
return $tag;
}
}
$value = html_form();
add_action('wp_head', 'post_tag');
function post_tag(){
global $value;
$output = $value;
echo $output;
}
?>
Can't seem to output the value in $tag to the header pages.Any help would be much appreciated.
If you don't have any reason to structure it the way you did, try this, which is cleaner
add_action('wp_head', 'post_tag');
function post_tag(){
$output = html_form();
echo $output;
}

How to retrieve $_SESSION value in a JavaScript/HTML

I have this working script yet when I change it to retrieve(supposedly) the value inside $_SESSION["username"], it doesn't retrieve anything. The whole page is saved as .php as I am using some codes that uses PHP.
Code:
echo "<script type=text/javascript>";
echo "var hidden = false;";
echo "function actiondb1() {";
echo "if(!hidden) {";
echo "document.getElementById(\'clickdb1\').style.visibility = \'hidden\';";
echo "document.getElementById(\'db1\').style.visibility = \'visible\';";
echo "document.getElementById(\'db1\').disabled = false;";
echo "document.getElementById(\'db1\').value =".$_SESSION["username"];.";";
echo "}";
echo "}";
echo "</script>";
How can I make the script to properly retrieve the data inside $_SESSION["username"];?
Observe that, for instance, if the value of $_SESSION["username"] is John, your echo will be generating this result:
document.getElementById('db1').value = John;
But John is supposed to be a string and should be wrapped in quotation marks, otherwise JavaScript will understand it as a variable name (which value will be probably undefined).
As Havenard mentioned, this line is missing Javascript single quotes to properly denote a string variable:
echo "document.getElementById(\'db1\').value ='".$_SESSION["username"];."';";
However, you really shouldn't print JS out with PHP if you can help it. Though iatboy's answer answer won't ultimately fix your bug, it is a much cleaner way of doing things.
?>
<script type=text/javascript>;
var hidden = false;
function actiondb1() {
if(!hidden) {
document.getElementById('clickdb1').style.visibility = 'hidden';
document.getElementById('db1').style.visibility = 'visible';
document.getElementById('db1').disabled = false;
document.getElementById('db1').value ='<?php echo $_SESSION["username"];?>';
}
}
</script>;
<?php
Did you start session in this page?If you didn't,use the follow code to start session.
session_start();
Then change your code to
echo "<script type=text/javascript>";
echo "var hidden = false;\n";
echo "function actiondb1() {\n";
echo "alert('".$_SESSION['username']."')\n"; //test code
echo "if(!hidden) {\n";
echo "document.getElementById('clickdb1').style.visibility = 'hidden';\n";
echo "document.getElementById('db1').style.visibility = 'visible';\n";
echo "document.getElementById('db1').disabled = false;\n";
echo "document.getElementById('db1').value ='".$_SESSION["username"]."';\n";
echo "}\n";
echo "}\n";
echo "</script>";
it will be ok.

I am trying to update records by php code. but having trouble in my code

I am trying to update records by php code. but having trouble in my code.
code is running without using functions (get40(),show()) but i want to use buttons to call these functions.
code is give below:
this is main code file:
<?php
$data;
$count=0;
$host='localhost';
$uname='root';
$pass="";
$dbname="testing";
$db=new mysqli($host,$uname,$pass,$dbname);
$result;
$query;
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
function get40($off='0', $rcd='2')
{
global $db,$result,$query;
$query="SELECT sword, tword, reviewed from TempDictionary LIMIT $off,$rcd";
$result = $db->query($query)or trigger_error($db->error);
}
function show()
{
global $db,$result,$query;
echo "<form action='testSave.php' method='POST'>";
echo "<table border=1 >";
while($row = mysqli_fetch_array($result))
{
global $count;
$count+=1;
echo "<tr>";
echo "<td><input type='text' name='s[]' value=" . $row['sword'] . "></td>";
echo "<td><input type='text' name='t[]' value=" . $row['tword'] . "></td>";
echo "<td><input type='text' name='r[]' size='1' value=" .$row['reviewed'] . "></td>";
echo "</tr>";
}
echo "</table>";
echo "<input type='text' name='no' size='2' value=" .$count. ">";
echo "<input type='submit' value='Save'>";
echo "</form>";
}
//get40(1,2);
//show();
mysqli_close($db);
?>
<script type="text/javascript">
function get()
{
<?php
get40(0,3);
show();
?>
}
</script>
<form action="" method="POST">
<input type=button name=btnGet value=Get onclick="get()">
</form>
and savetest.php file is:
<?php
$no=$_POST['no'];
$i=0;
$s=$_POST['s'];
$t=$_POST['t'];
$r=$_POST['r'];
$host='localhost';
$uname='root';
$pass="";
$dbname="testing";
$db=new mysqli($host,$uname,$pass,$dbname);
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
// display
foreach ($s as $key=>$value)
{
print "$key = $value $t[$key] $r[$key]";
echo '<br>';
}
// save to DB
foreach ($s as $key=>$value)
{
// $query="UPDATE TempDictionary set sword=".$value.",tword=".$t[$key].",reviewed=".$r[$key]."
// WHERE sword=".$value;
$query="UPDATE TempDictionary set sword='$value',tword='$t[$key]',reviewed='$r[$key]'
WHERE sword='$value'";
$result = $db->query($query)or trigger_error($db->error);
}
mysqli_close($db);
?>
the problem is while i click button it does not works.
AFAIK you are trying to run PHP code with Javascript code.
Use Jquery/Ajax to solve your problem. You can Google for that or look at stackoverflow.
Step 1: Learn how a click on a button can run PHP
Run php function inside jQuery click
Step 2: Learn how to use data from a database and populate a form with it:
ajax call to populate form fields from database query when select value changes
That's the first step in solving your problem. (sorry it's no copy/paste solution, just a pointer in the right direction)

Categories

Resources