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.
Related
as title you see, I meet some problem with my website,
I use ajax to read my API, and after ajax success, I need to reload page to display some data,
Unfortunately, the page sometime will blink and then reload, but sometime will not.
And I use setTimeout to achieve that, because I'm writing shopping cart page,
It allow user edit their shopping carts' goods.
My idea is: after user stop click plus or minus button or stop typing quantity about 1 second,
ajax will execute to read my API, after ajax success, reload page.
So, is there have any ways to prevent page blink?
Or maybe I can made a loading gif to display on the page?
My code will be like:
var timeout = null;
$('.num').on('keyup', function() {
var newNum = $(this).val();
var pid = $(this).attr("name");
clearTimeout(timeout);
timeout = setTimeout(function() {
if(newNum <= 0){
alert("At least 1 product!");
$(this).val("1");
$.ajax({
type: "post",
url: myAPI,
async: false,
data: {
pid: pid,
newNum: 1
},
dataType: "json",
success:function(data){
window.location.reload(true);
},
});
}else {
$.ajax({
type: "post",
url: myAPI,
async: false,
data: {
pid: pid,
newNum: newNum
},
dataType:"json",
success:function(data){
window.location.reload(true);
},
});
}
}, 1000)
});
You can add a loader gif as you want then remove when document loaded.
<div class="loader-fix" style="position:fixed;height:100vh;width:100vw;background:#ffffff;">
<img src="your.gif" />
</div>
<script>
$(window).on('load', function (e) {
$('.loader-fix').fadeOut('slow', function () {
$(this).remove();
});
});
</script>
What is the point in using ajax when you want to reload the page to show updated data...?
success:function(data){
window.location.reload(true);
}
What is the use of above piece of code..?
For your purpose a simple form submission thing was enough, but you have used ajax getting data but not using it anywhere.
If you want to reload the page, then better go with solution by Şahin Ersever.
If you want a dynamic site, where data is fetched from backend in background and updated on frontend without refreshing the page, do something like this.
<html>
<body>
<h1> Dynamic load using AJAX </h1>
<div class="dynamic_div">
<div class="some_class">
<!-- here some more elements may/may not contain dynamic data or some server side based-->
<!-- Like this -->
<h1> Name:- <?php echo $name;?> </h1>
<p> <?php echo $some_other_variable;?> </p>
<p> <?php echo $some_other_variable;?> </p>
....
</div>
</div>
<button onclick="letsload()">Load</button>
<script>
function letsload(){
$.post("someurl",{ data1: "value1", data2 : "value2"},
function(data, status){
if(status == "success"){
$('.dynamic_div').html(data);//Loading updated data
}
});
}
</script>
</body>
</html>
On data variable, you can echo out desired html/json or a success/error code, and handle the data/code in ajax function accordingly.
Edit :-
Looking at your comment But I check my website, if ajax success, I use console.log to print my data, it's not working, but if reload page, it can work.
I have a quick and easy solution for this.
Let's take above example, which I have given.
Suppose if I want updated data to be displayed in dynamic_div what I will do, is I keep the element to be shown inside that div in separate file.
eg:- updated.php
<div class="some_class">
<!-- here some more elements may/may not contain dynamic data or some server side based-->
<!-- Like this -->
<h1> Name:- <?php echo $name;?> </h1>
<p> <?php echo $some_other_variable;?> </p>
<p> <?php echo $some_other_variable;?> </p>
....
</div>
Now What I do is on success of my ajax, I will load this div in to my .dynamic_div like this.
success:function(data){
$('.dynamic_div').load("updated.php");//Load the inside elements into div
}
Now you will get updated data, as you have already updated it somewhere in backend, so load() will load a page inside a division, without refreshing the whole page.
Comment down for any queries.
AJAX Read data from a web server - after a web page has loaded
Update a web page without reloading the page
Send data to a web server in the background
What is Ajax
If you want to reload page then don't use ajax call,
but if you want to load data using ajax then update your html using JavaScript in ajax success message.
I am trying to create the following scenario:
A form in my index file collects input from a user, which is used to do some computation. The results of this computation should be echoed to him in a nice interface on the same page without reloading.
Currently, the results.php page is receiving the inputs correctly. Now, I just want to show it back inside the results div on the main page without reloading the results.php. .load is the wrong command for that. I need something like ".show"... Any ideas?
html:
<form action="results.php" method="post" class="ajaxform">
//all the inputs
<input type="submit" value="see your results" class="button"/>
</form>
<div id="results">
//here he should see the results.php output
</div>
jQuery
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( data ) {
alert('Form is successfully submitted');
setTimeout(function() {
$('#results').load('results.php');
}, 1000);
},
error : function(){
alert('Something wrong');
}
});
return false;
});});
change this
$('#results').load('results.php');
To
$('#results').html(data);
if the returned results in data variable.
If i understood your problem correctly, results.php recieves the output you would show in the div #result.
To use the return-data from ajax-request you have data as javascript variable. To show the result in the div you need the following statment in the success function from ajax-call.
$("#result").html(data);
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.
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.
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.