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.
Related
Ok so I have a script that layers data throughout the process (an online test, data is kept for up to 50 questions). I have recently found that my Ajax and jquery code is not stopping all users from getting a secondary page that is meant to be reloaded in place of a DIV currently on the page. All information is passed through the jquery and ajax and works great, but sometimes on a users very first visit and first question it loads the page that is just meant to replace the DIV information currently and is not meant to be visible.
Here is my Ajax & jquery code:
<script>
$("#quizForm").submit(function(event){
event.preventDefault(); //prevent default action
var post_url = $(this).attr("action"); //get form action url
var form_data = $(this).serialize(); //Encode form elements for submission
$.post( post_url, form_data, function( response ) {
$("#prntqst").html( response );
dataLayer.push({"event" : "formSubmitted", "formName" : "'.$this->quizID.'"});
});
});
</script>
Here is the HTML:
<div id="prntqst"> <!-- this is DIV set to be reloaded -->
<font class="prntqst-text">Question Goes Here</font>
<form id="quizForm" action="ajax.php" method="post"> <!-- Script setup to handle submitted data -->
<input type="hidden" id="next_question" name="next_question" value="2">
<input type="hidden" id="quiz_type" name="quiz_type" value="learning">
<input type="hidden" id="quiz_name" name="quiz_name" value="knowledge-1">
<label class="container" for="a">Ans A
<input type="radio" name="answers[1]" id="a" value="a">
<span class="checkmark"></span>
</label>
<label class="container" for="b">Ans B
<input type="radio" name="answers[1]" id="b" value="b">
<span class="checkmark"></span>
</label>
<label class="container" for="c">Ans C
<input type="radio" name="answers[1]" id="c" value="c">
<span class="checkmark"></span>
</label>
<div class="subbtn_contain">
<div class="submitbtn">
<input id="submit" type="submit" class="button" value="Next Question">
</div>
</div></div>
</form>
<!-- currently this is the location of Ajax and jquery script -->
<div>
So when the form is submitted it processes the data through the ajax.php page, and then page reloads the next question into the "prntqst" DIV, after the first page load every request is sent to the ajax.php location, and all subsequent reloads carry all of the data needed for the test to work properly. However I find that if I use a new computer, or clear the cache the very first request can sometimes result in the user be pushed to the location of the ajax.php instead of them staying at the current URL with a DIV reload.
I have verified this issue through my analytics account, 99% of the time a user still shows at the correct URL as if the ajax is properly reloading the DIV, however sometimes it does show a user directly at the ajax.php script.
Any ideas or comments would be appreciated,
Thanks again!
Okay, I see now.
If you can have "some garbage" inside a code block and, as you say
works with or without that line...
That's because that code block is not even running at all.
The processData: false is a value assignation to an object property. It is ouside any object, in the code you provided. Then it seems like you tried to comment it like this: <!-- removed from code processData: false; -->, which also should throw an error. That is the HTML way to comment lines. in JS, it would be // removed from code processData: false;.
So... It seems that the form submits anyway. That just can the the "normal" form submit where the whole page reloads. As a test. Please try your page with that script completely removed. You should see no difference.
There is something else to explain here. You are playing with "dynamic" elements. Those are elements that didn't exist on page load and were added after... Or element that were there and were removed/replaced.
You have to write the script in such that this situation is handled.
In $("#quizForm").submit(function(event){ an event handler is attached to the element #quizForm. If there is no such element in the page when the page first load... Or there is a parsing error... The function won't run. So the event.preventDefault() won't be called either.
Then, assuming you fixed all errors in that code block and it runs. It squarely replaces all the HTML inside #prntqst. So for the second submit, the element on which the event handler was attached is not there anymore and the function won't run again.
The solution for that is to use event delegation to attach the event handler to the document and "delegate" it to the #quizForm (if exist when the handler is called).
That is $(document).on("event", "delegated_element_selector", function(){
So when the "event" fires within the "document", a lookup is made to find the "delegated_element_selector" and if found, the handler is executed.
That way is the way to have some event handler for the dynamic elements in a page.
Additionnally, about your question where to place the code, I added a $(document).ready() handler, which ensures the initial page load is complete before trying any jQuery lookup on some elements. So you can place that script where you want.
$(document).ready(function () {
$(document).on("submit", "#quizForm", function (event) {
console.log("Custom submit")
event.preventDefault(); //prevent default action
var post_url = $(this).attr("action"); //get form action url
var form_data = $(this).serialize(); //Encode form elements for submission
$.post(post_url, form_data, function (response) {
console.log(response)
$("#prntqst").html(response);
dataLayer.push({ event: "formSubmitted", formName: "'.$this->quizID.'" });
});
});
});
Now you should see "Custom submit" in the console on each form submit. And you should see what is the response too.
About post_url , I didn't any action attribute to the <form>... Maybe you just did not post it here on SO. Make sure there is one. Also make sure that the response $.post() should receive only is the necessary HTML and not a whole page (with <head>, <body>, etc...).
I have PHP code which successfully gets the contents of a directory on my server.
I wish to then write this array to a specific div on my main html page (so that I can parse this later and use this information further)
Currently my PHP navigates me away from my current page to write this array which I want to prevent.
Furthermore I wish to do all of the PHP work on a button click, and return the values on the main html page after.
How can I do this???
My button on my html page is as follows:
<form action="PHP_Function.php">
<input type="submit" class="learnButton" name="insert" value="Find Available Evidence" />
</form>
And my PHP code looks like this to carry out the work:
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'insert':
insert();
break;
}}
I have an array: "IfPresentArray" which I then wish to write to my main html page:
if(in_array("Facebook.xml", $dirArray)){
$IfPresentArray[0]="1";
}else {
$IfPresentArray[0]="0";
}
Any help would be greatly appreciated as I am very new to PHP.
Thanks in advance
You need to use AJAX techniques to do this. Use a Javascript framework like jQuery to react to the button click, make a request to your PHP script, and then update the contents of the div.
See http://api.jquery.com/click/ for handling clicks, and http://api.jquery.com/jQuery.ajax/ for making the request.
Good luck!
You will need to use an ajax call. This allows your to click some div, send something to the server, receive a response and display an output in many different formats.
You can either reference the jQuery library in your header
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
or just download it and save it whereever
Here is a basic ajax call:
<script>
$(document).ready(function(){
$('#someval').click(function(){
var content = $('#somecontenttoadd').val; //this could be many things... etc(.text, .html)
$.ajax({
type:'post',
url: 'PHP_Function.php',
data: 'action='+content,
success: function(resp){
$('#somediv').html(resp); //lets put the information into a div
//this could be anything response format like .val or .text instead of .html
},
error: function(e){
alert('Error: ' + e);
}
});
});
});
</script>
HTML -- you can get rid of the tags and just use the id of the object.
<input type="submit" class="learnButton" name="insert" value="Find Available Evidence" id="someval"/>
As others said, AJAX is the solution, I will give you the code that works for me, so that you have an exact starting point.
As I understand you have a separate html page and a php file that includes your function.
In order to make this work you will have to implement a function with an AJAX call.
This should be placed in a javascript file and will be invoked after the form submit button is clicked on the html page.
The AJAX call will then invoke your php function, get the response data back from php.
The javascript function will update the html page in the end.
You will need three files:
main.html
script.js
function.php
Let me replace my original answer with a full example of the three files.
main.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="/script.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<form id="myForm" method="post" action="function.php">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Name">
</div>
</form>
<div class="modal-footer">
<button type="submit" form="myForm" class="btn btn-primary" id="SaveButton">Submit</button>
</div>
<div id="resultbox">
</div>
</div>
</body>
</html>
Here we included jQuery, our own javascript and bootstrap just to look better. the form action is our function.php, the form 'id' is used in our jQuery code. the "result box" box will display the response.
script.js
$(function(){
$("#myForm").submit(function(event) {
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
success: function(data)
{
//display data...
$("#resultbox").html(data.name).show;
}
});
return false;
});
});
this will override the default form submit behavior. I had a typo here in the original answer, I fixed it. url and data are taken from the html form, dataType is set to json, because we expect a json back.
function.php
<?php
echo json_encode(array('name' => $_POST['name']));
Our php code is just one line, we build an array and return it as json. You can then used in jQuery, just like any other json, as shown in the above code.
I had a question about JavaScript Popup here JavaScript popup result from a form
Now I was wondering, since no one could really help me out here, not even the internet!
is it possible to use JavaScript Dialog to show the result of a form with action "..php"
I could not find it.
situation:
imagine, we got 2 php files, index.php and test.php
is it possible to make a form with a submit button on index.php, with action="test.php"
but that the file test.php will get loaded in a JavaScript Dialog.
something like this: http://jqueryui.com/dialog/#animated
echo "<form action='getlist.php' method='post'>
<input type='text' name='exte' class='exte' value=".$value['ext'].">
<input type='submit' name='aanvragen' id='aanvragen' value='aanvragen'></form>";
echo "</td>";
This is what I have, now I want the getlist.php get loaded in a popup or Dialog.
I hope that I've been clear about my question, I am trying to get this working for hours now and quite lost my mind.
Sure it is, shouldn't even be very hard, just submit the form with ajax and show the result in a dialog
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize()
}).done(function(data) {
$('#dialog').html(data).dialog(settings);
});
});
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;
}
?>
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) {
}