I'm trying to get a page which includes a POST form to load inside an iframe for users to be able to confirm an action such as deleting a listing. I have successfully got the JS and the form page to load inside the iframe, but when I click an action inside the form, it's not updating the listing. Instead, it just refreshes the page.
The form is working fine because if I try to access the content-url manually in the browser and update the form, it works fine.
How can I get the iframe content to refresh instead of the parent page and load the response inside the iframe itself? What I am doing wrong exactly?
Any help is appreciated!!
Here's my code:
HTML:
<button class="myclass" content-url="<?php bloginfo('siteurl') ?>/?a_action=delete_auction&pid=<?php the_ID(); ?>">Delete Me</button>
<div class="popup"><iframe id="mynewiframeid" name="myframename" src=""></iframe></div>
JS:
$(document).ready(function() {
$(document).click(function(e) {
if ($(".popup").is(":visible")) {
$(".popup").fadeOut("fast")
}
});
$(".myclass").click(function() {
if (!$(".popup").is(":visible")) {
$('#mynewiframeid').attr('src',$(this).attr('content-url'));
$(".popup").fadeIn("slow");
}
return false;
});
$(".popup").click(function(e) {
e.stopPropagation()
})
});
Form:
<div class="popup_content">
<h3> You are about to delete <b><?php echo $title; ?></b>!</h3>
<?php
if(isset($_POST['yes_confirm']))
{
$s = "update ".$wpdb->prefix."posts set post_status='trash' where id='$pid'";
$wpdb->query($s);
echo '<div class="deleted_item_ok">';
printf(__('Your item has been deleted successfully!'));
echo '</div>';
}
else
{
?>
<form method="post">
<div class="are_you_sure_delete">
<?php
_e('Are you sure you want to delete this item?');
?>
</div>
<button class="button-small button-w-green" type="submit" id="submits" name="yes_confirm">Yes, Delete</button>
<button class="button-small button-w-red" type="submit" id="submits" name="no_confirm">No!</button>
</form>
<?php } ?>
</div>
You are trying to replace html in the class "popup" with following js code..
HTML => <div class="popup"><iframe id="iframeid" src=""></iframe></div>
JS => $('.popup').html(response);
This replaces the iframe element in the HTML above with the response..! Therefore after response comes, no iframes inside the page..
If you do want to use an iframe, I don't think you have to deal with AJAX. Instead just change the src of iframe. You may use following js code..
$(document).ready(function() {
$(document).click(function(e) {
if ($(".popup").is(":visible")) {
$(".popup").fadeOut("fast")
}
});
$(".myclass").click(function() {
if (!$(".popup").is(":visible")) {
$('#iframeid').attr('src',$(this).attr('content-url'));
$(".popup").fadeIn("slow");
}
return false;
});
$(".popup").click(function(e) {
e.stopPropagation()
})
});
Fiddle (with fake src urls)
First of all, correct the following errors and then see if it works:
in your you are missing semicolon after the closing parenthesis
you close the php tags and right after you continue with url and then you add another closing php tags
What you are looking for is this inside your content-url:
<?php bloginfo('siteurl') . '/?a_action=delete_auction&pid=' . $the_ID; ?>
What is the_ID()? I dont see that function. And if exists it has to return the value that you will store in variable $the_ID. You also have to call that function before button tag to get that variable.
In your JS you need to wrap everything in $(document).ready(function() {}
It seems you are trying to do GET request and not POST request since you are not sending any data in the body but in the url
Missing semicolon at the end of first .click function
I didn't even look at all other .click functions cause there's some repetitions going on and more weird stuff
Related
From this earlier thread I thought I learned that form data could be sent by POST method using javascript submit() command. But I can't get it to work. This demo doesn't make obvious sense with respect to purpose but bear with me. I just wanted to test this specific command which doesn't seem to work for me. Can you please help me? Clicking the regular submit button sends the post data ok but activating the javascript via the link does not.
<html><body>
<?php
$self = $_SERVER['PHP_SELF'];
$posttext = file_get_contents('php://input');
echo "Received input: ".chr(34).$posttext.chr(34)."<br><br>";
echo "<form id='test' action='{$self}' method='post'>";
?>
Please fill in the fields with any text:<br><br>
foo: <input type="text" name="foofield"><br><br>
bar: <input type="text" name="barfield"><br><br>
<input type="submit" value="Submit button works"><br><br>
Submitting by JS not working – why?
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
jQuery(function($) {
$(document).ready(function(){
$("a#submitlink").click(function(){
alert("Yes, the link has been clicked. It is not that.");
$("form#test").submit();
});
});
});
</script>
</body></html>
You need to: event.preventDefault(); the default behaviour from the <a>. The problem is if you don't do that, the page reloads cause that is what the <a> tag does. So even you submit the data you also refresh the page where the submitted data gets lost.
$("a#submitlink").click(function(event){
event.preventDefault();
$("form#test").submit();
});
The other solution is to add # in the href of the <a> tag like:
Submitting by JS not working – why?
this will also prevent the <a> tag from doing a refresh.
I am trying to insert html and javascript which is generated in php into a div in the page.
a.php file:
function get_preset() {
return (bunch of html, javascript);
}
b.php:
<div id="preset_preview">
//<?php echo get_preset(); ?> //this works well, but I need to execute this every time I click a button in jquery.
</div>
I can use ajax to communicate between my jquery and a.php successfully, but how do I place returned content from get_preset function call in php into preset_preview div?
Is there a way to do this without sending data with ajax from get_preset function call into jquery, then use jquery to put this into preset_preview div?
Can php somehow do it alone each time on request from jquery like this?
So I use jquery ajax to call php to execute this:
<div id="preset_preview">
<?php echo get_preset(); ?>
</div>
What is confusing to me is that php can do it successfully (as example above demonstrates) without sending data with ajax to jquery first.
a.php file
function get_preset() {
return (bunch of html, javascript);
}
echo get_preset();
b.php file
<button type="button" id="preview">Preview Preset</button>
<div id="preset_preview">
<?php include "a.php"; ?>
</div>
<script>
$('#preview').on('click', function(e) {
e.preventDefault();
$("#preset_preview").load('a.php');
});
</script>
There are several methods of jQuery AJAX which you can actually use. Example above is using load() which wraps your request with get method (you can override its request method by calling ajaxSetup(), anyways) to relative URL of a.php.
You can see a.php echoing (string of?) get_preset() function which will then placed inside <div id="preset_preview"> in b.php file.
To expand the needs of AJAX in this case is because PHP only does something like
Getting a request, no matter what the method is (get, post, put, etc)
Returns a response. Usually after you do some logic related to request value.
It dies whenever your expected response rendered to client side. You can't do anything magic behind the wall right after response is returned. In the other word, a page load is needed.
And then AJAX comes to help you create another request to corresponding PHP file. It revives a PHP file to do (another) request -> do some logic -> then do returning it. Silently, without a page load.
And in respond of comment -- Can this be done with function calls somehow without including the actual php file in preset_preview?
It's all yes. As long as you serve whatever the caller needs.
a.php file
function get_preset() {
return (bunch of html, javascript);
}
echo get_preset();
The a.php is simply echoing get_preset().
b.php
<button type="button" id="preview">Preview Preset</button>
<div id="preset_preview"></div>
<script>
$('#preview').on('click', function(e) {
e.preventDefault();
$("#preset_preview").load('a.php');
});
</script>
The b.php file is simply doing a request to a.php file. Whenever the button with selector id #preview is clicked it will load whatever a.php content to #preset_preview.
You can also render the content of a.php just after the page ready. This is similar approach like my first snippet as written on above.
<script>
$(document).ready(function() {
$('#preset_preview').load('a.php');
});
$('#preview').on('click', function(e) {
e.preventDefault();
$("#preset_preview").load('a.php');
});
</script>
It simply tells you that you should load a.php right after the b.php page is ready and "reload" it once the button clicked.
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 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) {
}