When the user presses the submit button from different forms, action pages execute their jobs. Before the end of those action pages I have put this lines:
$_SESSION['status']="inserted";
header("Location: storage.php");
or
$_SESSION['status']="removed";
header("Location: storage.php");
or
$_SESSION['status']="updated";
header("Location: storage.php");
The purpose of those lines is to save "globally" the success of the operation and then take the user to another page (storage.php).
In the storage.php page I want to show a specific message (depending on the operation) to inform the user that everything went fine (<body onload = "statusMessage()">).
Since $_SESSION['status'] is a PHP variable and the message is displayed using Javascript I googled a way to pass variables form PHP to Javascript.
The following code is what I have done:
In storage.php I have put these lines:
<div id="data-status" style="display: none;">
<?php
echo $_SESSION['status']; // put as the div content
$_SESSION['status']=""; // clear the variable
?>
</div>
with the purpose to save into an "invisible" <div> the value of my PHP variable.
Then I use DOM to access to that value:
<script type="text/javascript" >
function statusMessage() {
var status = document.getElementById("data-status").textContent;
switch(status){
case "inserted":
alert("Data inserted into database");
break;
case "removed":
alert("Data removed from database");
break;
case "updated":
alert("Data updated");
break;
default:
alert('Status code not known!');
break;
}
}
</script>
The problem is that always the default case is executed showing "Status code not known!".
Trying to debug I wrote this code:
var status = document.getElementById("data-status").textContent;
var string = "inserted";
console.log(string);
console.log(typeof(string));
console.log(string.length);
console.log("--------------------");
console.log(status);
console.log(typeof(status));
console.log(status.length);
and that's the output:
console output
It seems that for some strange reason, special non printable characters are added to the status string. I don't know why and how to remove them.
Sorry for my long message, I hope someone can help me.
Thanks in advance!
Related
I am trying to finish one page of my website the last couple of hours while achieving the following.
While clicking on a button, the following should happen
Download link appears (done - works)
The mySQL table should be opened and a counter should be incremented
As far as I got the points. Javascript cannot handle that and thus we can use AJAX or jQuery. I was already checking out different posts and websites such as:
how to execute php code within javascript
https://www.w3schools.com/js/js_ajax_database.asp
and much more. However, I guess I do have problems with the AJAX syntax and I actually don't know if the requested php files is loaded/opened or not. Especially the second link given above is almost similar to what I am searching for. However, it does not work. To check if the php file is called, I set an alert which works if I do call the file explicitly in the browser. Maybe this does not work with AJAX as I expect it. Here the code to get more familiar with the inconstency I am doing.
The page code:
<?php
echo '<div><button onclick="incrementAndDownload('testPath', 'fileName'); ">Click me</button></div>';
?>
<script>
function incrementAndDownload (link, fileName)
{
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
// Print something if necessary
}
});
//- Open the link
// window.open(arguments[0], "_blank");
//- Increment download inside mysql
//var xhttp;
//xhttp = new XMLHttpRequest();
//xhttp.open("GET", "openfoam/increment.php?foo=nana", true);
//xhttp.send();
}
</script>
The increment.php looks as follows:
<?php
echo '<script type="text/javascript" language="Javascript">
alert("Test message if the script is called...");
</script>';
// Code for accessing the mysql database and manipulate the data
//$page_id = mysql_real_escape_string(html_entities($_POST['file']));
?>
Now when I click the button, the javascript is executed (e.g., if I uncomment the window.open) this works as expected. However, as already said, the second part is to open the database via php and increment a number (counter). For any reason, I am not able to figure out where the problem is located. I am even not sure if AJAX opens the increment.php file (the alert messages never appears so I guess it is never called). Any suggestion is appreciated and I hope that this question does not just contain a fundamental small error. Thank in advance, Tobi
It's not the way the AJAX works. If you call alert() on a destination page it won't show in your browser. Your case is very basic so I will keep my solution on a basic level.
In increment.php just echo something, it can be just OK string. So when you go to increment.php page you will see only OK, nothing more, nothing less.
Then go back to your javascript and check what is your response.
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
if (data == 'OK') {
console.log('It works, sir!');
}
}
});
If you don't see a message in a console after these modifications something doesn't work. However, I think your page is executed properly, but you just don't get feedback, because you don't handle the response (data param in your case).
Check it out and don't forget to give me a feedback!🤓
I am building a login form in a HTML page login.html. Now after submitting the form the data is send to a php server side script named login.php. My problem is that if for some error say if the username is already present in the database table I want the user to stay in the same page with a red colored warning. Or if I want to add the popular two passwords did not match error message. How can I achieve this. As the data is stored in a mysql database I cannot access it using any client side script. But in my approach the php script moves the user to another page. And there is no way to dynamically make some error messages visible. I tried to make seperate html pages for this purpose, but I think it is not a very good solution. Can anyone provide me a sample code for this purpose? Thanks in advance.
You can either change messages with a switch statement in login.php (login.php would display the error message), or you can send the user back to login.html with an error code appended to url that can be retrieved (that is what I would do).
Using Switch in login.php
You would enter your predefined error code into an error function, there are multiple ways to do this.
function display_error_message($e) {
switch ($e) {
case "error_1":
echo "Error message 1";
break;
case "error_2":
echo "Error message 2";
break;
//Will execute the default if the error code does not match
default:
echo "Error message 2";
}
}
Calling:
display_error_message("error_1");
Appending Error to URL of login.html (recommended)
Here we again use a function. It will redirect user back to login.html with the error, this can be used on a successful login as well with append /?status=success.
Please note that you cannot use the header() function if any content is being displayed on login.php before the function is executed.
function error_redirect($e) {
header("Location: www.example.com/login.html?error=$e");
exit();
}
Calling:
error_redirect("nouser");
This question already has answers here:
PHP form - on submit stay on same page
(11 answers)
Closed 5 years ago.
I have a form on a website (www.mywebsite.com). I have a PHP script that sends me an e-mail with information when somebody submits a form on my website. But with action="submitform.php" in the form, it updates the site to the URL www.mywebsite.com/submitform.php. I would like it to stay on the main site (index).
The solution for this: I added header("Location: http://mywebsite.com"); die(); to my PHP code. In this way, users will be redirected to the main site when they have submitted code.
However, this pose a new problem.
Whenever someone submit the form, I would like to display a message such as "Mail has been sent". To make this work, I tried to have a small JavaScript code, basically
document.getElementById("message").innerHTML = "Mail has been sent."
... and <div id="message"></div> to my HTML code. Which works...... However, due to my PHP script redirecting me to my website (with header) when someone is submitting the form, the message will only be displayed for like half a second or something.
Anyone know any workarounds for this? Thanks in advance. I can provide more detail if needed, but my problem should be clear from this. Hope anybody is able to spot my mistake...
I use javascript and ajax for most of my form post. Works wonderful.
Ajax can grab the form information in a form object or pass it as an array. URL is your php proc page, there it will come back with whatever you "print/echo" in a data object that is passed into the success function.
Use this in your HTML,
<input type="button" onclick="submitForm();" value="Submit">
Javascript,
function submitForm(){
//Validate INPUT first. Then grab the form.
form = new FormData($('#frmIdHere')[0]);
$.ajax ({
type: 'POST',
dataType: 'text',
url: url,
data: form,
success:data => {
//Success message here.
//clear form here.
},
error: () => {
// error message here.
}
});
}
php process file use,
$inputFromForm = (isset($_REQUEST["NameOfInputFromForm"])) ? strip_tags($_REQUEST["NameOfInputFromForm"]) : "-";
Without using Ajax (which means you can send the form without refreshing the page), you have two options. Either send the form to a different file, process it, and redirect back - but with a GET parameter to indicate success or failure. Alternatively, just post to the same page (so the handling of the form happens in the same page - I recommend the first alternative).
If you want to use the post-redirect-get pattern, you would use
header("Location: /?status=success");
exit;
when the form was successfully handled in your submitform.php file.
Then you just check what the message in $_GET['status'] was, and display the message accordingly in your index.php file.
if (isset($_GET['status']) && $_GET['status'] == 'success') {
echo "Your message was successfully sent!";
}
This logic can be developed further to have different parameters, to post messages for success and failure, if that's needed for the application.
assumption: you want the user to stay on the page with the form.
in that case you probably don't return false / stop event propagation in your calling code.
let's say, you call your ajax like this:
<form onsubmit="submitform(this);" ...>[form]</form>
onsubmit does the following, it executes anything that is in it's attribute value (submitform(this)) and if it returns some non-false value, it will actually do the action of the form, as if the onsubmit wouldn't have existed. I assume this is exactly what's happening in your case.
To avoid this:
<form onsubmit="submitform(this); return false">[form]</form>
the return false will stop the form from being submitted, after it was already submitted by ajax. this also has the benefit of still working, if the user has javascript disabled.
if my assumption is false however ...
if you want to refresh the page, don't even use ajax and just add a parameter to the url that triggers the message to show. or add the message to the session in php and clear it out of there after displaying.
To doing this, You can use a SESSION var to store message send type (success or failed) and test it everytime on main page, if exist, display message and unset $_SESSION var !
Like this :
MAIN
if(isset($_SESSION['message'])){
if($_SESSION['message'] == 'success'){
echo "Yeah !";
}else{
echo "Problem";
}
unset($_SESSION['message']);
}
MESSAGE
if(mail()){
$_SESSION['message']='success';
}else{
$_SESSION['message']='error';
}
You can set interval and then redirect them to desired page.
<script>
setInterval(function(){ window.location.href="http://mywebsite.com" }, 5000);
</script>
I just need to ask small favor, can you please take a look at this code and what's the problem because it only loads the ph.php file even the user is from US that suppose to be us.php :
<script language='Javascript'>
var country = geoplugin_countryCode();
switch (country)
{
case (country = "UK"):
<?php include( "../../uk.php"); ?>
break;
case (country = "US"):
<?php include( "../../us.php"); ?>
break;
case (country = "PH"):
<?php include( "../../ph.php"); ?>
break;
}
</script>
1 Javascript - Load respective file on respective countries
This is actually an include file called offer.php inside index.php that dynamically call other files depends on what country is the user. For example if somone is from UK then offer-uk.php must load and replace the variables in index.php
2) PHP -
I need to load this page normally with this URL format : www.mydomain.com/index.php?noclid=abc123
It need to dynamically pass through the noclid variable using $_REQUEST or whatever just to make it work as www.mydomain.com/index.php?noclid=abc123. Inside the index.php file, I do $_GET['clid'] = '[[clid]]'; but the thing is i want to have noclid=abc123 not clid=abc123.
As many have pointed out, you've probably mixed up how server and client side resources are fetched. You need to understand that, all the code in the php side of things is compiled and evaluated into valid html when you submit a request for that resource.
Once the page renders in your browser, javascript comes into action. If you still want to include specific php files as per country code, you would have to make appropriate requests to the server.
So in your case since you are fetching the country code in javascript, you might want to make a request to another php script (let's call it foo.php) using a POST or GET request. You can then include the appropriate files for separate countries in a very similar switch statement. Only this switch statement would lie in foo.php. So foo.php could look something like this:
<?php
$country= $_POST['countryid']; //Assuming you are making a post request and passing 'countryid'
switch ($country) {
case "UK":
include( "../../uk.php");
break;
case "US":
include( "../../us.php");
break;
case "PH":
include( "../../ph.php");
break;
default:
//if you want to handle this case..
}
?>
The ajax request could simply be:
var country = geoplugin_countryCode();
...
$.ajax({
type: "POST",
url: "foo.php",
data: { countryid: country}
})
.done(function( msg ) {
//Ajax request completed
});
If you are unclear on how to make a post or get request and pass data along with it, I suggest reading up some documentation on ajax. Anyway, this is just one of the many ways you can get around your problem. Hope it gets you started in the right direction.
As Dagon said. You try to mix client side and server side code.
server side
if offer.php is included in your index php it will be parsed and all includes will executed. I guess they all set the same variables so you only see the effect of the last one. Change the order of your includes and you will see it's always the last one.
client side
If you have a look at your generated html and javascript you will probably see something like this:
<script language='Javascript'>
var country = geoplugin_countryCode();
switch (country)
{
case (country = "UK"):
break;
}
...
This is because your php is done and has generated the html output. You can build javascript code on the server side and send it to the browser to be executed there, but don't expect the browser to execute any php commands.
solution
Depends on your problem.
But if you need the country information on the server side you have to pass it to the php script. e.g. call your index.php with index.php?country=US
I am trying to add a CAPTCHA option to a specific page on a website. The validation code for the page is written in Javascript, and the PHP CAPTCHA documentation (http://www.phpcaptcha.org/documentation/quickstart-guide/) is given strictly in PHP. I've managed to add the CAPTCHA box to the page and everything else up until where the code verifies the user's CAPTCHA entry. I am having trouble merging the two because:
a) they are written in different languages
b) my knowledge in PHP/Javascript is very basic
Here is a snippet of the page's original validation code:
function validate(formData, jqForm, options){
// # Valid?
valid = false;
// # Validate Contact Form
var errs = new Array();
// # Contact Name
if($('#ContactName').val() == ''){
errs.push(['#ContactName', 'Enter your name.']);
} else if(label = $('#ContactNameLabel label.error-message')){
label.fadeOut();
}
I want to repeat the same process except with the user's CAPTCHA entry. The following code is given in the PHP CAPTCHA documentation:
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
and
if ($securimage->check($_POST['captcha_code']) == false) {
// the code was incorrect
// you should handle the error so that the form processor doesn't continue
// or you can use the following code if there is no validation or you do not know how
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}
The code can be found, along with instructions, in the link given above. My question is: how can I implement the given PHP code inside the Javascript function that I have? To my understanding, it is possible to embed PHP inside Javascript as long as the forum is written using PHP (and I can confirm that the website I'm working on is built using CakePHP) - I am just lost with the syntax/how to go about executing this (if it is possible).
If anyone could offer me a helping hand that would be greatly appreciated! Thank you in advance.
You can write PHP within JavaScript if the JavaScript is in the View (as opposed to being in a .js file)
Example:
<?php
$message = "Hello World";
?>
<script>
alert("<?php echo $message; ?>");
</script>
You can't do that as PHP is a server-side language and Javascript is a client-side one. By the time your browser sees the page, all the PHP processing has finished on the server and all that's left is client-side rendering of the page. You will need to validate the CAPTCHA on the server-side.