Disable buttons unless button is pressed - javascript

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.

Related

How to retrieve automatically uploaded form data in PHP

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.

How would you design this webpage with multiple forms?

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.

How to make a post request processed in the background

I've currently got the following button:
<input class="submitbutton" name="start" type="button" value="start"
onClick="window.location='vservermanage.php?_v=<?=$this->vid;?>'">
This button starts the current state of the 'service' - Either offline/online etc.
The page then loads & using if statements I can read whether it's offline or online. (PHP)
How do I make this post in the background instead - and once the result is returned process a javascript code, The following code also occurs when the page refreshes.
<?php if($this->msgsessuccess) { ?>
<div id="successbox"><?=$_lang[$this->msgsessuccess];?></div>
<?php } ?>
<?php if($this->msgseserror) { ?>
<div id="errorbox"><?=$_lang[$this->msgseserror];?></div>
<?php } ?>
I also have the following code which I want to do the same with HOWEVER I want to make this one automatic instead (every 2 seconds)
<input class="submitbutton" name="refresh" type="button" value="refresh"
onClick=" window.location='vservermanage.php?_v=<?=$this->vid;?>'">
The above code refreshes the state of the service.
There are a few elements to this but all can be achieved quite easily with JQuery. I assume you are including JQuery in your HTML head.
To illustrate you can tap into the click that happens on your submit button and then trigger an AJAX post, then do something with the results. Some example code:
$('.submitbutton').on('click', function(e) {
// Stop the browser from doing anything else
e.preventDefault();
// Do an AJAX post
$.ajax({
type: "POST",
url: "vservermanage.php",
data: {
_id: id_value // various ways to store the ID, you can choose
},
success: function(data) {
// POST was successful - do something with the response
alert('Server sent back: ' + data);
},
error: function(data) {
// Server error, e.g. 404, 500, error
alert(data.responseText);
}
});
});
The id_value parameter needs setting or obtaining, presumably from the original rendered page. You could for example, store the ID in a hidden form field e.g.
<input type="hidden" name="id_value" id="id_value" value="<?php echo $id;?>">
... and then include it like
_id: $("#id_value").val()
Regarding the second query, you could run the above POST within a standard JavaScript timer, e.g.
setInterval(function(){
$.ajax({
...
});
}, 2000);
I hope I've understood your question and that this helps put you on the right track.
You can use $.ajax(), or $.post(), even $.get(), but I wouldn't recommend allowing GET requests to modify data. Something along the lines:
function startProcess() {
$.ajax({
url: "vservermanage.php?_v=<?=$this->vid;?>",
type: "POST",
success: function(data) {
// proces the data if interested
// or just do what you need
}
});
}
, and you set this function as the click handler for your button.

Pass variables from HTML form -> ajax load()

What I am trying to do
I have a HTML form which looks like this:
[input text field]
[submit button].
I want the output results to display in only a small part of the page (don't want to refresh the entire page after the button is clicked).
What I have done so far
I am using jquery load() as follows:
<script type="text/javascript">
function searchresults(id) {
$('#myStyle').load('displaysearchresults.php?id=' + id ; ?>);
}
</script>
Results will appear in a div which is exactly what I want:
<div id='myStyle'></div>
The problem
The script above works just fine (I used a variation of it elsewhere). But I have 2 problems:
1-How to call the load() script from the form. I tried this but it doesn't work:
<form id="form" name="form" method="post" action="searchresults('1')">
2-If I am not able to call the load() script from the form, how do I pass what is into the input text field to the load() script so in the end it can be proceessed by the displaysearchresults.php file???
Thanks
Currently its not working since you have a typo:
function searchresult(id) {
/^ no s
$('#myStyle').load('displaysearchresults.php?id=' + id ; ?>);
}
Here:
action="searchresults('1')"> // this should be on the onsubmit
^
Since you're intention is to submit the form without reloading, you could do something like:
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: 'displaysearchresults.php',
data: {id: 1},
type: 'POST',
success: function(response) {
$('#myStyle').html(response); // assuming the markup html is already done in PHP
}
});
});
Of course in the PHP side, just call it like a normal POST variable:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = $_POST['id'];
// other stuff you have to do
// echo markup stuff
exit;
}
Ok I have been able to do what I wanted to do, i.e., displaying search results in part of the page without reloading.
Actually it is not necessary to use the ajax load() function. You can do it with the script below:
<form id="form" method="POST">
<input type="text" id="textbox" name="textbox" />
<input type="submit" name="test" />
</form>
<div id="myStyle"></div>
<p>
<script src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#form').on('submit', function(e){
e.preventDefault(); // prevent the form from reloading
$.ajax({
url: 'displaysearchresults.php',
type: 'POST',
dataType: 'html',
data: {text:$('#textbox').val()},
success: function(response) {
$('#myStyle').html(response);
}
});
});
});
</script>
So what is this doing:
It will "read" what the user entered in the textbox,
When the user click the "submit" button, it will put that into a POST variable and send it to "displaysearchresults.php" without reloading the page,
The search results will be displayed between the "mystyle" div.
Pretty nice.
Note for beginers: do not forget to copy the jquery file to your root folder otherwise ajax just won't work.

Can't use Ajax to Send/Retrieve variables To/From Server

Quite confused with the answers in the StackOverFlow and the whole Internet! I have some problems which seem easy but can't solve them since some days!
In my scenario (Online Booking System), I want to take the entered values in the FORM (Starting Time and Duration of the reservation) and send it to the SERVER (PHP); In the PHP function I will check if they are valid (some SQL queries and PHP functions); Then I'll retrieve the result back to the JQuery (as json encoded array);
The current snippets are as follow:
My HTML form:
<FORM ACTION="add.php" METHOD="post" ID="submitform">
<INPUT type="text" cols="50" id="starting_time" NAME="starting_time" PLACEHOLDER="Starting Time" /><br />
<INPUT type="text" id="duration" NAME="duration" PLACEHOLDER="Duration"/><br />
<P>Suggestions: <span id="txtHint"></SPAN></P>
<INPUT type="button" value='Add Reservation' id="button" />
<DIV ID="ajaxfield"></DIV>
</FORM>
My JQuery and AJAX codes:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
$(function(){
$('#button').click(function(){
$('#container').append('<img src= "ajax-loader.gif" alt="Currently loading" id="loading" />');
var str = $('#submitform').serializeArray();
$.ajax({
cache: false,
url: 'availability.php',
type: 'POST',
dataType:'JSON',
data: $str,
success: function(response){
resultObj = eval (response);
alert( resultObj );
}
});
});
});
</script>
My PHP:
<?php
header('Content-Type: application/json');
$starting_time = $_POST['starting_time'];
$duration = $_POST['duration'];
availability($starting_time, $duration);
function availability($starting_time, $duration) {
THE FUNCTION STUFF
}
echo json_encode( $arr );
}
?>
Now, the problem is first of all this is not working and the script is being stuck on the loader.gif!
And second how can I manipulate the json array from PHP to do some stuff, like enabling the submit button and/or suggesting a duration which works for the user.
PS: And of course, IN the final scenario I want to check these things instantly and before user presses the submission button.
Thanks!
EDIT
Some part of my problem is solved by the notes from answers, this is the modified code (till now):
var str = $('#submitform').serialize();
$.ajax({
cache: false,
url: 'availability.php',
type: 'POST',
dataType:'JSON',
data: str,
success: function(data){
alert(JSON.stringify(data, null, "\t"))
}
});
Now, obviously I could alert the JSON returned from the PHP function; I'll just need to modify it to manipulate for my purposes.
First of all... I'll try to teach you a bit of fishing instead of just giving you a fish...
You say that your code is just stuck on the loader.gif... you've been several days stuck so I supose you had time enough to detect where your code stops, to detect if there is any error on your javascript code or if your client code execution reachs your server code.
The only info you give us saying that it's stuck on the loader is that this line of code:
$('#container').append('<img src= "ajax-loader.gif" alt="Currently loading" id="loading" />');
Has been executed.
Well... and now?
Ok, you can check things like the following:
Check if str contains what you expect it to contains.
Check if execution reachs availability.php
Check what $str contains (is the data you're trying to pass to your server)
Surely during those checkings you'll see some light through your doubts and you'll be able to post here a more detailed question.

Categories

Resources