I'm somehow stuck when I'm working on:
I want to pass a parameter to a php file and execute it when we rate something. php file is finished, but don't know how to code js part.
In detail,
user rates a passage, js gets the rating;
------ get parameters, store them in function Rate(), finished
when user submits it;
------ don't know how to check if the button is clicked, add DomListener in Rate()?
js calls the php file meanwhile passing the rating parameter to it;
------ php part finished
execute the php file without opening it in a new window.
----- don't know what to do.
HTML
<div>
<form id="rateform" action="php/rate.php" enctype="text/form-data" method="POST">
<input id="rating" type="text" />
<input id="sbm" type="button" />
</form>
</div>
JS
function Rate(){
var rate = document.getElementById("rating").value;
var sbm = document.getElementById("sbm");
// don't know how to do...
//if(sbm is clicked) {
// execute rate.php...
//}
}
thx in advance.
Here's how I'd do it in jQuery (better than dealing with an XMLHttpRequest object):
$('#sbm').click(function() {
var rating = $('#rating').val();
/* Send request to PHP script. */
$.post('/url/to/script', { rating: rating }, function(resp) {
console.log('Response:', resp);
});
});
And your php script could be something like:
<?php echo 'Hey, I got this rating ' . $_POST['rating']; ?>
I'm not a PHP guy, though!
Related
I'm trying to create a roulette system, which should work as follows: The user clicks on a submit button, which is then checked on the opening_case_handler.php file to see whether the user has sufficient funds in his account or not, and if he does it will echo javascript code which will create the animation for the roulette and will also come out with the winning prize. For security purposes I am executing the js code in php so the user has no access to it since it is executed in the server side.
The issue here is that the js and jquery code do not get executed once this line of code has been reached:
var gw = $(".gift").outerWidth(true);
in the opening_case_handler.php.
You will notice that there are two alerts before and after the previous line code I have just mentioned. If I uncomment alert("TEST1") it will get executed and an alert message will appear however the rest of the code will no be executed. Also if I uncomment only the alert("TEST2") it will not be executed and nothing will happen.
To make sure that the javascript code actually works. I previously tested it in a javascript file and sourced it in the index.php file and it worked perfectly.
index.php
This page contains the roulette with all the different images of each item. The submit button is at the bottom. This is the button that users will click to be able to spin the roulette.
<div class='rafflebox'>
<div class='pointer'></div>
<div class='boxwrapper'>
<ul class='giftwrapper'>
<div class="gift item bg-size2 box-bg3">
<img class="item-product2" src="graphics/mouse.png" draggable="false">
</div>
<div class="gift item bg-size2 box-bg2">
<img class="item-product2" src="graphics/mouse.png" draggable="false">
</div>
<div class="gift item bg-size2 box-bg3">
<img class="item-product2" src="graphics/mouse.png" draggable="false">
</div>
<div class="gift item bg-size2 box-bg4">
<img class="item-product2" src="graphics/mouse.png" draggable="false">
</div>
</ul>
</div>
</div>
<form method="post">
<button type="submit" name="opening_case" class="btn open-box-btn btn-openbox-font button"><img id="lock" src="graphics/iconos/Candado Cerrado Black.png">ABRIR CAJA</button>
</form>
</div>
opening_case_handler.php
<?php
session_start ();
if(isset($_POST['opening_case']))
{
opening_case ();
}
function opening_case ()
{
if ($_SESSION['balance'] >= $_SESSION['box price'])
{
echo '
<script>
//alert("TEST1");
var giftamount = 10;
var gw = $(".gift").outerWidth(true);
//alert("TEST2");
var giftcenter = gw/2;
var cycle = 7;
var containercenter = $(".boxwrapper").outerWidth(true)/2;
for(var i = 0; i <=5; i++)
{
var giftduplicate = $(".giftwrapper").children().clone(true,true);
$(".giftwrapper").append(giftduplicate);
}
$(".button").click(function()
{
alert("You DO have sufficient funds");
var btn = $(this);
btn.hide();
var randomgift = Math.floor(Math.random() * 4) + 1;
var dev = Math.random()*(giftcenter+1);
var distance = giftamount * cycle * gw + (randomgift*gw) - containercenter -24 +dev;
console.log(distance);
$( ".giftwrapper" ).css({left: "0"});
$(".giftwrapper").animate({left: "-="+distance},10000,function()
{
alert("You Won Gift" + randomgift);
btn.show();
});
});
</script>';
} else {
//to be done
}
}
?>
Please feel free to express your ideas on how this type of system should be better built. I am open to all suggestions, I am fairly new to this.
Thank you!!
Try using Heredoc string quoting example for printing your JavaScript:
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
Heredoc text behaves just like a double-quoted string, without the
double quotes. This means that quotes in a heredoc do not need to be
escaped, but the escape codes listed above can still be used.
Variables are expanded, but the same care must be taken when
expressing complex variables inside a heredoc as with strings.
If it is just a php code file. You can try some below.
<?php
echo "some stuff here"
if ($condition){ ?>
<script>
alert("condition true");
</script>
<?php } else { ?>
<script>
alert("condition false");
</script>
<?php }?>
When a form gets submitted it redirects you to the PHP page (ie when you click submit in index.php you will get redirected to opening_case_handler.php ) and then the PHP page will send you back to the index page with the new info. Thus, your javascript code gets printed in the opening_case_handler.php which is why your javascript did not get executed. Also, your javascript code will always be visible unless if you do something really creative so if you are trying to handle any sensitive information do it in PHP or any backend framework you are using.
There are ways to fix this issue but I would recommend a different approach to solve this issue. You can use an AJAX request which basically works in the following manner:
You send a request to your PHP server with the data you want to send.
Your PHP server will process the request and send it back to you
Your Javascript code will process the result and show the animations
or whatever you want to do.
This way your algorithm is not shown and your client ( the javascript side ) only handles information entered by the user and the results came from the server.
In your case, we can do that using the following changes
Index.php (which can be changed to index.html now)
<button type="submit" id="opening_case" name="opening_case" class="btn open-box-btn btn-openbox-font button"><img id="lock" src="graphics/iconos/Candado Cerrado Black.png">ABRIR CAJA</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#opening_case").on("click", ()=>{
// $.get( "opening_case_handler.php?opening_case=true", function( data ) {
// console.log(data.funds)
// });
$.ajax({
url: "opening_case_handler.php?opening_case=true",
success: (data)=>{
if(data.funds) {
alert("You DO have sufficient funds")
} else {
("You don't have sufficient funds")
}
},
dataType: "JSON"
});
})
</script>
opening_case_handler.php
<?php
if(isset($_GET['opening_case'])) {
$result = [
"funds" => true,
];
$ResultsInJSON= json_encode($result);
echo $ResultsInJSON;
}
?>
The index.php will send the request when the button is clicked using AJAX which you can read about it here https://api.jquery.com/jquery.get/ then your PHP will receive the request and response with a JSON code which can be processed using the data.whatever as shown in the example above.
Note: I am not a PHP expert but I believe this will be a better method to use in this case.
Note2: You don't need Jquery for Ajax but it's easier! Here is how you do it without Jquery https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp
I have almost completed my chat application using php & ajax functions .
Now question is , how to show "Typing.." (text) when the opposite user triggers the keyup() function from text-area.
My working structure :-
chat.php
<?php
// unique.html is created for each individual chat , just name is stored in database.
//For eg :- Two user_id's(5,4) combined together forming 54.html ..& so on
echo '<div id="mychat_box">
//old content of chat/messages are loaded from an unique.html file here ..
//working fine
</div>
<textarea id="usermsg" ><textarea>
<input type="submit" id="submitbutton">';
?>
Ajax functions
$('#submitbutton').click(function(){
$('#usermsg').val();
//Content is posted to post.php via ajax
//working fine
});
function Loadlog() {
// This function loads/refresh the contents
//(renders content from unique.html) inside the div mychat_box
via setInterval() , 10 seconds.
}
post.php
<?php
//content is accepted from the ajax call & posted to the unique.html file .
//also some information is collected & stored to database.
//Working fine
?>
Above process is working fine , last need is to to add "Typing.." text dynamically(ajax ?) when the opposite user triggers the keyup() function as asked earlier.
Can anyone explain how can it be achieved ? Or explain me the logic behind it with some pseudo-code/article/tutorial ?
Will post code in more detail if necessary.
I understand that SO advocates that we do our research before asking, but I'm not sure how to put it another way, so I thought I'd ask directly -
I'm actually trying to do something simple - upload a file, but when I select "choose" in the file browser, it just redirects to the PHP page, which shows the corresponding error message (since nothing has been uploaded).
Would really appreciate if you can explain the process flow of uploading a file. Here's my code:
HTML
Simple form
<form action = "./php/upload_avatar.php" method = "POST" enctype = "multipart/form-data">
<div class = "change-avatar-text">
改变头像
</div>
<!-- hidden button trick -->
<input type = "file" name = "file" id = "change-avatar-input"/>
<button type = "submit" class = "change-avatar" onclick = "fake_photo('change-avatar-input')"></button>
</form>
http://i.stack.imgur.com/6d2U4.png
The onclick is just a way to use a photo as the file button instead of a traditional button. I don't think it's relevant, so I omitted it here.
PHP
The upload file code
if (file_exists("../avatars/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "../upload/" . $_FILES["file"]["name"]);
}
Two things happened: when I tried clicking the upload button on the HTML page, it returned "already exists", but there's nothing in the ../avatars/ folder.
http://i.stack.imgur.com/DG8Vm.png
I then tried commenting out everything except for move_uploaded_file, and nothing happened.
Would appreciate your advice on this, thanks!
UPDATE
JS
Here's the fake photo function:
function fake_photo(element_id) {
document.getElementById(element_id).click();
}
You do not prevent the default action of the form from happening within your onclick method. But that will not be the only problem, since you are using the submit button as the trigger to start the file chose process you will need to resubmit the form after the image has been picked.
HTML
<form id="myform" action="./php/upload_avatar.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="change-avatar-input" onchange="onFileChanged()"/>
<button type="submit" id="submitBtn" class="change-avatar" onclick="fake_photo('change-avatar-input',event)"></button>
</form>
Javascript
var hasChosenFile = false;
function fake_photo(element_id,event){
//If hasChosenFile is false then we want
//to prevent the default action of the form
if(!hasChosenFile){
event.preventDefault();
document.getElementById(element_id).click();
}
//Else let the form submit.
}
function onFileChanged(){
hasChosenFile = true;
document.getElementById('myform').submit()
}
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>
I currently have a form that looks like this (using Bootstrap):
I've traditionally processed the form via post to another php file like so
<form action="complete.php" method="post" class="form-inline" role="form">
However, it kind of ruins the user experience when they're taken to a different page, and I've seen something before, where after submitting a form, the text just changed if it was valid. So, the text and form of the above image might just be replaced with "Thank you, your email has been accepted" if they offer a valid email.
So this question is two-part:
First, how do I do this on the backend? I'm using php for simplicity since it was so easy to install.
Second, how do I do this on the front end? Is there a common reference term for this kind of action in JS?
Answering either part of this (both if you can!) would be wonderful. If you have reference documents for me that aren't too complicated (I'm new to this), I'd be more than happy to read them too.
Thank you!
I'm going to extend on what Sam Sullivan said about the Ajax method.
Ajax basically runs any script in the background, making it virtually unnoticeable to the user. Once the script runs you can return a boolean or string to check if the result is true or false.
JS:
function validateForm(){
$.ajax({
type: 'POST',
url: '/path/to/processForm.php',
data: $('#yourForm').serialize(),
success: function(output){
if(output){ // You can do whatever JS action you want in here
alert(output);
}else{
return true; // this will redirect you to the action defined in your form tag, since no output was found.
}
}
});
return false;
}
Then in your processForm.php script, you validate the data through $_POST. Whatever you echo out in this script, will be your output.
For more, http://api.jquery.com/jquery.ajax/
Either include the PHP and form logic on the same page:
<?php
if(isset($_POST['submit'])) {
// Submit logic
echo 'Success';
}
?>
<form action="" method="POST">
<!-- etc -->
<input type="submit" name="submit" value="Submit" />
</form>
Or you can submit it with AJAX:
<form action="" method="POST" onsubmit="submitForm(this); return false;">
<!-- etc -->
<input type="submit" name="submit" value="Submit" />
</form>
<script type="text/javascript">
function submitForm(form)
{
// This can use AJAX to submit the values to a PHP script
}
</script>
If you have jQuery, you don't need to use an inline event handler (which is better):
<script type="text/javascript">
$('form').submit(function(event) {
event.preventDefault();
$form = $(event.target);
// AJAX here
});
</script>
This should be enough to get started..let me know if you have specific questions.
Change the form to
<form action="[whatever the page name is]" method="post" class="form-inline" role="form">
First, how do I do this on the backend? I'm using php for simplicity since it was so easy to install.
At the top of the page, add
<?php
if(isset($_POST)){
// Check for the $_POST variables and process
// $content = "<div> ... </div>" // Then echo out the content in place of the original for
}
?>
You can just put form action="filename-of-the-form-processor" or leave it blank for same page. If you can't avoid to put php module on the same page where your form reside make a view.php file then just include it.
index.php <- where form process happends
index.view.php <- where form tags reside so you will have a cleaner line of codes.
Note: this is not the best way to do it.