JavaScript onsubmit event won't update html form action property - javascript

I'm trying to update the action property of the form tag by calling a JavaScript function when a user presses the submit button. The action property is updated depending on what is selected in the select box called "proceed". However the following script does not work and I don't know why.
Javascript:
<script type="text/javascript">
function updateAction() {
<?php
if (empty($errors) && isset($_POST['submit'])) {
echo 'document.newStudent.action = document.newStudent.proceed.value';
} else {
echo 'document.newStudent.action = "newStudent.php"';
}
?>
}
</script>
<form name="newStudent" method="POST" onsubmit="updateAction()">
Select box which is much further down in my code:
<?php //PROCEED
echo '<tr>';
echo '<td><p>Proceed To:</p></td>';
echo '<td>
<select name="proceed">
<option value="newSchedule.php">add student\'s schedule</option>
<option value="newStudent.php">add another student</option>
<option value="staff.php">staff page</option></td>';
echo '</tr>';
?>

You can not write PHP code inside a JavaScript method like that. You have to understand difference between server-side scripting and client-side scripting. In your scenario write a JS code which accomplish your task. Read this Client side vs server side basics, PHP vs JavaScript For Dynamic HTML Pages
Javascript and PHP allow website developers to create dynamic Web pages. Javascript is a client-side language, so it runs on the reader's computer. PHP is a server-side language, so it runs on the Web server. These two languages are combined to create interactive website's for readers. Each of these languages are combined, but they interact with the Web browser differently.
There are situation you can write PHP inside a Javascript function but not in your scenario.
Read More

Related

Php code to modify a document element

I am trying to build a PHP webpage with the following behaviour:
1- A client access the webpage (that contains some buttons);
2- When the webpage is loaded, the PHP script opens a file stored on the server and, based on the information in this file, enables/disables some of the buttons, so that the client can see the webpage with the correct buttons enabled or disabled.
To enable/disable buttons, I know I can use javascript, while to read the file on the server I use PHP as stated above.
How do I put the two things together? Or should I use a PHP code equivalent to the following javascript line:
<script>document.getElementById("button1").disabled = true;</script>
At first I thought that inserting this line in the PHP code was the solution, but then I found out that this can't work for obvious reasons.
Thanks for the help!
Is it correct if I add the following javascript function in the head section of my webpage?
<script>
function enableButtons() {
<?php
if($state=="state1") {
echo 'document.getElementById("button1").disabled = true;';
}
else if($state=="state2") {
echo 'document.getElementById("button2").disabled = true;';
}
?>
}
</script>
I call the enableButtons() function when loading the page by using
<body onload="enableButtons()">
The php code above is just an example, the number of states and buttons is higher, that's why I would like to use this solution.
The common thing to do is to have php read the settings file, and echo the "disabled" attribute on the buttons before sending the output to the user browser. You can get more info about the attribute here here.
You do not need javascript.
Do something like this:
<button type="button" <?php if($state === 'state1') echo 'disabled'; ?>>Button text</button>
Usually you send to the client the buttons already disabled and use js to respond to any event that happens after sending the page, like selecting a combo box value..
You can omit the code, using an if sentence, or hide them using css. First approach is preferred.
Script
<script>
function isValid(f){
if(f.test.value==''){
alert('please enter name');
return false;
}else{
$(".bbutton").html("Processing please wait");
return true;
}
}
</script>
HTML
<form method="post" onsubmit="return isValid(this);">
<input type="hidden" name="te">
<input type="text" name="test">
<div class="bbutton">
<input type="submit" value="send">
</div>
</form>
When you submit the form then it will automatically hide the submit button to avoid pressing again and again, and you can redirect it to other page. May be this idea helpful.

Jquery and AJAX script to run a PHP script in the background to avoid any refreshing

I have built a follow/unfollow Twitter like system using PHP. Now I would like to run the follow-unfollow PHP script in the background using AJAX/JQUERY to avoid refreshing the page when you follow/unfollow a user. To make things simpler, I will be here just using the example of “unfollow”. As you notice, I am running an iteration to output all the members in the database. I am outputting here (as well for simplicity) just the member’s name and an unfollow button to each one.
This is the code using php.
members.php
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member->name; ?></p>
<p class="follow_button">Unfollow</p>
<?php } ?>
unfollow.php
<?php
if($_GET['unfollow_id']){
$unfollow_id=$_GET['unfollow_id'];
$unfollow=Following::unfollow($id, $unfollow_id); //Function that will make the changes in the database.
// $id argument will be gotten from a $_SESSION.
}
I am trying to achieve the same result running unfollow.php in the background to avoid any refreshing. This is what I have come up with, as you might imagine it is not working properly. I am including the Jquery script inside the iteration which I think is the only way of obtaining the $member->id property to then assign it to the Jquery variable.
members.php THE NEW ONE THAT TRYS TO RUN THE SCRIPT WITH AJAX JQUERY
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member_name; ?></p>
<button type="button" class="unfollow_button" id="unfollow">Unfollow</button>
<script type="text/javascript">
$(document).ready(function(){
$("#unfollow").click(function(){
// Get value from input element on the page
var memberId = "<?php $member->id ?>";
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data){
// Success
});
});
});
</script>
<?php } ?>
Can you provide me any help for this to work?
Thanks in advance.
Remember, in HTML, id attributes have to be unique.
Because you're rendering multiple members on a single page, you should not use an id selector in jQuery, but a class selector (e.g. button.unfollow). If you use #unfollow, you'll run into ID conflicts between each of the members' buttons.
First, render all of your members with unfollow buttons without ids. I'm adding the member_id in the markup using a data attribute called data-member_id.
<?php foreach($members as $member) { ?>
<p class="member_name"><?=$member_name?></p>
<button type="button" class="unfollow_button" data-member_id="<?=$member->id?>">Unfollow</button>
<?php } ?>
Then add a single click handler for all button.follow buttons, which extracts the member_id from the clicked button's data-member_id attribute and sends it to the server.
<script type="text/javascript">
$(document).ready(function() {
$("button.unfollow_button").on('click', function() {
// Get value from input element on the page
var memberId = $(this).attr('data-member_id');
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data) {
// Success
});
});
});
</script>
On a side-note, you should probably look into building a RESTful service for this, to which you can post proper HTTP requests using http://api.jquery.com/jquery.ajax/.
See here for an intro on REST in PHP I wrote a while back:
Create a RESTful API in PHP?

Javascript input issue

I have written a code for redirecting the page on submitting the form.
I have a drop down and textbox in that form.
I typed </script> as input for the textbox , which had lead to normal excution but with ); on screen.
this is what i got from my firebug tool
<script type="text/javascript">
loadSearch('Customer','
</script>
');
PHP CODE for submit
<?php
if($_POST['searchButton']){
echo "<script type='text/javascript'>loadSearch('".$_REQUEST['search_details']."','".$_REQUEST['search_input']."'); </script>";
}
?>
JAVASCRIPT
function loadSearch(selM,selK){
document.location.href="index.php?pg=search&selM="+selM+"&selK="+selK;
}//loadSearch
Note: $_REQUEST['search_input'] is the textbox and if the textbox is given with </script> as input
There is a severe vulnerability in you server side code. You should always clean strings which arise from user inputs using methods like htmlspecialchars.
Replace :
$_REQUEST['search_details']
and
$_REQUEST['search_input']
With :
htmlspecialchars($_REQUEST['search_details'], ENT_QUOTES, 'UTF-8')
and
htmlspecialchars($_REQUEST['search_input'], ENT_QUOTES, 'UTF-8')
Not doing this can make your website vulnerable where a malicious user could include scripts to snoop on your users. What this function does is convert special characters like < to html HTML character entities like < so that it can't be interpreted as code by the browser on the client side.
The problem is that you are dumping the request values into your page without doing any escaping of them. Since this is JavaScript, one quick fix is to use json_encode() to encode the values as JSON:
<?php
if($_POST['searchButton']){
echo "<script type='text/javascript'>loadSearch(".
str_replace(json_encode($_REQUEST['search_details']), '<', '\x3C') . ", " .
str_replace(json_encode($_REQUEST['search_input']), '<', '\x3C').
");</script>";
}
?>
Also, your function should be using encodeURIComponent():
function loadSearch(selM,selK){
document.location.href="index.php?pg=search&selM="+
encodeURIComponent(selM) + "&selK=" +
encodeURIComponent(selK);
}
But the question remains: if what you really want to do is redirect the user to a search page, why are you using this roundabout script approach in the first place? Why not just do a redirect directly from your PHP?
\Why do you not consider to use plain javascript without any php?
<input type="text" id="selM">
<input type="text" id="selK">
<input type="button" onclick="loadSearch(document.getElementById('selM').value,document.getElementById('selK').value);">

php script passed with external javascript is not working [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So in my php page I have this code :
<div id="test"></div>
<script src="test.js"></script>
And in my external javascript I have :
document.getElementById('test').innerHTML=
"<div id='abc'><a href='index.html'><?php echo 'Welcome '.$_COOKIE['user'].'<br>' ;?></a></div>";
Cookie has been set and if I put the script inside the php page, it does work but why isn't it working when it is external script ? Did I do something wrong here ? or is there a rule for doing this ?
Please educate me.
Thx in advance. =D
While using PHP and javascript together is absolutely possible, you have to remember, that PHP is executed on server-side while javascript is executed on client-side.
So you cannot have PHP in your javascript, as the page lifecycle is like this:
Get the request from client browser
Execute the PHP of the requested page and provide the html
Send the html to the client browser
Render the html in the client browser
Execute the javascript of the page
So after the page is sent, the php processing is done.
You can however embed variable via php for later use with javascript. If you echo out something like this, your java scripts can use it:
<script type="text/javascript">
var myCookie = "<?php echo $_COOKIE['user'];?>";
</script>
If you do a lot of stuff with cookies in your javascript, you may even better have a look at jQuery Cookies and fetch the cookie value directly. This will make you end up with much cleaner code.
You can't use PHP in a javascript file like that. They are two totally different languages.
You can't render php on a Javascript file, but you can do this:
on your php file:
<script>
var cookie = "<?php echo 'Welcome ' . $_COOKIE['user'] . '<br>'; ?>";
</script>
<div id="test"></div>
and in your js file:
document.getElmentById('test').innerHTML = cookie;
Regards
We cannot add php code inside the js file.
PHP is server side scripting language which will executed in the server and response will returned to the browser, while Javascript is client side scripting language which is executed in the browser.
This is a solution but just use ajax to get the required information from the server.
<div id="dom-target" style="display: none;">
<?php
$output = "42"; //Again, do some operation, get the output.
echo htmlspecialchars($output); /* You have to escape because the result
will not be valid HTML otherwise. */
?>
</div>
<script>
var div = document.getElementById("dom-target");
var myData = div.textContent;
</script>

PHP mail function gets triggered every time i load the page

I am trying to send mails using PHP's mail() function.
I have a button (Send Mail), clicking on which the mail has to be triggered. Since PHP is a server side scripting language, I used Javascript to trigger the PHP function. A very unusual event occurs. Whenever I load the page, the mail gets triggered. So, I put alerts and echos to check if the code logic is correct.
Funny thing is that the mail does not get triggered when I click the button. Where am I going wrong?
Please see my code:
<input type="button" onclick="jMail()" value="Send Mail"/>
<script>
function jMail()
{
alert("Inside Javascript Function");
alert("<?php PHPFunction(); ?>");
}
</script>
<?php
function PHPFunction(){
echo("Inside PHP Function");
mail("to#example.com", "Help Mee", "Definitely Help me", "From:from#example.com");
echo("Mail Sent");
}
?>
PHP is a server side language, while Javascript is a client side language. I think you are confusing the two, and trying to mix their use in a way that would never work.
When the page is loaded, these steps occur in sequence:
The server interprets the PHP code in your page, and renders a page that does not contain any PHP code.
The client, viewing the page, does not obviously have access to any PHP function, because it sees only the result of the elaboration. It still can use Javascript to achieve dinamic behavior of the page (i.e. changes without refreshing), and things like AJAX to make requests to the server still without re-rendering the page.
<input type="button" onclick="jMail()" value="Send Mail"/>
The event onclick is indeed triggered when you press the button, but after the page has been fully loaded. At this time, all the PHP code has been already interpreted by the server, and there is no chance to execute it again without reloading the page.
EXAMPLE: here you can see the result of the elaboration of your code (under stdout). As you can see, the client is left with a PHP-free web page.
If you're looking for a way to trigger PHP code when an event occurs after the page has been loaded, I suggest you take a look at this question.
Also, this question on programmers.stackexcange.com could help you clarify the difference between client side and server side if it isn't clear.
You cannot trigger PHP from javascript that way. Create another PHP file, and call it using AJAX javascript requests.
<form method="post">
<input type="submit" value="Send Mail" />
</form>
<?php
if(isset($_POST)){
///do sent mail here
mail("to#example.com","Help Mee","Definitely Help me","From:from#example.com");
}
?>
PHP is a server side scripting language which has already been interpreted by the server and then sent to client(i.e browser) for interpretation of any client side script( ex JavaScript).
But if want a responsive webpage to be handled by your server try to use Form and inputs tags and their attributes to send your request back to server
But if you want a Quick way Try using AJAX.
every time you do
<?php PHPFunction();
you send the mail..
maybe you could play with something like
<?php
if(array_key_exists('postMail',$_POST)){
echo ("Inside PHP Function");
//if(empty($_POST['mailContent'])){/*angry blablabla*/}
mail("to#example.com","Help Mee",$_POST['mailContent'],"From:from#example.com");
echo ("Mail Sent");
die();
}?>
<input type="button" onclick="jMail()" value="Send Mail"/>
<script>
function jMail()
{
alert("Inside Javascript Function");
var xhr=new XMLHttpRequest();
xhr.open("POST","?");
var fd=new FormData();
fd.append("postMail","true");
fd.append("mailContent","fooooobar");
xhr.send(fd);
}
</script>

Categories

Resources