Load .php site in to div without reloading - javascript

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);

Related

after ajax success refresh / reload page but prevent page blink

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.

Submitting a form for use with php inside content loaded with AJAX

I've been search for a solution to this for a while and haven't been able to find one.
My company has quite a few webtools that we use for our jobs and I have been tasked with combining them all into a dashboard page. One of my coworkers started this project but never finished it before he left, so now I have to figure it out and there are quite a few problems.
The dashboard page is composed of a couple of sidebars, plus a "main" element. The sidebar includes a bunch of links that when clicked load specific php pages into the "main" via a call to jQuery AJAX. Here's a simplified example:
<html>
<head>
<script>
$(function() {
$("#pageToLoad").click(function() {
$.ajax({
url: "some_directory/pageToLoad.php",
success: function(result) {
$("#main").html(result);
}
});
});
});
</script>
</head>
<body>
Load Page
<main id="main"></main>
</body>
</html>
The problem here is that most of our tools use forms that are submitted via POST and then parsed with PHP (has to be php because it connects to our database to get information needed). Here's a simplified example of a tool page:
<?php
$action = htmlspecialchars($_SRVER["PHP_SELF"]);
function getResults() {
if(isset($_POST["infoForQuery"])) {
//Do some sort of query to database and print out results
}
}
?>
<body>
<form action="<?php echo $action;?>" method="post">
<input type="text" name="infoForQuery">
<input type="submit" value="submit" />
</form>
<div>
<?php getResults();?>
</div>
</body>
I need to be able to use these tools inside the dashboard page, but whenever I try to submit a form, it just reloads the entire dashboard page, resulting in the POST data not existing (maybe this is because the PHP code is run before ajax loads the content into the dashboard page? not sure).
I know I can use AJAX to send the POST like so:
$(function() {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'some_directory/pageToLoad.php',
data: $('form').serialize(),
success: function() {
alert('form submitted');
}
});
});
});
However, this does not allow me to use the data collected in the form to query a database and print results out on the page.
Is it possible to accomplish this without having to leave the dashboard page, and if so, how?
Edit: I believe I've figured it out! What I wasn't realizing was that when I overrode the submit function and used ajax to send the post instead, I could actually retrieve the result of that post and put it into my page. Here's what I did:
<script>
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'some_directory/pageToLoad.php',
type: 'post',
data: $('form').serialize(),
success: function(result) {
$("#main").html(result);
}
});
});
</script>
Could be because the submit event is not firing. Since your forms are loaded dynamically do it like this:
$(function() {
$(document).on('submit', 'form', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'some_directory/pageToLoad.php',
data: $('form').serialize(),
success: function() {
alert('form submitted');
}
});
});
});

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.

Get public function via ajax based on a custom script

I am trying to execute a public function with an ajax script with the following
In the front end, root folder from where I am trying to call the public function I have within the contents of the file
details-page.php
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function () {
$("#formaddtofav").on("submit", function (e) {
$.ajax({
type: "post",
url: "lib/execute-ajax.php",
data: $("#formaddtofav").serialize(),
success: function(){
alert("form was submitted");
}
});
e.preventDefault();
});
});
</script>
and HTML
<form id="#formaddtofav">
<input type="submit" name="addtofav" onclick="displaymessage()" id="addtofavs" class="addtofav" value="">
</form>
the public function is located in lib/details-page.inc and looks like this http://pastebin.com/U5tCxwVc
and in the file lib/execute-ajax.php I am echoing the function like I would if i would have not used ajax
<?php
include_once('detail-page.inc');
echo $objWebUser->addtofavorites();
?>
The problem is that I get a success message just that the data is not inserted in the database, what am I missing here.
Function addtofavorites() works 100%, tested with the old method of inserting data (<form action="" method="post"> and if isset).
EXPECTED OUTPUT
When i click the input submit, function should be run and do all the things I have written:
Add data into dbs, check if data is already there and print the coresponding messages.
Please help me on this. It's my first attempt on integrating ajax. It's much appreciated any help.

Categories

Resources