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) {
}
Related
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.
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.
I have PHP page that have submit button to another URL.
I want to reload the current page after the submit button clicked, and add div to the HTML.
My page url is: /foo.php, and in the HTML I have:
<button onclick="$.get('/bar', function() { ... })">Submit</button>
As you can see the form sends request to /bar page.
I want to reload the /foo.php (the current page), and change the HTML to:
<button onclick="$.get('/bar', function() { ... })">Submit</button>
<div>Thank you!</div>
My problem is how can I know that the user click on the button and the refresh was because the click, and not because just navigating.
Another thing, if it possible, I want that the new div will disappear if the user refresh the page again.
Why don't you just append the div in the success callback of the get function? You wouldn't have to reload the page.
<div id="btn_area">
<button onclick="$.get('/bar', function() { $('#btn_area').append($('<div>').html('Thank You');)})">Submit</button>
</div>
By the way, i hardly recommend to separate the javascript from the html and not put it directli in the DOM.
Another Method would be, to fire an additional form with a hidden parameter to the same side. After that, you check on the serverside the hidden parameter and display the div.
A third method is, to set a cookie in the Callback, reload the side, check the cookie, display the div and remove the cookie again.
In my opinion, the first mentioned option (add the div directly in the callback without reloading) would be by far the 'prettiest', but of course i don't know what else is going on on your site
Alternatively, you could simulate a flash session (one time use session) if you opt to do this in PHP. Consider this example:
foo.php
<?php session_start(); ?>
<form method="POST" action="bar.php">
<button type="submit" name="thank_you">Submit</button>
</form>
<?php if(isset($_SESSION['thank_you'])): ?>
<?php unset($_SESSION['thank_you']); ?>
<h1>Thank You!</h1>
<?php endif; ?>
bar.php
<?php
session_start();
if(isset($_POST['thank_you'])) {
$_SESSION['thank_you'] = true;
// processes
header('Location: foo.php');
}
?>
Demo
You can handle that in js side. Just make your request, and in callback, you can manipulate dom. You can see below;
<button>Submit</button>
$("button").on("click", function() {
var $button = $(this);
$.get("/echo/html", function() {
$button.after("<div>Thank you!</div>");
});
});
I have over 1.5 million dynamically created (php/html/js) web pages that contain lists of up to 300 people, to whom I need to allow visitors to send messages by using a popup form that is triggered by link next to each person's name. I'm using the PopEasy jquery modals plugin http://thomasgrauer.com/popeasy/ .
All these modals/forms are identical, except for a unique recipient ID associated with each link that needs to be passed through to the AJAX code that fires to save the message to that person's record when the modal's form's Send Message btn is clicked (e.g. "1001', '1002' in the examples below).
For each page, I could dynamically create up to 300 form DIVs, one for each link, but would rather find a clever way to transfer the recipient ID with just one modal/form DIV, to cut down the bandwidth. I should be ok, if I can reference the ID of the link from within the AJAX code (as the "u" var in the example below).
Ideas?
(my competencies: js: "barely any" / html and php: "average".
Here is the code that works for just two links/divs/forms:
<a id="1001" class="modalLink" href="#modal_1001">Send msg</a>
<a id="1001" class="modalLink" href="#modal_1002">Send msg</a>
// the plugin uses the class to fire, and the href to know which of several DIVs of
// that class to use; if the a#id isn't needed, I can strip the "modal_" part out of
// the href to save having to parse it
<div id="modal_1001" class="modal">
<form method="post" action="">
<textarea>(write your msg here)</textarea>
<button type="button" onclick="storeMsgAjax(1001,1234)">Send message</button>
</form>
Close Form
</div>
<div id="modal_1002" class="modal">
<form method="post" action="">
<textarea>(write your msg here)</textarea>
<button type="button" onclick="storeMsgAjax(1002,1234)">Send message</button>
</form>
Close Form
</div>
And here is the js modal plugin function:
$(document).ready(function(){
$('.modalLink').modal({
trigger: '.modalLink', // id or class of link or button to trigger modal
olay:'div.overlay', // id or class of overlay
modals:'div.modal', // id or class of modal
animationEffect: 'slideDown', // overlay effect | slideDown or fadeIn | default=fadeIn
...(other options)...
close:'.closeBtn' // id or class of close button
});
});
And here is the AJAX code:
function storeMsgAjax(s,u)
{
var m = document.getElementById("msgtxt").value;
var url = "http://ifinallyfoundu.com/storeMsg.php?s="+s+"&m="+m+"&u="+u+"&t=" + Math.random();
xmlHttp2 = GetXmlHttpObject();
if (xmlHttp2 == null) {alert("Browser does not support HTTP Request"); return;}
xmlHttp2.onreadystatechange = function()
{
if (xmlHttp2.readyState == 4 && xmlHttp2.status == 200)
{
var formSaveResults = xmlHttp2.responseText;
document.getElementById("modal_"+s).innerHTML = formSaveResults+'<br><br>Close Form' ;
}
}
xmlHttp2.open("GET", url, true);
xmlHttp2.send(null);
}
Looks like I can add an onclick script to each link to put the ID in the innerHTML of a hidden page element, which should be accessible to the AJAX routine. I'm sure there is probably a more elegant solution, but this seems to work.
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;
}
?>