<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.
Related
Hi I have been at this for days now and I just cant figure out why this isn't working, please could someone take a look.
index.php
<form id = "update_status" method = "POST">
<textarea id="shadow" name ="user_status" placeholder = "Share what is on your mind!" cols="97" rows="1" title="Share what's on your mind"></textarea>
<input style="float:right; margin-top: 0.3%;margin-right : 0% !important;" id = "btnStatus_update" name = "btnStatus_udate" type="button" value="Add Post" title="Your posts will be made public"></input></form>
swift.php
$(document).ready(function(){
$("#btnStatus_update").click(function(e) {
e.preventDefault();
//alert("Confirming function works");
$.ajax({
cache: false,
type: 'POST',
url: './datacenter.php',
data: $("#user_status"),
success: function(d) {
$("#successMesg").html(d);
}
});
});
});
datacenter.php
if (isset($_POST['user_status'])) {
var_dump($_POST['user_status']);
foreach ($_POST as $ak => $av) {
if (empty(trim($_POST['user_status']))) {
echo 'Say what is on your mind'.' ';
} else {
$userstatus = $_POST['user_status'];
add_user_status($user_data['id'], $userstatus);
}
}
}
using var_dump for testing I was hoping it did return the data, but instead i get NULL, i need the data so i can pass it into the add_user_status function to be added to the database, but it seems there is something missing or off about the code denying me my satisfaction. Please help
There are a few things that appear to be missing:
Index.php:
You need to add an action="something" attribute to the form tag, this tells the form what to do when you submit it. (unless you are manually handling this is JS somewhere else?)
<form id = "update_status" action ="data.php" method = "POST">
Also, unless you are using JavaScript on the index page to handle the actual submitting of the form, your <input> should include a type="submit" attribute. (this will also make it a button) and when clicked it will automatically submit the form to the action location above.
Swift.php:
the code posted is JS, and does what the first line of the previous paragraph mentioned (handles the submit button). Do you include this file inside the index.php? if the index.php cannot see it, then it wont run. It must also be in the html somewhere in a proper <script> block.
I believe the correct way to send form data using ajax is to serialize the data:
$('#update_status').serialize() instead of just sending the one input field.
You will also be required to reference the jQuery libraries, preferably in the index, but could also go in swift.php. I am also assuming that the code posted appears in the necessary <script> block.
Data.php:
should this be datacenter.php? your Swift.php is sending the ajax request to ./datacenter.php
On a side note, if you need it to use Ajax then you actually don't need the action ="data.php" method = "POST" in the form (Ajax does all that for you)
The way it could be done would be something like this:
Index.php:
// HTML beginning stuff
<head>
// Either reference the script in its own JS file or:
// Need to also include jquery library
<script type="text/javascript">
$(document).ready(function(){
$("#btnStatus_update").click(function(e) {
e.preventDefault();
//alert("Confirming function works");
$.ajax({
cache: false,
type: 'POST',
url: './datacenter.php',
data: $('#update_status').serialize(),
success: function(d) {
$("#successMesg").html(d);
}
});
});
});
</script>
</head>
<body>
<form id = "update_status">
<textarea id="shadow" name ="user_status" placeholder = "Share what is on your mind!" cols="97" rows="1" title="Share what's on your mind"></textarea>
<input style="float:right; margin-top: 0.3%;margin-right : 0% !important;" id = "btnStatus_update" name = "btnStatus_udate" type="button" value="Add Post" title="Your posts will be made public"></input>
</form>
</body>
datacenter.php:
<?php
var UserStatus = user_status
if (!empty(UserStatus)) {
var_dump($_POST['user_status']);
// process as necessary
}
?>
But, including the
<form id = "update_status" action ="datacenter.php" method = "POST">
and changing the button to
<input style="float:right; margin-top: 0.3%;margin-right : 0% !important;" id = "btnStatus_update" name = "btnStatus_udate" type="submit" value="Add Post" title="Your posts will be made public">
will allow users to still post information if they have JavaScript disabled.
the selector for the textarea is incorrect, the id is not "user_status", its "shadow"
data: $("#user_status"),
should really be:
data: $("textarea[name=user_status]")
or
data: $("#shadow")
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();
......
The problem that we have is describing as follows. We have two different pages, the first one is called profile.php and the second one is called save_button.php. In the page profile.php I have this script which is written the following code in jQuery:
<script >
$(function(){
$("#save").bind('click', function(){
document.getElementById('save').style.background='#F26522';
document.getElementById('modify').style.background='#0083A9';
$.ajax({
url: 'save_button.php',
type: 'post',
data: { "callFunc1": "test"},
success: function(response) { alert(response); }
});
})
});
</script>
In the body of profile.php page we have written this code, here we have two different buttons:
<body>
<div class="button_container" >
<input id="modify" type="button" class="buttons" value="Modify" onclick="changeText();" />
<button id="save" class="buttons" >Save</button>
</div>
</body>
When we click the save button we want to execute the PHP code in another page, called save_button.php. Inside this page, save_button.php, we have written the following code:
<?php echo "test works"; ?>
What happens with us is that when we click the save button, in our page is not alerted the words "test works". Do you have any idea what to do in this page? Please, give us a quick feedback as this is a school project and we have to submit within the three next days. Many thanks.
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()
I have an HTML form in a PHP file like the attached snippet:
When I hit the "Save Details" button, I want the page to load a jQuery UI modal dialog. That dialog will execute a controller action (ex:savedetails) through Ajax.
Essentially, the controller action will get all the POST details in "frmEmployees" and saves the changes to a database through Ajax.
I am interested in the logic to load the dialog with the Ajax content in it (Get all the POST variables through the controller action, say "/public/empdetailcontroller" via Ajax). So, far I have something like the HTML below.
Any Ideas?
Snippet:
<form name="frmEmployees" id="frmEmployees" method="POST" action="">
<table>
<tr><td>Name:</td><td><input type="text" name="empName" size="50"></td></tr>
<tr><td>City:</td><td><input type="text" name="empCity" size="50"></td></tr>
<tr><td>Country:</td><td><input type="text" name="empCountry" size="50"></td></tr>
<tr><td colspan=2 align=center><input type="button" name="btnsubmit" value="Save Details"></td></tr>
</table>
</form>
<div id="dialogSaveChanges"
title="Saving.."
style="display:none;"><p><span
class="ui-icon
ui-icon-info"
style="float:left; margin:0 7px 20px 0;"
></span><span id="dialogText-savechanges"></span></p></div>
<script language="JavaScript>
$(document).ready(function() {
$('#dialogSaveChanges').dialog({
autoOpen: false,
width: 400,
modal: true,
title: titleText,
closeOnEscape: false,
open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); },
resizable: false,
buttons: {
Ok: function() {
$(this).dialog('close');
}
}
});
$('#btnSaveChanges').click(function() {
$('#dialogSaveChanges').dialog('open');
$("span#dialogText-savechanges").html("Your Changes have been saved successfully.");
});
});
</script>
You'll need to submit the form in order for the form values to be sent. The logic will follow something like this:
Bind function (e.g., submitForm) to form's submit event, returning false to prevent normal (non-AJAX) form submission.
submitForm function makes $.ajax call.
AJAX call is configured to open the dialog before the the request is sent (event: beforeSend).
Dialog box is populated with "Loading..." text/image.
On success or failure of the ajax call (events: success/failure), the dialog box is populated with the results or an error message.
Code might look like:
$('#frmEmployees').submit( function() {
$.ajax({
url: this.attr('action'), // Make sure your form's action URL is correct.
method: 'POST',
data: this.serialize(), // this = $('#frmEmployees')
// Add hidden form inputs to send any control
// parameters to your server script.
beforeSend: openDialogFunction,
success: handleFormSuccess,
failure: handleFormFailure
});
return false; // prevent normal form submission.
});
If you program it like this, your page will also work without javascript, it just won't have the dialog box.
Not sure I completely understand what you are trying to do, but let me try...
So, you want to:
Send form details to a controller via AJAX.
Save the form data to the DB from the controller.
On success, show a dialog box with a "Success" message and the saved items.
On error (you didn't mention this), I assume you would display an alternate method, correct?
Look into the jQuery Ajax methods.