PHP Post to Simple Modal then Update the page - php

So what I'm attempting to do is this:
User clicks a radio html form button.
User clicks a submit button to confirm his choice.
SimpleModal pops up and displays the value of the button chosen.
User clicks 'Accept' in the SimpleModal and the parent page updates accordingly.
I'm not so worried about step 4, but I'm not sure how to transfer the post information into the SimpleModal.
For reference I'm using the SimpleModal Contact Form demo that Eric Martin has provided.
I'm new to Ajax as well as jQuery.
I saw this post: Passing a Value from PHP to the SimpleModal Contact Form
They had a similar problem, however they are not retrieving post information from their index page.
Is there a way to retrieve this post information and pass it to the contact.php that is called for the SimpleModal window?
Any help is greatly appreciated.
My index (where radio buttons are generated.):
<div id='contact-form'>
<form action="index.php" method="get">
<?
echo "<h3>Degrees (double click a degree to add a generator):</h3><br />";
for($deg = $_SESSION['degmin']; $deg <= $_SESSION['degmax']; $deg++)
{
?>
<table>
<tr>
<th>
<?
echo $deg;
for($gen = 0; $gen < $_SESSION['degree_gens'][$deg]; $gen++)
{
echo "<input type='radio' name='test' value='deg' />";
}
?>
</th>
</tr>
</table>
<?
echo "<br /><br />";
}
?>
<input type='submit' name='contact' value='Demo' class='contact demo'/>
</form>
</div>
My contact.js (this is called from index when user clicks "Demo):
$.get("data/contact.php", { r: $("input[name='test']:checked").val()}, function(data){
// create a modal dialog with the data
$(data).modal({
closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
position: ["15%",],
overlayId: 'contact-overlay',
containerId: 'contact-container',
onOpen: contact.open,
onShow: contact.show,
onClose: contact.close
});
});
My contact.php (The modal displays this page, trying to output post info):
<h1 class='contact-title'>Edit Generator(" . $_POST['test'] . "):</h1>
-Chad

As I understand, you want to load modal from external php file, so you should pass the variable with GET or POST paramater, here is an example how you can do that,
cantact.js
$.get("data/contact.php", { test: $("input[name='test']:checked").val()}, function(data){
// create a modal dialog with the data
$(data).modal({
closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
position: ["15%",],
overlayId: 'contact-overlay',
containerId: 'contact-container',
onOpen: contact.open,
onShow: contact.show,
onClose: contact.close
});
});
contact.php
<h1 class='contact-title'>Edit Generator(" . $_GET['test'] . "):</h1>
POST and GET are different types of HTTP request method.
In jQuery,
if you use $.get(), you can get parameters with $_GET in PHP.
if you use $.post(), you can get parameters with $_POST in
PHP.

$('form').submit(function(e){
e.preventDefault();
var ourVal = $('input:radio').val();
$.modal('<div id="ourModal"><div id="modalText"></div></div>');
$('#modalText').text(ourVal);
});

Related

Popup - open form, submit data and return selected values

I've install bPopup and have a simple popup configured on my main.php page:
$('#element_to_pop_up').bPopup({
contentContainer:'.content',
loadUrl: 'test.php',
onClose: function(){
var name = $('#name').val();
console.log(name)
}
});
When the button is pressed #element_to_pop_up is shown and test.php is loaded. test.php contains:
SITE<br/>
NAME <input type='text' id='name' name='name' value=''><br/>
ID <input type='text' id='idd' name='idd' value=''><br/>
DESC <input type='text' id='desc' name='desc' value=''><br/>
<input type='submit' class="b-close" />
When the close button is pressed the popup closes and my console.log does show the value from name
What I'd like to do is have is
a close button that closes the popup without passing the values back
a separate submit button that submits the form to a database, closes the popup and returns the 3 values to the parents OnClose function.
I've created a codePen that shows the code so far.
Any one any idea how I can do this ?
Thanks
I am happy to consider a different plugin if that helps..
In your test.php add two buttons with ID's
<input type='button' class="b-close" id='close' value='close'/>
<input type='button' class="b-close" id='save' value='save'/>
Change your onClose function to detect which button was selected and then set the onClose function to work with this.
onClose: function(){
var val = $(document.activeElement).attr('id'); // ID of selected button
console.log (val)
if ( val == 'close') { // close popup
return false;
}
var name = $('#name').val(); // return values.
console.log(name)
}
}
New codePen showing this.
Open the pen's console log, launch the popup and enter your name.
If you click save you should get your name shown in the console. If you click close you should get 'close' shown in the console.
Hope this helps.

jquery popup div on click an element in a form

i have a form with four elements. i need to open a jquery popup when click on image that i set as fourth element in my form. popup window contains another form and a submit button. herepopup not coming. what wil i do.
this is my form
echo "<div class=\"addform\">
<form method='GET' action=\"update_events.php\">\n";
echo " <input type=\"hidden\" name=\"column1\" value=\"".$row['event_id']."\"/>\n";
echo " <input type=\"text\" name=\"column2\" value=\"".$row['event_name']."\"/>\n";
echo " <input type=\"text\" name=\"column3\" value=\"".$row['description']."\"/>\n";
echo " <input type=\"image\" src=\"images/update.png\" id=\"update_event\" alt=\"Update Row\" class=\"topopup\" onClick=\"callPopup(".$row['event_id'].")\"; title=\"Update Row\">\n";
}
echo "</table></form><br />\n";
this is my jquery
<script type="text/javascript">
function callPopup(id) {
console.log(id);
var datastring = "&event_id="+id;
$.ajax({
url: 'event_edit_popup.php', //enter needed url here
data: datastring,
type: 'get', //here u can set type as get or post
success: function(data) {
$('.popupContent').html(data);
console.log(data);
$('.loader1').hide();
$("#popup_content").after(data);
// u can see returned data in console log.
// here, after ajax call,u can show popup.
}
});
};
</script>
and this is my popup div
<div id="toPopup">
<div class="close"></div>
<span class="ecs_tooltip">Press Esc to close <span class="arrow"></span></span>
<div id="popup_content"> <!--your content start-->
<p align="center">edit company</p>
</div> <!--your content end-->
</div> <!--toPopup end-->
<div class="loader"></div>
<div id="backgroundPopup"></div>
You just need to give the image an id.. say id="clickme"
and in the jquery script:-
$('document').ready(function(){
$('#clickme').click(function(){ $('#topopup').show(220);}); });
Again u can add in transitions in the css of the topopup to give it various effects.
Also to hide the pop up:-
$('document').ready(function(){
$('#backgroundPopup').click(function(){ $('#topopup,#backgroundPopup').hide(220);}); });
//This is assuming that you want the popup to be closed when u click on the background
First mistake in your form is not complete and second is there is no input type='image' if you want to display image than you use image tag.
Please follow the code I hope it will be helpful to you:
<div class='addform'>
<form method='GET' action='update_events.php'>
<input type='hidden' name='column1' value="123"/>
<input type='text' name='column2' value="456"/>
<input type='text' name='column3' value="789"/>
<img src='images/update.png' id='update_event' alt='Update Row' class='topopup' onClick='callPopup("1")' title='Update Row'/>
</form>
</div>
Now jQuery code:
$("#update_event").click(function() { alert('sdf'); });
Now instead of alert you can use your ajax call for pop up.

previewing php/jquery form in fancybox, then submit or return to form

I've got a basic html/php form, with jquery validation. I want the user to be able to click a link that says "preview", have fancybox load up, and then I'll present a preview of the data, which means combining elements. For instance, the user can choose the background of the iframe. Here is the basics of my form -
<form action="loggedin.php" enctype="multipart/form-data" id="message_form" method="post">
<h4>Who would you like to send a message to?</h4>
<input type="text" size="35" id="recipient" name="recipient" value="Enter Name">
<h4>Choose A Background: </h4>
<input type="radio" value="plain" class="stationery_radio" name="stationery_radio" checked />
<label for="plain">Plain</label>
.....
And this is the info I want in my fancybox:
<a class="fancybox" href="#preview_message">Click Here To Preview Your Form</a>
<div id="preview_message" style="display:none;">
<h2>To: <?php echo ($message_form['recipient']) ?></h2>
.....
But I can't use the POST, as I haven't really submitted the form yet. How can I sent the data to my fancybox where the user can look at it, and either submit the form or return to edit? Thanks for any help.
What I would do is to create another .php file (e.g. preview.php) where you can (pre)submit the form via ajax. This file would basically echo the POST values of your form fields like $_POST['recipient'], etc.
Additionally, within the same file (preview.php) you may have some links to either submit the actual form or close fancybox.
Here is an example of the preview.php file
<?php
function check_input($data){
// sanitize your inputs here
}
$field_01 = check_input($_POST['field_01']);
$field_02 = check_input($_POST['field_02']);
$field_03 = check_input($_POST['field_03']);
// ... etc
?>
<div style="width: 340px;">
<h3>This is the preview of the form</h3><br />
<p>Field 01 : <?php echo $field_01;?></p>
<p>Field 02 : <?php echo $field_02;?></p>
<p>Field 03 : <?php echo $field_03;?></p>
<a class="submit" href="javascript:;">submit</a>
<a class="closeFB" href="javascript:;">back to edit</a>
</div>
notice style="width: 340px;" so fancybox will know what size of box to display (height would be auto)
Then in your main page, add the preview button
<a class="preview" data-fancybox-type="ajax" href="preview.php">Preview</a>
notice the data-fancybox-type="ajax" attribute, which tells fancybox the type of content.
Then the script to submit (preview) the form via ajax :
jQuery(document).ready(function ($) {
$('.preview').on("click", function (e) {
e.preventDefault();
$.ajax({
type: "POST",
cache: false,
url: this.href, // our preview file (preview.php)
data: $("#message_form").serializeArray(), // all the fields in your form (use the form's ID)
success: function (data) {
// show in fancybox the returned data
$.fancybox(data,{
modal : true, // optional (no close button, etc. see docs.)
afterShow: function(){
// bind click to "submit" and "close" buttons inside preview.php
$(".submit, .closeFB").on("click", function(event){
if( $(event.target).is(".submit") ){
$("#message_form").submit(); // submit the actual form
}
$.fancybox.close(); //close fancybox in any case
}); // on click
} // afterShow
}); // fancybox
} // success
}); // ajax
}); // on click
}); // ready
Of course, the DEMO at http://www.picssel.com/playground/jquery/postPreview_05Jun13.html.
NOTES:
this is for fancybox v2.1.4+
.on() requires jQuery v1.7+
You can use Jquery, to get the values, and put them into the fancy box...
A little like this...not quite, but you get the idea...
$('#preview_button').click(function(){
var msg = $('#recipient').val();
var bg = $('input:radio[name=stationary_radio]:checked').val();
$('h2#recipient').html(msg);
//and whatever you wanna do with the value of the bg
//probably apply some CSS on the fly to change the preview background?
$('#fancybox').show();
});
The fancybox show() is likely wrong, never used fancybox, so I dont know, but Im just using a generic, 'hidden div' show. I assume fancybox has its own API that is different, so just substitute...

Posting a form in a div with menu div seperate

I have a 2 divs one for menu links and the other for content. What I want to be able to do is click a menu link and the page for that menu link to load in the content div.
I have already done this and it works. The problem is that the page inside the div contains a a form which does not come up with the success message and the database does not update.
All it does is either refresh to main content page or opens current window just as the content page or opens a new window with content page.
What solutions are there for this?
Logged_in.php
left div = menu
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".menuLink").click(function(){
$.ajax({
type: "POST",
url: $(this).attr('href'),
data: "",
cache: false,
success: function(html){ $("#Middle").html(html); }
});
});
});
</script>
</head>
<body>
<div id="head">
<div class="lefttop" align="center">
<div class="lefttopleft">
<a class="menuLink" href="Test.php" onclick="return false;"><img src="Images/logo.jpg" width="94" height="21" /></div>
When click on that link the page loads into the content div so now that page is showing with a form on in content div what I am having the trouble with is filling form out clicking submit and it updatung the database it just refreshes to main content div or just page loads the the file click on or does so in new window.
Test.php in content div
session_start();
include_once("connect.php");
include_once("functions.php");
if($_POST['WallSubmit'] && $_POST['Wall']){
$wall = makesafe($_POST['Wall']);
mysql_query("INSERT INTO `Wall` (`ID`, `Username`, `MessageBy`, `Date`, `Message`) VALUES ('', '', '$username', '" . time() . "', '$wall')");
}
?>
<body>
<form method="post">
<table class="default" style="width: 80%" align="center">
<tr>
<td class="subheader">Wall</td>
</tr>
<tr>
<td class="content">Post a comment.<br /><textarea name='Wall' id='Wall' style='width: 99%; height: 110px;'></textarea><br /><br/><center><input type='submit' value='Post' name='WallSubmit' /></center><br /><hr><br />Latest Comments.</td>
</tr>
</td>
</table>
</form>
</body>
</html>
Is there an easy way round this I have looked everywhere?
First off, try to set an action on your form tag. The action defines the page, to which the form will be submitted.
<form method="post" action="Test.php">
With this the form should get submitted to Test.php. If it still doesn't do anything, try to print a variable dump (manual) with var_dump($POST); on top of the page. You will then see all set values of the post attributes. From there on it should be easy to find the error.
EDIT
After your comment I realized that you are trying to send the form with AJAX and just reload the content div. You have to do this in two steps. First, send the data of the form to Test.php, and then reload the content div. If stumbled upon this question: jQuery AJAX submit form. This may help you how to submit your form. If you want to use a return value, you can try something like this:
$.post("Test.php", $("#form").serialize(),
function(data) {
alert("Returned data: " + data);
});
See jQuery.post()

How to display content within modal window?

I have a simple application here (QandATable2.php) where when the user clicks on the plus button, it will open a modal window and it displays the details which is stored in another page (previousquestions.php).
Now the problem I have is that if you straight away click on the "Search" button when the textbox is blank, you will see that it loads the page on its own page, displaying the message to enter in a phrase for the search and it also displays all of the features previously from the modal window into that page as well. This is incorrect.
What I want it to do is that if the user has clicked on the search button, then when it post's the form and outputs the message, it does it within the modal window, not on its own whole page. So does anyone know how this can be acheived?
The modal window I am using is known as SimpleModal and it's website is here
Below is the QandATable2.php code where it displays the plus button and where it opens the modal window, linking the content of the modal window to the previousquestions.php page:
<script type="text/javascript">
function plusbutton()
{
$.modal( $('<div />').load('previousquestions.php #previouslink') );
return false;
}
</script>
<h1>CREATING QUESTIONS AND ANSWERS</h1>
<table id="plus" align="center">
<tr>
<th>
<a onclick="return plusbutton();">
<img src="Images/plussign.jpg" width="30" height="30" alt="Look Up Previous Question" class="plusimage"/>
</a>
<span id="plussignmsg">(Click Plus Sign to look <br/> up Previous Questions)</span>
</th>
</tr>
</table>
Below is the previousquestions.php code, where it displays the details in the modal window and where the search feature is stored:
<?php
foreach (array('questioncontent') as $varname) {
$questioncontent = (isset($_POST[$varname])) ? $_POST[$varname] : '';
}
?>
<div id="previouslink">
<button type="button" id="close" onclick="return closewindow();">Close</button>
<h1>PREVIOUS QUESTIONS</h1>
<p>Search for a previous question by entering in a phrase in the search box below and submitting the phrase</p>
<form action="previousquestions.php" method="post">
<p>Search: <input type="text" name="questioncontent" value="<?php echo $questioncontent; ?>" /></p>
<p><input id="searchquestion" name="searchQuestion" type="submit" value="Search" /></p>
</form>
</div>
<?php
//...connected to DB
if (isset($_POST['searchQuestion'])) {
$questionquery = "SELECT QuestionContent FROM Question
WHERE(QuestionContent = '".mysql_real_escape_string($questioncontent)."')";
if (empty($questioncontent)){
echo "Please enter in a phrase in the text box in able to search for a question";
}
?>
You'll probably want to use AJAX, since you're already using jQuery you'll just need something like this:
// override the "default" form submitting behavior with a callback function
$("form").submit(
// this is the callback function for your form submit function.
function(e)
{
// this prevents the page from reloading -- very important!
e.preventDefault();
// get the search data from the input textbox
var s = $("input[name='questioncontent']").val();
// see annotation
$("#simplemodal-data").html("loading...")
.load("previousquestions.php #previouslink",
{
questioncontent : s,
searchQuestion : "Search"
}
);
}); // end submit wrapper
This will send the value to the server and load it in the div with id simplemodal-data
Annotation:
The last line in the code does several things. First, it replaces the simplemodal DIV with a "loading" message. At the same time, it makes a POST request to your previousquestions.php page. This part { questioncontent : s, searchQuestion : "Search"} is where the data from the form gets passed to the PHP page, (remember the variable var s assignment above. Lastly, the results from the previousquestions.php page should be loaded in the simplemodal-data modal window.
One thing that's missing is to add #previousquestions in the load method so that only a portion of your HTML document gets inserted in the modal. It's never a good idea to load an entire HTML page inside another HTML document, and "load" is designed to allow you to just pick the part of the document you want to insert, which is just that DIV.
I added "#previouslink" after the php filename. This is where the magic happens. The browser knows to extract that DIV from your PHP file and insert just that part on the page, no <head> <body> or any of the unneeded markup.
You can achieve what you're looking for by using AJAX to submit the form instead of using the default behavior where the page reloads with the new content. You can't use modal.load because you need to POST data in the request in order to get the appropriate response.
However, when using AJAX to post your data, you can take the response as HTML and add that HTML to a DIV on your page, and then invoke the SimpleModal command on that DIV container.
First, modify the submit button on your form so that it's type="button" instead of type="submit". This will prevent the form from submitting and redirecting the page. Alternatively, you could add event.preventDefault(); and return false to the form submit click handler (see the second step), but it's probably easier to try this method while you're making the changes:
Step 1:
<!-- change type to button -->
<input id="searchquestion" name="searchQuestion" type="button" value="Search" />
Step 2:
Create a handler for the form button, which uses serializeArray to serialize the form into a string and then POST it to the server. In the success callback handler, you'll then take the HTML response and replace the content in the modal window with the new HTML. This also catches errors, if any, and alerts them and writes them to the console:
$('form[type="button"]').click(function() {
var dataString = $('form').serializeArray();
$.ajax({
url: "/previousquestions.php?t="+new Date().getTime(),
type: "POST",
data: dataString,
context: document.body,
success: function(data){
alert(data); // results from server, either the HTML page, or JSON/XML
$('simplemodal-data').html(data); // if HTML, just insert into div#results
},
error: function(jqXHR, textStatus, errorThrown) {
if(window.location.hostname == "localhost") {
alert("Error submitting the form :: " + textStatus + " : " + errorThrown);
}
console.error("Error submitting the form :: " + textStatus + " : " + errorThrown);
}
});
});
Step 3:
Lastly, be sure that your previousquestions.php code returns only a partial HTML document, not a full HTML document. Since you're injecting HTML into an existing page, you don't need the <html>, <head>, or <body> sections. These will just cause your page to not validate, and may cause undesired behavior in legacy browsers. Here is an example of what your response might look like:
<div id="previouslink">
<button type="button" id="close" onclick="return closewindow();">Close</button>
<h1>PREVIOUS QUESTIONS</h1>
<p>Search for a previous question by entering in a phrase in the search box below and submitting the phrase</p>
<form action="previousquestions.php" method="post">
<p>Search: <input type="text" name="questioncontent" value="test" /></p>
<p><input id="searchquestion" name="searchQuestion" type="submit" value="Search" /></p>
</form>
</div>
<p>
Your Search: 'test' </p>
<p>Number of Questions Shown from the Search: <strong>0</strong></p><p>Sorry, No Questions were found from this Search</p>
I have found out from an answer on another page to a similar question to this that like Bergi has stated, it is easier using an iframe than using ajax to keep content displayed within a modal window. So the best answer for this question is below where it shows how an iframe is used for the question above:
function plusbutton() {
// Display an external page using an iframe
var src = "previousquestions.php";
$.modal('<iframe src="' + src + '" style="border:0;width:100%;height:100%;">');
return false;
}

Categories