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;
}
Related
I'm having some trouble with Jquery as of late. I wanted to get a little more skillful with it and create a login form using Jquerys $.post method but I've hit a little snag.
For some reason When I click the button to submit, the data I want to post instead gets put into the URL of the current page I'm in. Furthermore, the Jquery will only work when this data is in the url.
I don't want to show the website visitors their username and password in the url. Why isn't it just posting the data as intended?
EDIT: IT seems even with all the changes i've made, I still need to submit the form twice for it to actually log me in.
// WHERE MY REQUEST IS MADE AND SENT
<script>
$( document ).ready(function() {
$( "#loginbtn" ).click(function() {
var u = $("#loginform input:text" ).val();
var p = $("#loginform input:password" ).val();
$.post( "http://www.gameandshame.com/auth/login.php", { username: u, password: p}).done(function( data ) {
//alert("Data Loaded: " + data);
location.href = "http://www.gameandshame.com/";
});
});
});
</script>
//DATA POSTED TO HERE
<?php
session_start();
include_once("".$_SERVER['DOCUMENT_ROOT']."/auth/class_loader.php");
echo "STARTING LOGIN";
$login = new login();
$login = $login->startLogin($_POST['username'],$_POST['password']);
?>
//END OF MY STARTLOGIN FUNCTION
$_SESSION['t'] = $t;
$_SESSION['u'] = $u;
echo "SUCCESS";
return;
// The Login Form
<form method="post" id="loginform">
<table>
<tr>
<td><input name="username" type="text" maxlength="24" placeholder="Username"></td>
</tr>
<tr>
<td><input name="password" type="password" maxlength="24" placeholder="Password"></td>
</tr>
<tr>
<td><input id="loginbtn" type="submit" name="submit" value="Go!" /></td>
</tr>
</table>
</form>
I'm honestly at a miss as to why it would stick the arguments in the URL. there seems to be no logical reason for it, even more .
NOTE: The "STARTING LOGIN" only gets returned when I try to login and all the form data is in the url. The login script isn't even ran if there is no data in the url. very weird... :S
I see two problems.
[NO LONGER VALID AFTER FULL CODE ADDED BY POSTER] Check your javascript console. None of your javascript is getting executed because you're msising a }); to close your .click.
[HTML CODE ADDED BY POSTER, STILL VALID POINT BUT NOT THE SOURCE OF ERROR] Without your html, I'm talking a guess here. But I see a problem with the absence of e.preventDefault() in your click event. If your button is type="submit", your form will submit normally.
Wrap everything in
$(document).ready(function(){ [ALL YOUR JS CODE ] });
Otherwise jQuery tries to attach your click event before the DOM is fully loaded.
I found the problem.
In my form i had
<input id="loginbtn" type="submit" name="submit" value="Go!" />
when what I really needed to do was take out the submit from the button, and just grab the form details on-click. Because this type="submit" was still in there, it was posting the form normally, then attempting to post again from the JS, and as a result completely screwed up the ajax request.
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...
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
putting html inside an iframe (using javascript)
I'm using the following code and what I want to do essentially (I'm new to jquery) is submit this form, but then have what is normally outputted on the uploadpic.php page - appear on this page where the form is, in an iframe. I just can't work out how to do it. I added the Jquery Form Plugin - http://www.malsup.com/jquery/form/
So I've gone through the code and commented what it does now. But I've no idea how to add that iframe exchange. Basically the uploadpic.php does this:
$add_one = $membership->add_photo($_POST['photo'], $_POST['caption']);
And if it is all submitted successfully, or if it is a failure, it echos either "sorry your file wasn't uploaded" or "file was uploaded successfully.
How would I stop from having to go to a new page, or resorting to an irritating popup? I thought a temporary iframe would be a good idea - but simply no idea how to implement such a thing.
<div id="uploadform">
<form id = "uploadpicform" enctype="multipart/form-data" action="uploadpic.php" method="POST">
<p>Photo: </p><input type="file" name="photo"><br />
<p>Caption:</p> My <input type="text" name="caption"><br />
<input type="submit" class="large blue button" value="Add">
</form>
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#uploadpicform').ajaxForm(function() {
$("#hideuploadbutton").hide();
$("#uploadbutton").show();
$("#uploadform").hide();
});
});
</script>
</div>
What that does at the moment, is submits the form, with no notice, hides the upload button and shows an open upload button to start the process again. I figure there must be some sort of 'add iframe' or 'print php variable from the other page' option or something.
I'd appreciate any help, thanks a bunch!
EDITED Added code for populating iframe
HTML
<form id="uploadpicform">
<p>Photo:</p>
<input type="file" name="photo"><br />
<p>Caption:</p>
<input type="text" name="caption"><br />
</form>
<div id="uploadpicbutton" class="bluebutton">Upload</div>
JQuery
// **ADDED** Populate the iframe
function iframeresults() {
var content = phpresults;
var tFrame = document.getElementById("iframeid");
var doc = tFrame.contentDocument;
if (doc == undefined || doc == null)
doc = tFrame.contentWindow.document;
doc.open();
doc.write(content);
doc.close();
}
//Submit Upload Ajax Call Function
function submit_upload() {
$('#status').html('Uploading, Please Wait').fadeIn(500);
$.ajax({
type: "POST",
url: "/uploadpic.php",
cache: false,
data: $('#uploadpicform').serialize(), //This adds the variable name and input values automatically
dataType: "script", // Returns Javascript outputted from PHP page and Launches the Script
success: function(){
iframeresults();
});
}
// Bind the upload function to the button
$('#uploadpicbutton').on('click', submit_upload);
PHP
//Use this echo in your PHP after your PHP Successful validation
echo "var phpresults = 'Upload Succesful'; ";
//Use this echo in your PHP after your PHP Failure validation
echo "var phpresults = 'Upload Failed'; ";
Greetings from some noob trying to learn JQuery,
I am attempting to make it when you type something in a box below a div layer it reloads that layer upon submission of the form with a php get of the text box in the form. Expected behavior is it would reload that box, actual behavior is it don't do anything. Can someone help me out here.... Below is the code.
<div id="currentwxdiv">This is where the new stuff happens
</div>
<form name="changewx" action="/">
<input type="text" id="city">
<input type="submit" name="submit" class="button" id="submit_btn" value="New City" />
</form>
<script>
/* attach a submit handler to the form */
$('form[name="changewx"]').submit(function(event) {
/* get some values from elements on the page: */
var $form = $( this ),
city = $('#city').val()
/* Send the data using post and put the results in a div */
$('#currentwxdiv').load('http://api.mesodiscussion.com/?location=' + city);
return false;
});
</script>
Its giving the Javascript Console Error Error....
"XMLHttpRequest cannot load http://api.mesodiscussion.com/?location=goodjob. Origin http://weatherofoss.com is not allowed by Access-Control-Allow-Origin."
You are using POST method? is impossible to post to an external url because with ajax, the url fails the "Same Origin POlice".
If you use GET method, is possible to do that.
Another solution is to make a proxy. A little script that recive the params and then... using CURL or another thing you have to post to the external URL... finally, you jquery have to do the post thing to the proxy:
For example:
$.ajax({
url: '/proxy.php?location=' + city,
success: function(data) {
$('#currentwxdiv').html(data);
}
});
I do it so:
<div id="currentwxdiv">This is where the new stuff happens
</div>
<form name="changewx" action="/">
<input type="text" id="city">
</form>
<script>
$('#city').keyup(function() {
var city = $('#city').val()
$.ajax({
url: 'http://api.mesodiscussion.com/?location=' + city,
success: function(data) {
$('#currentwxdiv').html(data);
}
});
});
</script>
To help you out, i need to test this.
What's the url address of your html code working ?
http://api.mesodiscussion.com/?location= doesn't work... only list the directory content... maybe that's de problem?
Greatings.
Ok, so I am fairly new to webdeveloping, so probably a silly question:
I have this search form which does autocomplete for fooditems (gets values from a database column) and that works. Now when I press the submit button I want to load a block of code that displays the food-items' calories etc (also in the database on the same row as the food-item).
How can I accomplish such a thing. I kno this is a fairly broad question, but what i am really asking is, how can I make a small part of my website reload when pressing the submit button and using the input given in the text field as a parameter of some kind.
I don't need whole answers, just any tips getting to the right path would be greatly appreciated!
here my code for the input and button:
in head
<script type="text/javascript" src="jquery.js"></script>
<script>
function ok(){
$.post("test.php", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); });
}
</script>
in body:
<form autocomplete="off">
<p>
Food <label>:</label>
<input type="text" name="food" id="food" / >
</p>
<input type="submit" id="submit" value="Submit" onclick="ok()" />
</form>
or:
head:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script>
$("input[type='submit']").bind("click", function (event) {
event.preventDefault(); // Stop a form from submitting
$.post("/path/to/call", { /* data? */ }, function (data) {
// Process return data here
});
});
</script>
body:
<form autocomplete="off">
<p>
Food <label>:</label>
<input type="text" name="food" id="food" / >
</p>
<input type="submit" id="submit" value="Submit" />
</form>
jQuery and Ajax.
Change that input to a button
<button id="submit">Save</button>
For this I would do something like:
$("button#submit]").bind("click", function (event) {
event.preventDefault(); // Stop a form from submitting
$.post("/path/to/call", { /* data? */ }, function (data) {
// Process return data here
});
});
You need to first catch the click event .bind("click"). Then initiate an ajax call $.post which you will send data to. This data is received on the server via the POST array.
Like Josh said, jQuery is the way to go here.
You'll want to do 3 things:
Attach a click handler to a button like "onclick='doSomething();'"
In that function,use jQuery to do an async post to a script like
$.post("test.php", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
When this comes back, you can do something with that data(instead of the alert above), like $('#listnode').append... which would stick the HTML into your list
This is the general pattern, but you'll have to fit it to your scenario.
It is hard to answer your question from what little you have given us, but I will assume little knowledge.
Your input fields have to be inside a form tag. The form tag includes an action and a method. The method must be "POST" to send the data. The action can be any URL.
You simply have to name the URL of your php script that will handle the results.
It will find the data in $_POST['food'] etc. It has to build the reply page - the whole screen, with the food and data and the search form for the next submit if you want.
If you want to use AJAX to replace part of the screen, then you have a whole nother level of problems. The trick is to replace the content of a div tag with the requested data.