I am trying to post data automatically with javascript and retrieve it in a PHP file, but the PHP file does not retrieve the data.
I created an automatic form which receives its input from another form and automatically sends it to another PHP file. But the next file pics.php does not receive the data. I only posted the relevant part of the code. First the HTML/javascript code.
<html>
<script type="text/javascript">
function submit()
{ document.getElementById("auto").click();
document.auto.submit();
}
</script>
<body onload="submit()">
<form name="auto" id="auto" action="pics.php" method="post">
<input type="hidden" name= "prodnm" value="<?php echo
$prodnm; ?>" /><br/>
<input type="hidden" name= "eigid" value="<?php echo $eigid;
?>" /><br/>
</form>
</body>
</html>
And this is part of the PHP code in file pics.php
<?php
require_once 'connect.php';
$prodnm = $_POST['prodnm'];
$eigid = $_POST['eigid'];
echo $prodnm;
echo $eigid;
?>
Help is very much appreciated. I've been at it for two days straight.
Am afraid the approach you are using is not advisable.
The form seems not to be getting the values you said are from another form(who does that anyway?).
Why not use a single form that has a submit button.
Define default values to you input fields(both visible and hidden, as you wish.)
Then use the JavaScript code to auto submit the default values on page load.
Remember, there are always better and less complicated ways to write codes for easy debugging.
Looking at the code above I cannot see why you could not send the data via an ajax request rather than trying to populate a form and then trigger the submit method somehow... Perhaps the following might be of interest in that regard.
/* replace the inline submit handler with a remote listener */
document.addEventListener('DOMContentLoaded', ()=>{
/* a very basic ajax function to send a POST request */
const ajax=function( url, params, callback ){
let xhr=new XMLHttpRequest();
xhr.onload=function(){
if( this.status==200 && this.readyState==4 )callback( this.response )
};
xhr.open( 'POST', url, true );
xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
xhr.send( params );
};
/* for convenience, declare PHP variables as Javascript variables */
<?php
printf("
let prodnm='%s';
let eigid='%s';\n",
$prodnm,
$eigid
);
?>
/* Make the POST request to pics.php */
ajax( 'pics.php', 'prodnm='+prodnm+'&eigid='+eigid, r=>{
alert("Do something with result?\n\nResponse: "+r+"\n\nReload? Modify DOM?")
});
});
As the data exists in PHP at the point you are trying to POST the form and because there is no intended human interaction then you could use curl ( or similar ) and negate the need for this page.
Related
I currently have a simple php/html page with only one form, where the user inputs a number, then the page loads itself (but this time with parameters).
Some key codelines :
<form action="index.php" method="get">
<input type="text" name="name">
<input type="submit" value="Submit">
</form>
<?php
if (!isset ($_GET["name"])) {
echo "<div> Adding some content related to the input </div>";
}
?>
Now i'm looking forward adding 3 more fields, and split my page for each form.
The user should be free to use the 4 forms separately, I don't want to have the page reload every time. I'm unsure how to design this page - should i rework my page and work with JS ?
I have basic knowledge with PHP, a little with JS. I will be able to google up most things i need but first i need a proper direction :) thanks !
you can use AJAX for this purpose...
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
AJAX is a must if you don't want the page to reload between each interaction.
If you have trouble with it and want to opt for just PHP (with page reloads) you can handle multiple forms on one page easily enough - my preferred method is to set a hidden value in the form called 'action' settings its value & reading this in again when the page loads for example:
<?php if(isset($_POST['action']))
{
$action = $_POST['action'];
switch ($action)
{
case 'hello':
echo 'hello';
break;
case 'bye':
echo 'bye';
break;
}
}
?>
<form method="post" action="Untitled-5.php">
<input type="hidden" name="action" value="hello"/>
<input type="submit" value="hello"/>
</form>
<form method="post" action="Untitled-5.php">
<input type="hidden" name="action" value="bye"/>
<input type="submit" value="bye"/>
</form>
You could then save and echo out the values for each form each time keeping them updated as the user interacts with each of the forms.
AJAX is the nicer solution however
If you do not want to reload the page every time you submit each form then you should use Ajax for calling your api. You write the separate api in PHP, and then call that api in Jquery's Ajax.
Here the page won't be reloaded. Also you can call the ajax on each of the button click.
I want to make my alert value as a variable in php. This is my code
<html>
<body>
<form action="" method="post">
<select name="kat" id="kat" >
<option></option>
<option>UNANG TAE</option>
<option>PANGALAWANG TAE</option>
</select>
<input type="text" value="" name="baliw">
</form>
<script src="js/jquery.js"></script>
<script>
$('#kat').on('change', function () {
<?php
/*
mysql_connect('localhost','root','');
mysql_select_db('perens');
mysql_query(" INSERT INTO table (sample) VALUES ('".$alert_value."') ");
*/
?>
alert(this.value);
});
</script>
</body>
</html>
There's a comment inside my PHP where I want to make the alert value as a variable but I don't know how.
JavaScript runs on the client side, after the PHP code is executed on the server side. So you cannot work with the JavaScript variables in PHP. However, you can make an Ajax call to a PHP file, posting the JavaScript values. These values can then be stored in a database by the PHP script.
Using jQuery, you can easy send Ajax requests:
http://api.jquery.com/jquery.ajax/
You can then access these values using PHP $_POST and $_GET.
http://api.jquery.com/jquery.ajax/
Take a look at this to use ajax to send javascript variables to php.
You can't do that directly.
The javascript event listener that raises the alert message is executed by the web browser (client side) and the php is executed in the server side before than page is loaded by the web browser (server side).
What you can do is to send the alert message to a PHP script using an AJAX request.
Example:
$('#kat').on('change', function() {
$.ajax({
url: "myscript.php",
type: "post",
data: {
message: this.value
}
});
alert(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Type whatever you want here:
<input type="text" id="kat" />
Now you can capture the messages from a php script like the following one:
<?php
// myscript.php
$alert_message = $_POST['message'];
// !!! Importat, sanitize the input in order to avoid a classic
// SQLInjection
// $alert_message = mySanitizationFunction($_POST['message']);
mysql_connect('localhost','root','');
mysql_select_db('perens');
mysql_query(" INSERT INTO table (sample) VALUES ('".$alert_value."') ");
?>
Remember that it is important to sanitize the input in order to avoid a SQL Injection, I recommend you to use a database abstration layer like PDO or an ORM that can facilitate the input sanitization.
I would like to disable some buttons until a button is pressed.
The first button (button1) generates a file. The rest of the buttons have something to do with that file (view, download, etc.)
I tried disabling the buttons until the first button was pressed, but as I'm using a post request the page is refreshed when I hit button1 and everything is reset.
I was thinking along the lines of grep-ing for the file and assigning that to a variable in PHP then disable/enable the buttons based off whether or not that file is there, but I'm unsure how to do the PHP/JS crossover. Any guidance would be appreciated.
You should use asynchronous page loading. Just send a request string to the server and it echoes you an answer back., without reloading page.
var jstring = JSON.stringify(request); //wrap up your specification in an JSON
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://" + window.location.hostname + "/request",
data: jstring,
success: function(response) {
//... enable buttons
},
error: function(response) {
//... file could not be loaded
}
});
In PHP
if ($_GET["type"] === 'request') {
$jsonraw = $decode ? utf8_encode(file_get_contents("php://input")) : file_get_contents("php://input");
$jsonstring = json_encode($jsonraw, true);
$array = json_decode($jsonraw, true);
//... do something with $array
}
You can also do this without an ajax. You can also do this using sessions.
Save it in a session, before any session is saved, disable the buttons view, download, etc., after the file is created, then save a session, that will determine the disabled attribute.
Rough Example:
session_start();
if(isset($_POST['create_file'])) {
$_SESSION['file_exists'] = true;
// generate file blah blah
echo 'File created: stackoverflow.jpg <br/>';
}
// now you decide when to destroy the session for this
// unset($_SESSION['file_exists']);
?>
<form method="POST">
<input type="submit" name="create_file" value="Create File" /><br/><hr/>
<input type="submit" name="view_file" value="View File" <?php echo !isset($_SESSION['file_exists']) ? 'disabled' : ''; ?> /><br/>
<input type="submit" name="download_file" value="Download File" <?php echo !isset($_SESSION['file_exists']) ? 'disabled' : ''; ?> /><br/>
</form>
What you need is called AJAX.
Make an AJAX call on click of the first button to a php file that checks for the above mentioned file. Set the PHP to return true if file is found and false if not.
Finally, in the callback of the ajax make the javascript changes if returned code is success.
I will not write the code for you, but I'll give you a link. It should be more than enough.
http://api.jquery.com/jquery.ajax/
Note that you need jQuery to execute the example.
I am new to AJAX and am in the process of converting some regular HTML forms to AJAX.
My existing implementation is as follows - form (on page1.php) posts to page2.php which does some validation on post data and redirects to an error page if something is missing. If the input is fine, it includes page3.php which processes the request and redirects back to page1.php.
php/page1.php
<form method="post" action="/php/page2.php" >
<input type="text" name="input1" placeholder="Howdy..." />
<input type="text" name="input2" placeholder="Howdy..." />
<input type="submit" value="Submit" />
</form>
php/page2.php
<?php
// perform some validation on inputs
if (empty($_POST['input1']))
{
$location ='Location: /php/error.php';
header($location);
exit;
}
// Inputs are fine
include('/php/page3.php');
?>
page3.php
<?php
// do some form processing
// redirect back to page1.php
$location = 'Location: /php/page1.php";
header($location);
exit;
?>
To convert to AJAX, I am using #SSL's solution on this SO link How to show loading gif when request goes Ajax
http://jsfiddle.net/clickthelink/Uwcuz/1/
The error from validation and success page are both displayed back on page1.php via the callback function.
php/page2.php
<?php
// perform some validation on inputs
if (empty($_POST['input1']))
{
// Echo erorr code isntead of redirect
echo "Please enter input1";
return;
//$location ='Location: /php/error.php';
//header($location);
//exit;
}
// Inputs are fine
include('/php/page3.php');
?>
page3.php
<?php
// do some form processing
// Echo success instead of redirect
echo "SUCCESS";
// redirect back to page1.php
//$location = 'Location: /php/page1.php";
//header($location);
//exit;
?>
This part is working fine.
My question (finally) is how do I handle users who have javascript disabled? I know the form will get submitted appropriately but I wont get the redirect back in case of the error or success. I would like to retain header() redirect type of functionality in this case also. Is this possible? I would appreciate the help.
You want to detect if this is an xhr request, and default to the non-ajax behavior if it is not.
I would look at $_SERVER['HTTP_X_REQUESTED_WITH']
Keep your current form setup as-is, if it is working for you without javascript.
For javascript enabled browsers you can hijack the 'submit' event on the form. Capture the event and post the form, via ajax, to scripts/pages that handle and return the data in a javascript-friendly format for final consumption.
For example, using jquery:
<form method="post" action="/php/page2.php" id="js-form" >
<input type="text" name="input1" placeholder="Howdy..." />
<input type="text" name="input2" placeholder="Howdy..." />
<input type="submit" value="Submit" />
</form>
<script>
$(document).ready(function(){
$('#js-form').on('submit',function(e){
// logic to submit ajax form and handle response
// return false to cancel native browser form submission.
return false;
});
});
</script>
Another idea is to keep the pages you already have, but send a flag with the ajax request to disable the browser redirect headers. For example, add 'src=ajax' when submitting the form via ajax. Then in the script use logic to say:
<?php
if( !empty($_REQUEST['src'] && $_REQUEST['src'] == 'ajax' ) {
// add redirect logic here.
}
?>
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.