Don't know how to solve (Between Php and Javascript) - javascript

I don't know how to solve the variable $cat by following script.
"text" variable from Form to javascript and pass to php function to be $Categories_name and to be $cat.
I already test the $cat variable, it is not "String", it is "object", I don't understand.
But I need $cat to be "String".
when Test = "This is Cat" (3 words),
I test $cat by php str_word_count and the output is 1 (I need to correct answer 3);
I test $cat by php var_dump and no output (I need to correct answer "String").
<p id="CaTable"></p>
<script>
function CaFunction()
{
var text = document.getElementById("CategorySelect").value;
document.getElementById("CaTable").innerHTML = "<?php php_catable('" + text + "'); ?>";
}
</script>
<!-- Generate Table by php and MySQL-->
<?php
function php_catable($Categories_name)
{
$cat = $Categories_name;
.................
.................
$sql = "select * from table where xyz = '" .$cat. "'";
}
?>

You are confusing server side code and client side code. Your php code live on the server and can only be executed on the server. And your javascript is on your client's browser and does not know about the server (remember, php generate a text file, and only that text file is sent to the browser). if you want to use the php_catable() function from your client, you will need to do an AJAX call or to redesign your page to do a form submit (just like what Steve is proposing).

Your First Page:
Assuming CategorySelect is a dropdown select box, create a script for its onChange event and create a method="post"post form with a hidden input that goes to "generate_table.php".
<input type="hidden" name="ca_table" id="ca_table" />
You make ca_table a hidden input so php will pick up the value from it when this page gets submitted to a second page where you can generate your table using the php function.
<script language="javascript" type=text/javascript>
function CaFunction(){
documentGetElementById('ca_table').value = documentGetElementById('CategorySelect').value;
submit();
}
</script>
add this to your select dropdown:
onChange="CaFunction();"
Your Receiving Page:
So your receiving page "generate_table.php" would have
<?php
function php_catable($Categories_name)
{
$cat = $Categories_name;
.................
.................
$sql = "select * from table where xyz = '" .$cat. "'";
}
$category_name = $_POST['ca_table']; // cleaned up at least with suitable preg_replace etc
// and call your catable function
php_catable($category_name);
?>
So that way your result will have been posted back to the server as per comments about client side/server side by #Fluinc and answer by #litelite. To get it to do something which performs looking like innerHTML which changes a part of the page without submitting the whole page you will need AJAX, again as per #litelite's answer.
Might get marked down for being dependant on JavaScript but intended mostly to help clarify client v server.
If you want to avoid the JavaScript dependency of this script you could leave out the onChange altogether and add a submit button, then collect $_POST['CategorySelect']; assuming that is its name - ensure it has name="CategorySelect" for php as well as its Id for your css/javascript. Php gets its variable from the item's name.
To get something a bit like the effect of AJAX visually (though the page is still submitted) you could submit the page to itself using action="<?php echo $_SERVER['PHP_SELF']; ?>" on the form and have all the code on the one page. You can put the table generating code in the div where you want the table to appear - it would need a default state set, of course.
#litelite's comment regarding not using posted data directly in an sql query is also vital to prevent attack - make sure you clean it up before you use it!

Related

How to prevent file declared in <form action="process-form.php"> from showing results to users when form is submitted?

I have a form with a form-handler 'process-form.php. This form works as planned, however, whenever the form is submitted, before redirecting the user to another URL, (say, thank-you.html) it is showing the contents received from the form in process-form.php. How can I prevent that from happening?
if ($mail->send())
{
?>
<script type="text/javascript">
alert('Message Sent!');
window.location.replace("thank.html");
</script>
<?php
}
else
{
echo "<script type='text/javascript'>alert('ERROR!');</script>";
}
You mean shown in the URL, or is it in the HTML of the page? If it is the former, you can use
<form method="POST" ...>
If you mean the latter, you should change your PHP / JavaScript to not show the data
Hey so the issue you're seeing is that not all form fields are filled in so that you get an undefined variable error and you don't want users to see that.
Usually in a production environment (like my shared server) errors are hidden anyway just not on my localhost. To hide the errors though you can just use this:
error_reporting(0);
ini_set('display_errors', 0);
However, You'd be much better off making sure there was no error in the first place. To do this check if the fields were actually filled in otherwise set your variable equal to nothing so technically it will still exist even if it is blank.
if(isset($_POST['my_var'])){
$my_var = $_POST['my_var'];
}else{
$my_var = "";
}
You can also use the same if(isset()) logic where you are actually using the variables rather than where you set them

UPDATE SQL table to change timestamp

I am using php to display an SQL table. When the user selects a row on the table and then clicks a button, I want it to update the timestamp to the current time and appear on the table displayed on the webpage. The SQL query I am using works, however when I click the button, it doesn't change the values in the database, nor does it change anything displayed in the table either. The code I am using is:
I've tried CURRENT_TIMESTAMP and GetDate();, however neither seems to be what I am looking for.
So if the SignOut value is currently at 00:00, I want it to be updated to the current time.
The button appears in the following table:
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>"."<td>". $row["StudentNum"]. "</td>". "<td>". $row["Name"]."</td>"."<td>".$row["Location"]."</td>"."<td>". substr($row["HomeTime"],0,-3)."</td>"."<td>".substr($row["SignOut"],11,-10)."</td>"."<td>"."<center>"."</center>"."</td>"."<td>"."</td>"."</tr>";
}
}
else {
echo "0 results";
}
The script to add the time:
<script type="text/javascript">
var _common;
$("#table tr").click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
var value=$(this).find('td:first').html();
_common = value;
});
function select(){
alert(_common);
<?php
$signingout = "UPDATE signon SET SignOut=CURRENT_TIMESTAMP WHERE StudentNum= '_common'";
mysqli_query($conn, $signingout);
?>
}
</script>
You are can't mix together client side code and server side code.
PHP is a server side code and can not be mixed with the javascript.
Javascript is a client side code and only lives in the browser, therefore can't be used to contact the database.
So you need to start with isolating your code. Make a new file on the server that contains the php code and call it with javascript and re-render the side with the new values.

Passing JavaScript Codes via PHP POST

I have two textareas, an iframe and a submit button. They are all in the same page. What I want to do is that; user will code some html and javascript codes in to the first textarea. the second one is already hidden to pass the javascript codes. After the user click submit button, s/he will see results in the iframe. actually what i am saying is something like w3school's trying page.
my submit button is:
<INPUT type="submit" value="Run the Codes" name="submit" onclick="sendthem()">
my textarea's are:
<TEXTAREA id="textareaCode1" style="WIDTH:100%;HEIGHT:400px" name="code22" rows="21" wrap="logical" cols="42"><?=$code;?></TEXTAREA> //the user's textarea
<textarea id="textareaCode" style="WIDTH:100%;HEIGHT:400px" name="code" rows="21" wrap="logical" cols="42"><?=$code;?></textarea> //this is actually hidden (style="display:none;") one but to see what happens, temporary i made it visible.
and my sendthem() function is:
function sendthem()
{
var t=document.getElementById("textareaCode1").value; //the visible textarea
t=t.replace(/</g,"SMALLER"); //string manipulation to pass js codes via php post
t=t.replace(/>/g,"GREATER"); //string manipulation to pass js codes via php post
t=t.replace(/=/g,"EQUAL"); //string manipulation to pass js codes via php post
document.getElementById("textareaCode").value=t; //manipulated code goes in to hidden textarea
document.getElementById("sampleform").submit(); //send the form
}
And my php code is:
<?
$code = $_POST['code'];
echo "$code"; // here i can see the manipulated code like "SMALLERhtmlGREATER"
?><br/><? // to try it :
$code = str_replace("GREATER", ">", $code); // I reverse the changes
$code = str_replace("EQUAL", "=", $code);
$code = str_replace("SMALLER", "<", $code);
printf("%s",$code); //and there is no js codes.. i tried echo or other php print commands also.
?>
Here is a screenshot http://i57.tinypic.com/sghcba.png (I hope it helps)
Now.. I think my problem is in the PHP part. Can anyone tell me why I can't see the JS part of code, after reversing changes ?
And please, I don't want to change all my codes with jQuery or AJAX etc.. I want to fix this code. Thanks in advance...

JavaScript variable passed to PHP

I'm working on a form that adds up the totals selected (via checkboxes). In my JavaScript file, build.js, the totals are added together. On my PHP page, the code takes the items selected on the previous form/HTML page and passes them to what is shown on the PHP page. I want to be able to take the total that was added up via JavaScript on the form page and bring it over to be listed as a total underneath all the options that were selected.
My knowledge of PHP and JavaScript are very rudimentary. This is the first real form I have created in either of these languages. I have poured over this site and the internet in general and have not been able to get any of the options I've found to work. I think I just lucked out on getting the form this far, so I apologize if my code isn't very clean!
Any help would be amazing, as specific as possible please. Here is my code:
The JavaScript that adds the total:
$(document).ready(function() {
$("input[type=checkbox]:checked").attr("checked", false);
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel"));
});
$("#output").html(sum);
}
$("input[type=checkbox]").change(function() {
recalculate();
});
});
Code written on the form itself that shows the total:
<span id="output" class="total"></span><BR><BR>
Code written on the PHP page:
<b>Estimate:</b>
<?php
$aTruck = $_POST['formSelected'];
if(empty($aTruck))
{
echo("You didn't select a truck.<BR><BR>");
}
else
{
$N = count($aTruck);
echo("<h3>Truck Type: ");
for($i=0; $i < $N; $i++)
{
echo($aTruck[$i] . " ");
}}
$aAddons = $_POST['formAddons'];
if(empty($aAddons))
{
echo("You didn't select any options.");
}
else
foreach ($aAddons as $v)
{
echo "<h3> $v </h3>";
}
?>
If I'm not mistaken, the reason I can't currently pass the total is because of something I read on here: the PHP is run on the server while the JavaScript runs on the user's end. My options are thus to send the total in the form (possibly as a hidden variable, which I can't figure out either), pass it along in Ajax (I don't know if the server I'm on is capable of this- possibly so and it's all use error!), or use an XMLHttpRequest. I've tried anything I could find on any of those and either do not have the right variable listed inside, am placing it in the wrong spot, or it's just plain wrong.
As I mentioned, I've poured over the forums for everything I can that's related to this and nothing I've found is specific enough for the tiny bit of understanding I have. Among other things I've tried: Pass a javascript variable value into input type hidden value and Pass Javascript Variable to PHP POST along with using an XMLHttpRequest, using Ajax, passing it as a hidden variable (which I'm leaning towards but don't think I'm implementing correctly) and a ton more- it's pretty much all I did all day at work yesterday so I'm not trying to be redundant with my question- I just can't figure out where I'm going wrong.
It looks like you hit upon it right here:
send the total in the form (possibly as a hidden variable)
Since you're talking about one page posting to another page, and that other page showing the results, then there's no need for AJAX here. You can just use a form value like any other. The "hidden variable" in this case is actually an input element:
<input type="hidden" name="sum" />
In your JavaScript where you're displaying the sum on the first page:
$("#output").html(sum);
You can also set that sum to the form element's value:
$("#output").html(sum);
$("input[name=sum]").val(sum);
As long as that input is inside the same form as the other input elements (like formSelected and formAddons) then when the first page posts to the second page, the code in the second page can access the sum value the same way:
$_POST["sum"]
In your form you should add a hidden input like this :
<input type="hidden" name="sum" value="">
Then in your recalculate() (javasript) function, you should change the value of this input once you calculated everything :
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel"));
});
$("#output").html(sum);
// Change the hidden input value
$("input[name='sum']").val(sum);
}
Now, when your form is submitted, you should access the sum value, server side (PHP), with a simple :
$sum = $_POST['sum'];

Execute script when select option is changed

I have a html form which includes a dynamically created dorpdown list. The dropdown list contains the names of newsletters which are stored in my MySQL database. What I want the dropdown list to do is: When I select a newsletter an other php script will activate which will take the data from the newsletter in my DB and writes it to a .txt file. The codes I currently have is:
The dropdown list:
<?php
echo "<select id=\"NieuwsbriefSelect\" name=\"show\">";
echo "<option size =30 selected>Select</option>";
if(mysql_num_rows($sql_result))
{
while($row = mysql_fetch_assoc($sql_result))
{
echo "<option value=\"$row[Titel]\">$row[Titel]</option>";
}
}
else {
echo "<option>No Names Present</option>";
}
?>
And the write script:
<?php
$title = $_REQUEST["show"];
mysql_connect('localhost','root','root');
mysql_select_db('NAW') or die (mysql_error());
$strSQL = "SELECT Content from NAW.Mail where Titel = '$title' ";
$sql_result = mysql_query($strSQL);
$row = mysql_fetch_assoc($sql_result);
$file = 'nieuwsbrief.txt';
$current = $row["Content"];
file_put_contents($file, $current);
?>
I do not want the page to redirect to the write script but just to execute it (I hope you get this^^). Is this possible using the HTML onChange Event or do I have to use javascript? Any help would be great and if you have a question about my code just ask in the comments!
NOTE!
I know I shouldn't be using Mysql_* and That I am vulnerable to sql injection but that is not the point.
You need to define a onchange event on your SELECT option and inside this onchange event, you can redirect to another page with selected item OR do an AJAX call to another PHP script
Unfortunately what you are asking is not possible without JavaScript. PHP is a server side language and therefore cannot be run, without a call from the client-side browser. You're best bet would be to use ajax in conjunction with the JavaScript onchange event. When the change event occurs, fire an ajax call off to the server to run the script with the selected option. This is the only way to do what you're asking without a page reload or redirect.

Categories