Posting a form in a div with menu div seperate - php

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()

Related

jQuery submits the wrong html form

I have a php script that fetches items from database and allows users to vote for them, I give each one of those fetched items a (html form) with one (input text field) and a (submit button) to submit an entered score when clicked, and I have a jQuery script in the very same page that inserts the score via that form to the database without refreshing the page, everything seems to be working just fine except the script has one.
This script allows only the very first (html form) in the loop to submit and this first (html form) affects item that does not follow it in the loop, how to make every form attributed to its item?
Alongside this I also want the script to return a notification for the user who submits the score to inform them whether the data is successfully inserted or failed and when success I want to the score that the user submitted to appear for them after the submission
Any help is appreciated, here is my code:
<body>
<div id="items-wrapper">
<?php //function where i fetch items/records from database $items=g et_items_function($page_id); if(!$items){ echo 'There are no items in this page yet!'; }else{ ?>
<div id="item">
<?php //looping the fetched items/records foreach($items as $item){ $_itemid=$ item[ 'item_id']; $_name=$ item[ 'item_name']; $item_file='path/to/items/name-' .$_name. '-id-'.$_itemid. '.jpg'; ?>
<ul id="responds">
<!--i want to append data here-->
</ul>
<img src="<?php echo $item_file; ?>" />
<form action="setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>" method="POST">
<input type="text" name="content_txt" id="contentText" placeholder="Enter score" />
<button id="FormSubmit">Add Score</button>
<img src="images/loading.gif" id="LoadingImage" style="display:none" />
</form>
<?php } ?>
</div>
<?php } ?>
</div>
<script type="text/javascript">
$(document).ready(function() {
//Ajax request to setItemScore.php
$("#FormSubmit").click(function(e) {
e.preventDefault();
if ($("#contentText").val() === '') {
alert("Please enter some text!");
return false;
}
$("#FormSubmit").hide();
$("#LoadingImage").show();
var myData = 'score_value=' + $("#contentText").val();
jQuery.ajax({
type: "POST",
url: "setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>",
dataType: "text",
data: myData,
success: function(response) {
$("#responds").append(response);
$("#contentText").val('');
$("#FormSubmit").show();
$("#LoadingImage").hide();
},
error: function(xhr, ajaxOptions, thrownError) {
$("#FormSubmit").show();
$("#LoadingImage").hide();
alert(thrownError);
}
});
});
});
</script>
</body>
Issue #1
You should always use the .submit() method when a form is being submitted rather than the submit button onclick() for two reasons. 1) When using inputs you can hit enter and submit the form bypassing the entire method. 2) .submit() uses the form allowing you to get children items for that form.
With that in mind I would add a class name to the forms that you know are being submitted through ajax like:
<form class="ajax-form" action="setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>" method="POST">
...
</form>
Then instead of using .onclick() you can use:
$('.ajax-form').submit(function(e){
...
});
Issue #2
In your AJAX request you are using the following line:
url: "setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>",
This is always going to set $_itemid to the last iteration from your above foreach() loop instead of the action from the form.
If you use the method mentioned above in issue #1 then you could simply use the forms action property:
url: $(this).prop('action')
Whereas $(this) is the form.

Form submit supposed to refresh only Div, but instead refreshes Page

I have a PHP page included called 'leaguestatus.php'. This page allows the user to post a message/status update and the intent is to have only this part of the div refreshed; however, on submit, the entire page is reloaded.
In the current implementation I'm simply printing all the $_POST variables to the div so I can see what's coming through. The MsgText textarea DOES get posted, however, it's only after the whole page loads. I'm trying to get just the div and that included file to reload.
div id="statusupdates"><? include 'leaguestatus.php'; ?></div>
leaguestatus.php
<form id="statusform" method="POST">
<textarea name=MsgText rows=5 cols=40></textarea><BR>
<input type=submit value=Post id=uhsbutton>
</form>
<BR>
<BR>
<div id='formbox'>
<? print "<pre>POST Variables:<BR>";
print_r ($_POST);
print "</pre>";
$MsgText = $_POST["MsgText"];
?>
</div>
The jQuery I'm running in the header is:
$(document).ready(function() {
$("#statusform").submit(function(e) {
e.preventDefault();
var formData=$(this).serialize();
var pUrl="leaguestatus.php";
submitFormSave(formData, pUrl);
});
function submitFormSave(formData, pUrl) {
$.ajax({
url: pUrl,
type: 'POST',
data:formData,
success: function(response) {
$("#formbox").html(response);
}
}).success(function(){
});
}
});
Here are my includes:
html header
<link rel="stylesheet" href="css/jquery-ui.css">
<script src="js/jquery-1.9.1.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
Edit: updated code to reflect use of #sazedul's response. Only issue now is on first click page acts as expected (no page refresh). On second click the entire page reloads. On third click we're back to normal.
Use this following code for ajax submit hope it will work.
$("#statusform").submit(function(e) {
e.preventDefault();
var formData=$(this).serialize();
var pUrl="leaguestatus.php";
submitFormSave(formData, pUrl);
});
function submitFormSave(formData, pUrl)
{
$.ajax({
url: pUrl,
type: 'POST',
data:formData,
success: function(response)
{
$("#formbox").html(response);
}
});
}
Made the following changes in your leaguestatus.php remembar to put double quote in the name="MsgText" in text area.
<form id="statusform" method="POST">
<textarea name="MsgText" rows=5 cols=40></textarea><BR>
<input type=submit value=Post id=uhsbutton>
</form>
<BR>
<BR>
<div id='formbox'>
</div>
<?php
if(isset($_POST['MsgText'])){
$message=$_POST['MsgText'];
echo $message;
}
?>
check for .load() like the code below....
$(document).ready(function() {
$("#statusform").submit(function() {
$("div").load();
});
});
You have to preventDefault of submit then other thing
so,you have to use e.preventDefault() to prevent submit.then do what ever you want
$("#statusform").submit(function(e) {
e.preventDefault();
......

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...

forms to update database in div=content

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="./js/jquery.blockUI.js"></script>
<script>
$(document).ready(function(){
$(".menuLink").click(function(){
$('#content').block({
centerY: 0,
css: { top: '40px', left: '', right: '10px' },
message: '<img src="./Images/ajax_loader.gif" /><br /><h3>Loading...Please wait.</h3>'
});
$.ajax({
type: "POST",
url: $(this).attr('href'),
cache: false,
success: function(html){ $("#content").html(html); }
});
});
$(document).ajaxStop(function(){
$('#content').unblock();
});
});
</script>
This is the code I have for geting links in div id=menu when clicked they load the php file into div id=content ahref I have is here.
<p><a class="menuLink" href="Test.php" onclick="return false;">Wall</a></p>
Now the class and onclick with script above is what makes the Test.php load in div id=content when that link is clicked on div id=menu.
Below is the script in Test.php
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')");
}
<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>
Now the problem I am having is once I have clicked wall on menu as can see in href it loads into div id=content no problem at all so now the Test.php is displayed in content div but now when I fill in that form on Test.php it just refreshes to the default content page and it does not update the database if it doesnt refresh to that default content there then the button does not do anything when click, Now I know the coding works for the database and form as it's been tested in a framed layout and also works if I set Test.php to the default content page, will put default content as I have in page.
<div id="content" class="auto">
<?include_once("Test.php");?>
</div>
What is trhe solution for this? I know it sounds abit confusing but all I want is to figure out once I click Wall on menu and it loads Test.php into div id=content how to get the form in Test.php to do it's job lol.
The action of your form, since not specified, simply refreshes the page and submits WallSubmit and Wall to the main page, rather than to test.php. Instead, you could specify the action like so:
<form action='test.php' id='wallForm' method='post'>
However, this would simply take the user to a blank page with the contents of test.php. Instead, within the javascript, an ajax call must be made:
$(document).ready(function() {
...
$(document).on("submit","#wallForm",function(){
$.ajax({
type: "POST",
url: $(this).attr('action'),
cache: false,
data: {Wall: $("#Wall").val(), wallSubmit: $("[name=WallSubmit]").val()},
success: function(html){ $("#content").html(html); }
});
});
...
});
on() has to be called because the form was loaded after the DOM was. Javascript won't recognize it otherwise, as it only deals with content loaded into the DOM. For more information on this, this site contains some useful information.
If you want to have a generic form submission function, serialize() should probably do the trick. The jQuery API page should summarize this well. You would replace the data: {Wall: ...} with data: $(this).serialize(). This function takes the valid fields in a form and places it into a string that can be used to set data to a php file. However, I'm not quite sure what the effect the WallSubmit name has on the form. From what I can tell, you can eliminate that step altogether.

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