Refresh chart(javascript) after doing mysql Query - javascript

I've got a javascript for drawing a chart. I get my information out of my MySQL base. And I got 3 different buttons to get the different information out of the database.
My problem now is, I get the information out of my database, it shows it in the chart but when it shows the information it refreshes the page.
Is there a way to show the information after my page is refreshed? I actually tried to use the window.onload but that doesn't give me the wanted result.
in php I use the following code to get the info from my MySQL DB:
if(isset($_POST['btnProduct']))
{
....
}
in html it's like this:
<div class="content">
<form action="" method="post" enctype="multipart/form-data">
<input type="submit" name="btnProduct" id="btnFilterProduct">
</form>
</div>
And in JS I use this code:
<script type="text/javascript">
window.onload = function()
{
document.getElementById('btnFilterProduct').onclick = function()
{
....
}
}
I know the PHP needs to refresh to get the data. and Javascript doesn't. But can I change the order? Or is there a way to change my JS to let it load AFTER the page is refreshed?

To stop the page reload, modify your onclick function to be:
document.getElementById('btnFilterProduct').onclick = function(event) {
event.preventDefault();
...
}
event.preventDefault stops the default behavior of the event, which in this case is to refresh the page since you have an empty action. Another option would be to not use a form. Just use the <button> element instead.

Related

Pass Javascript variable to another page via PHP Post

I am having two php pages:
page 1:
<form class="form-horizontal" role="form" method="post" action="Page2.php">
<button id="place-order" class="btn btn-lg btn-success">Place Order</button>
<div id="ajax-loader" style="display:none;"><img src="images/ajax-loader.gif" /></div>
</form>
<script>
var id = Math.random();
$(document).ready(function() {
$('#place-order').on('click', function() {
$(this).hide();
$('#ajax-loader').show();
});
});
</script>
As on form, it redirects to Page2.php, I want to pass the Javascript variable "id" from Page1 to receive it in Page2.
I have tried using cookies, but need an alternative approach.
I am not understanding the transistion from PHP to JS and vice-versa. Help is appreciated.
Thanks in advance
Dear you can do it very easily with ajax. Ajax has data attribute which helps you pass your data from javascript to another page.
This link will help you a lot
https://api.jquery.com/jquery.ajax/
You can use session storage or cookies.
Example for session storage:
// First web page:
sessionStorage.setItem("myVariable", "myValue");
// Second web page:
var favoriteMovie = sessionStorage.getItem('myVariable');
You could use a query string to pass the value to the next page.
Add an ID to the form
<form class="form-horizontal" role="form" method="post" action="Page2.php" id="order-form">
Update the action of the form to add this query string from our JS variable
var id = Math.random();
$('#order-form').attr('action', 'Page2.php?id=' + id);
Get this variable in PHP (obviously you might wanna do more checks on it)
<? $id = $_GET['id'] ?>
We can now use $id anywhere in our PHP and we'll be using the ID generated from JS. Neat, right? What if we want it in JS again though? Simply add another script tag and echo it there!
<script type="text/javascript">
var id = <? echo $id ?>;
</script>
EDIT: Updated to add a little about how it works as you said you're not too sure about the transition between PHP and JS.
PHP runs on the server. It doesn't know much about the browser, and certainly doesn't know about JS. It runs everything and finishes executing before the web page is displayed. We can pass PHP variables to JS by creating script tags and creating a new javascript variable, echoing the PHP value.
JS (JavaScript) runs in the browser. It doesn't know about anything that happens on the server; all it knows about is the HTML file it is running in (hit CTRL+U to see raw HTML). As JS runs at a completely separate time to PHP there is no easy way to transfer variables (e.g. $phpVar = myJSVar). So, we have to use server methods like POST or GET.
We can create a GET or POST request in 2 main ways:
Using a form
Using an AJAX request
Forms work in the way I've outlined, or you can create a hidden field, set the value you want and then check for that. This involves redirecting to another page.
AJAX (Asynchronous Javascript And Xml) works slightly differently in that the user doesn't have to leave the page for the request to take place. I'll leave it to you to research how to actually program it (jQuery has a nice easy API for it!), but it basically works as a background request - an example would be displaying a loading spinner whilst loading order details from another page.
Hope this helps, let me know if something's not clear!

Getting Javascript/jQuery and PHP To work together

UPDATED:
Okay, Thanks to OneSneakyMofo's Help below, I have managed to use ajax to call a submit.php form and have it return for example an echo statement. My problem is that none of my $post values are being carried over, for example if my start my php script with if (isset($_POST['pizzacrustformid'])) { the javascript will return blank, also when I do a var_dump($_POST);, Nothing is being saved into it which means the data is not being carried over, the php script is just being called. Please let me know if there is something I need to do in order to get the POST information to get carried over from the form as it would with a
< Submit > Button traditionally.
I Have Updated my code on Github to reflect my progress. https://github.com/dhierholzer/Basiconlineordering Thanks Again!
ORIGINAL POST:
I am new to using jquery and having forms be submitted without loading a newpage /refreshing the page.
In my Code I have multiple forms on one page that display one at a time via fade in and out effects by hitting the next button.
My problem is now that I do this, I cannot seem to get a PHP script to activate when hitting the next button to save those form options into sessions.
So here is an example:
<!--First Pizza Form, Pick Pizza Crust Type-->
<div id="pizzacrust">
<form method="post" name="pizzacrustform" id="pizzacrustformid">
<div id="main">
<div class="example">
<div>
<input id="freshpizza" type="radio" name="pizzacrust" value="1" checked="checked"><label style="color:black" for="freshpizza"><span><span></span></span>Fresh Dough</label>
</div>
<div>
<input id="originalpizza" type="radio" name="pizzacrust" value="2"><label style="color:black" for="originalpizza"><span><span></span></span>Original</label>
</div>
<div>
<input id="panpizza" type="radio" name="pizzacrust" value="3"><label style="color:black" for="panpizza"><span><span></span></span>Deep Dish Pan</label>
</div>
</div>
</div>
</form>
</div>
<div><button href="#" id="btn">Show Pizza Size</button></div>
So this Is my First Form, One thing to pay attention to is that instead of a < Submit > button, I am using a normal button and using javascript to do the submitting part.
Here is that Javascript:
<!--Controls All Button Fades-->
$('#btn').click(function(e){
$('#pizzacrust, #btn').fadeOut('slow', function(){
$('#pizzasize, #btn2').fadeIn('slow');
$('#pizzacrustformid').submit();
});
});
and Then:
$(document).ready(function () {
$('#pizzacrustformid').on('submit', function(e) {
e.preventDefault();
});
});
Now Traditionally being a php programmer, I just had a button in my form and then my php activated by having something like:
if (isset($_POST['submitted'])) { //MY Code To save values into sessions}
I cant seem To Get a function like that working when the form is submitted via a javascript function as I have it.
Here is my full code in my GitHub which may make it easier to see more so how these forms are working together right now.
https://github.com/dhierholzer/Basiconlineordering
Please Let me know any solutions that might be possible
Thanks again.
Edit:
OP, it looks like you are wanting to do AJAX, but you don't have anywhere to submit your AJAX to. Firstly, you will need to create a file that accepts the form.
Let's call it submit.php.
With that in place, you can start working on the AJAX call. To begin, you will need to separate your code from index.php.
Take this out of index.php and put it in submit.php:
if (isset($_POST['pizzacrustformid'])) {
// use a foreach loop to read and display array elements
echo '<p>hello!<p>';
}
In your Javascript, you will need to do something like the following:
$('#btn').click(function(e){
$.ajax({
method: "POST",
url: "some.php",
data: $('#pizzacrustformid').serializeArray()
})
.done(function(data) {
alert(data); //should be "Hello world"
$('#pizzacrust, #btn').fadeOut('slow', function(){
$('#pizzasize, #btn2').fadeIn('slow');
});
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
});
What is happening here is is on submit, your form data will pass over to the submit.php page, and it will generate the PHP code. That code will hit the done function (if it's successful), call an alert, then fade out to the next section.
That should get you on the right path. I would create another branch and strip out all of the forms and work on getting this done before continuing.
Also, I would set this all up in one single form and show the first section, do some validation, and then move on to the next section before finally submitting eveyrthing you need.
Hope this helps.
I recommend you do requests via ajax, here a tutorial and examples:
http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
delete all jquery functions about submit
create a file called blu.php with the php code
add the jquery code in index.php
with this you only do once request at the end. I hope this helps you.
<?php echo 'tus datos son: ';
echo ' '.$_POST["data1"];
echo ' '.$_POST["data2"];
echo ' '.$_POST["data3"]; ?>
<script>
$(document).ready(function(){
$("#btn5").click(function(){
var pizzacrust= $('input[name="pizzacrust"]:checked').val();
var pizzasize= $('input[name="pizzasize"]:checked').val();
var pizzatoppings= $('input[name="pizzatoppings"]:checked').val();
$.post("blu.php",
{
data1: pizzacrust,
data2: pizzasize,
data3: pizzatoppings
},
function(data,status){
alert("Data: " + data);
});
});
});
</script>
I think you need to using click() func call ajax, dont use on() submit. Submit action makes current page will refresh. I will review your code later, but you should to try this solution above.

Posting Div Content in Php

I have two php pages. In the first.php page user choose orders and a div is filling with this content, no problem. And there is a confirm button to confirm these list. When the user click this button, second.php page should be opened and the contents of the div should be displayed on that page. This is my html code for the first.php div and confirm button.
<form method="post">
<div class="col-md-5" id="orderList">
<h3 align="centre">Order List</h3>
</div>
</form>
<form role="form" method="post" action="second.php">
<div id="firstConfirmButton">
<button type="submit" name="firstConfirmButton" id="firstConfirmButton" class="btn btn-primary btn-lg">Confirm</button>
</div>
</form>
This is the javascript code to post the contents to second.php. First alert is working fine but second alert is not.
$("#firstConfirmButton").click(function() {
var content = $('#orderList').html();
alert(content);
$.post("second.php", { html: content})
.done(function(data) {
alert(data);
$('#confirmForm').empty().append(data);
});
});
Second.php page has the confirForm div and I want to display the contents in this.
<div id="confirmForm"> </div>
Where is the problem?
Your button is a submit button, so if you don't cancel the default event, the form will be submitted the regular way as well.
You need to capture the event and cancel it:
$("#firstConfirmButton").click(function(e) {
var content = $('#orderList').html();
e.preventDefault();
// the rest of your code
Or in modern versions of jQuery:
$("#firstConfirmButton").on('click', function(e) {
var content = $('#orderList').html();
e.preventDefault();
// the rest of your code
You submit the form to the page second.php by using the POST method, so the data can be retrieved from the second page by using this PHP code:
var_dump($_POST);
So basically, the data is stored within the $_POST array.
Regarding your second question. You need to avoid that you submit the default form if you first need to grab a value form a Javascript. You can do that by something like that:
$("#firstConfirmButton").click(function(e) {
var data = $('#orderList').html();
e.preventDefault();
//...
}
This will avoid that your submit button submits the form without adding the desired POST data to it.

jQuery Auto-submit form inside of a <div> loads in new page

I'm developing a project of "prettifying" of a part of an existing web application. There is a need of putting the existing code: search criteria form in one div, and search results in another div (forming a kind of tabs, but that's another story).
Using jQuery I was able to manage that, but right now I am struggling with the results page, which by itself is yet another form that auto-submits to another file (using document.form.submit()), which is the final search results view. This auto-submit causes that the final view quits the destination div and loads as a new page (not new window).
So, the flow is like that:
First file, let's call it "criteria.html" loads the search criteria form (inside of a div) + another div (empty) destined to be filled with search results.:
<div id="criteria">... form with search criteria here...</div>
<div id="results"></div>
On submit, using jQuery's "hide()" method, I hide the first div (surrounding the search criteria form), and make Ajax call to the second file, let's call it "results.php":
<script>
$("#criteria").hide();
$.ajax({
...,
url: "results.php",
success: function(data){
$("#results").html(data);
},
...
});
</script>
results.php searches according to given criteria, and displays an "intermediary form" (which returns as a data result of the ajax query above) with a lot of hidden fields, and at the end executes:
<script>document.form.submit();</script>
which submits to another file, let's call it "resultsView.php"
This line causes that a result page shows outside the div "results", as a new page.
As there is a lot of logic in those files (more than 700 lines each), the idea of rewriting this monster just gives me creeps.
And now the question: is this a normal behavior (opening the result outside div)?
I tried removing the document.form.submit() code and everything works fine (well, without showing the results from "resultsView.php"). It's this line that causes the viewport to reset. I also tried with empty pages (to eliminate the possibility of the interaction with contents of the pages) - still the same result.
I hope there is not too much text and the problem is clearly stated. Every suggestion of how to fix this will be greatly appreciated.
If I understand your question correctly, you need to process the final submit using ajax instead of <script>document.form.submit();</script> so that you can handle the results on-page. Traditional form submits will always reload/open the action page. If you want to avoid that you'll have to control the form submit response via ajax and handle the results accordingly... like you are doing with the first submit.
The only alternative I can think of is to make div id="results" an iframe instead, so that it contains the subsequent form submit. Of course, that unleashes further restrictions that may cause other troubles.
I am not sure if I understood your question, but maybe u can do something like this.
This is my JQuery script: [I just wait for the submission search. When it happens, I use the $.Post method to call a function that should return the Html results (You can include somenthing to hide any field you want using JQuery or css)].
<script type="text/javascript" src="http://code.jquery.com/jquery-1.3.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("form#searchForm").submit(function() {
var theCity = $("select#chooseCity").val();
var theName = $("input#searchInput").val();
$.post("callProvideSearchResults.php", {theCity: theCity, theName: theName}, function(data) {
$("div#searchResults").html(data);
});
return false
});
});
</script>
This is my Body: {it consists of the choice of a city, the a form to provide the name of the person you are lookng for and the place to provide the results.
<body>
<FORM id="searchForm">
<h2>Select the city: </h2>
<select id="chooseCity">
<?php
$theCitiesOptionsHTML = "cityOptions.html";
require($thePathDataFiles.$theCitiesOptionsHTML); / A large list of cities
?>
</select>
<h2> What is the name of the person </h2>
<P> <INPUT id="searchInput" TYPE="TEXT" SIZE=50></P>
<P><INPUT TYPE="submit" VALUE="search"></P>
</FORM>
<div id="searchResults">
<!-- Here: Search results -->
</div>
</body>
// Function callProvideSearchResults.php // Just call the function that makes all the job and echo the $Html page
<?php
include "provideSearchResults.php";
$theName=$_POST['theName'];
$theCity=$_POST['theCity'];
echo provideSearchResults($theName, $theCity);
?>
// provideSearchResults.php // Database connection and search
<?php
function provideSearchResults($theName, $theCity) {
include "databaseConnection.php";
//database Queries
// Generate $theHtml using strings or ob_start, for instance
return $theHtml;
}
?>

Hide, load, and show div with javascript

I have a few pages from each other to interact with page with id load, as below:
inside process.html
<div id="guest_details"> </div>
<div id="first_start"> </div>
<script>
<! -
$('#guest_details').load('?p=guest_details.html');
$('#first_start').load('?p=first_start.html')
$('#guest_details').hide('slow');
$('#first_start').SlideUp('slow')
->
</Script>
inside guest_details.html
<form action="guest_details.php" <form method="POST" id="guest">
<!-- Some cell here -->
<a onclick="$('#guest').submit();" class="button" id="first_start"> <span> <?php echo $button_submit;?> </span> </a>
</Form>
That I want is when the submit button is clicked then:
data sent to guest_details.php
If the data has been sent then hide < div id="guest_details"> < /div>
showing the show < div id="first_start"> < /div>
but when I make it like the above, that not work, Could someone give a clue how to correct?
Thanks a lot
Looking at your previous question and your tags, I assume you are not much aware of AJAX.
You need to
1.post the form asynchronously (without reloading the page, using AJAX).
2. On successfully sending the data, do the dom manipulations.
I suggest using jquery for doing an AJAX post.
Here is a sample code, using jquery:-
$('#guest_details').load('?p=guest_details.html');
$('#first_start').load('?p=first_start.html')
function ajaxPostForm()
{
$.post('guest_details.php',
function(data) {
//Dom manipulation
$('#guest_details').hide('slow');
$('#first_start').SlideUp('slow')
});
}
And your form html inside guest_details.html needs to be like:-
<form method="POST" id="guest">
<!-- Some cell here -->
<a onclick="ajaxPostForm();" class="button" id="first_start"> <span> <?php echo $button_submit;?> </span> </a>
</Form>
The $.post given above is a very basic AJAX post. You may add further features as give in Jquery Post.
Also if you want to post the entire form, you can refer jQuery Form Plugin
Updates
I think I understood your problem better this time. Inside your update where you say this-
by default guest_details.html is
showing and first_start.html is hiding
referring to the sections as guest_details and first_start would make more sense because guest_details.html may mean the page guest_details.html which you might have opened in another window.
Anyway, I am sure you mean the sections inside the page process.html as you have used jquery .load(). Let's call the first_start.html and guest_details.html as sections first_start and guest_details respectively.
As per your updates do you mean the following:-
Initial state
Section guest_details is shown and first_start is hidden
Cases/Situations
When form inside guest_details section is submitted, then hide the section guest_details and show first_start section.
At this state when guest_details is hidden and first_start is shown, the button on first_start can be clicked and on doing so the guest_details section shows again.
During these states where one section is hidden and another is shown reloading/refreshing the page should preserve the states.
If above is the complete scenario, here is the code:-
<script>
<! -
initiateSections(<?php echo $this->session->data['display_state']; ?>);
//state can have "display_first_start" or "display_guest_details"
function initiateSections(state)
{
$('#guest_details').load('?p=guest_details.html');
$('#first_start').load('?p=first_start.html')
if(state == "display_first_start")
{
displayFirstStart();
}
else
{//If chosen or by default
displayGuestDetails();
}
}
function ajaxPostGuestDetails()
{
$.post('guest_details.php', //In this post request - set $this->session->data['display_state'] = 'display_first_start'; in php
function(data)
{
//Dom manipulation
displayFirstStart();
});
}
function ajaxPostFirstStart()
{
$.post('first_start.php', //In this post request - set $this->session->data['display_state'] = 'display_guest_details';
function(data)
{
//Dom manipulation
displayGuestDetails();
});
}
function displayGuestDetails()
{
$('#first_start').hide('slow');
$('#guest_details').slideUp('slow');
}
function displayFirstStart()
{
$('#guest_details').hide('slow');
$('#first_start').slideUp('slow');
}
->
</Script>
You need to implement ajax to post the data to php
http://api.jquery.com/jQuery.ajax/
use ajax success to do your post success activities.
Once ajax is successful do the HTML manipulations
success: function(data) {
}

Categories