I have a div with a form in it. After a user submits the form, I want to load new content into the div, replacing the form.
The new content will be static.
Do I need AJAX for this?
you don't HAVE to use ajax for this, after submitting the form you can issue a redirect to a static page without the form(post-redirect-get pattern).
But note that in this case the entire page will refresh while submitting,
and if the submit might fail from some reason(who said validation), hitting F5 will pop up the ugly "do you want to send crap..."
so no, you don't have to use ajax, but it is so easy with the form plugin that it is a crime not to.
if you do use the form plugin, then at the success callback hide the form with the static content
You do need Ajax: (I'll do it like SimpleCoder said, but with the ajax call)
$('#myForm').submit(function(){
var field1 = $("#field1").serialize(); // If this doesn't work just remove the serialize()
var field2 = $("#field2").serialize();
$.ajax({
type: "POST",
url : "???", //your processing page URL instead of ???
data: "&field1="+field1+"&field2="+field2,
success: function(){
$("#formHolder").html("Your static content");
}
});
});
( You should replace field1, field2 with your fields, and if it doesn't work, remove the serialize() function. )
All you have to do is .html() the static content in the success function of the ajax call.
Assuming your HTML looks something like this:
<div id="formHolder">
<form id="myForm">
...
</form>
</div>
Do something like this:
$("#myForm").submit(function(){
$("#formHolder").html("Your static content");
});
You can find an example of this here
https://www.write-about-property.com/seo-services/ the code to work on the form submit uses an instance of the object created in form.js
If you have a crack at it then come back we will help you perfect it for your purpose. You would put the div you wanted to update in the toupdate var
ajform.toupdate = $("#update")
you can simply make the divs invisible, and the submit button is just a button with js action to make the div visible
<script type="text/javascript" language="javascript">
function step2() {
document.getElementById('step1_container').style.display = 'none';
document.getElementById('step2_container').style.display = 'block';
}
function step3() {
document.getElementById('step2_container').style.display = 'none';
document.getElementById('step3_container').style.display = 'block';
}
</script>
...
<form action="validate.php" method="post">
<div id="step1_container">
PAGE 1 here
<input type="button" onclick="javascript:step2();" value="submit"/>
</div>
<div id="step2_container" style="display: none;">
Page 2 here
<input type="button" onclick="javascript:step3();" value="submit"/>
</div>
<div id="step3_container" style="display: none;">
Page 3 here
<input type="button" onclick="javascript:step4();" value="submit"/>
</div>
</form>
And so on
You don't need ajax, using only on-page javascript would be enough.
However, with ajax you can display the content from the page you're submitting the form to.
Try the jQuery From plugin for an elegant ajax solution:
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#myForm').ajaxForm({
target: '#divToUpdate',
url: 'comment.php',
success: function() {
alert('Thanks for your comment!');
}
});
});
</script>
Related
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();
......
I'm trying to change the content of div using jquery. but the content flashes and resets the div. i cannot use return false; because there is another button for post text field value. i want to keep the changes of div. here is my code:
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div>
<form id="form" method="POST">
<input type="text" name="gname" id="gname"/></br>
<button id="btn">Set</button>
<button id="nbtn">View</button>
</form>
</div>
<div id="outp">
</div>
</body>
<script>
$("#btn").click(function(event) {
$.post("send.php", {
named: $("#gname").val()}, function(data) {
alert(data);
});
});
</script>
<script>
$("#nbtn").click(function(e) {
$("#outp").html("<?php include './view.php'; ?>");
});
</script>
It's not jQuery; it's that your form is being posted. So your change is made, but then the form is posted and the page is refreshed from the server.
The default type of button elements is "submit". To make one or both of those buttons just a button, use type="button".
Alternately, if you want to allow the form to be used when JavaScript is disabled (e.g., allow it to be posted normally), leave the buttons as submit buttons but prevent form submission using JavaScript. E.g.:
$("#form").submit(false); // Prevents the form being submitted in the normal way.
Any buttons inside a form are considered submit buttons.
So you need to add event.preventDefault() to your .click code.
Also, why are your scripts outside body section?
You can try with ajax and catch success and error:
$("#btn").click(function() {
var named: $("#gname").val();
$.ajax({
url: 'send.php',
type: 'POST',
data: {param1: 'value1'},
})
.done(function(data) {
console.log("Post success"+data);
})
.fail(function() {
console.log("Post error"+data);
});
});
Because of my web style, i don't want to use input & textarea and get information by using $_POST[] and i need to get information that is in DIV element.
For example , I want to get information in this :
<div class="mine" name"myname">
this is information that i want to get and put into database by PHP !
</div>
and :
$_POST[myname];
But i can't do it with $_POST , How can i do it ??
And if this method can't do this , do you know any other method to get information from DIV like this ?
you can call a onsubmit function and make a hidden field at the time of form submission like this
HTML
need to give a id to your form id="my_form"
<form action="submit.php" method="post" id="my_form">
<div class="mine" name"myname">
this is information that i want to get and put into database by PHP !
</div>
<input type="submit" value="submit" name="submit" />
</form>
Jquery call on submit the form
$(document).ready(function(){
$("#my_form").on("submit", function () {
var hvalue = $('.mine').text();
$(this).append("<input type='hidden' name='myname' value=' " + hvalue + " '/>");
});
});
PHP : submit.php
echo $_POST['myname'];
You can use this method. First, with javascript get content of <div>
Code:
<script type="text/javascript">
var MyDiv1 = Document.getElementById('DIV1');
</script>
<body>
<div id="DIV1">
//Some content goes here.
</div>
</body>
And with ajax send this var to page with get or post method.
You would need some JavaScript to make that work, e.g. using jQuery:
$.post('http://example.org/script.php', {
myname: $('.mine').text()
});
It submits text found inside your <div> to a script of your choosing.
You can use following structure;
JS:
$(document).ready(function() {
$("#send").on("click", function() {
$.ajax({
url: "your_url",
method: "POST",
data: "myname=" + $(".mine").text(),
success: function(response) {
//handle response
}
})
})
})
HTML:
<div class="mine" name"myname">
this is information that i want to get and put into database by PHP !
</div>
<input type="button" name="send" id="send" value="Send"/>
You can see a simulation here: http://jsfiddle.net/cubuzoa/2scaJ/
Do this in jquery
$('.mine').text();
and post data using ajax.
Put the content of DIV in a variable like below:
var x = document.getElementById('idname').innerHTML;
This site has been really helpful while writing this program. Unfortunately, I hit a snag at some point, and have boiled the problem down quite a bit since. At this point, I am looking at three files, a .html that contains a form, a .js that contains my event handlers, and a .php that receives my post variables and contains new content for the form.
I am getting the post data from the initial text input just fine. The new form content is set as I would expect. However, after this form content is set to a new input of type button with a class of button, the post method in my button class handler is not setting post data on login.php as I expect it to.
Here is my code:
Contents of interface.html page:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<form id="interface" action="login.php" method="post">
<input type="text" value="enter username here" name="user"/>
<button id="submit">submit</button>
</form>
<script src='events.js'></script>
</body>
</html>
Contents of events.js file:
$("#submit").click(function(){
$.post(
$("#interface").attr("action"),
$(":input").serialize(),
function(info){$("#interface").html(info);}
);
});
$(".button").click(function(){
var $this=$(this);
$.post(
$("#interface").attr("action"),
{data:$this.val()},
function(info){$("#interface").html(info);}
);
});
$("#interface").submit(function(){
return false;
});
Contents of login.php file:
<?php
if(isset($_POST['user'])){
echo '<input type="button" class="button" value="set data"/>';
}else if(isset($_POST['data'])){
echo 'data is set';
}
?>
You need to wait until the button exists to bind an event to it. Additionally, i'd switch from click to submit and drop the click event binding on .button completely.
//$("#submit").click(function () {
$("#interface").submit(function (e) {
e.preventDefault();
var $form = $(this), data = $form.serialize();
if ($form.find(".button").length && $form.find(".button").val() ) {
data = {data: $form.find(".button").val()};
}
$.post($form.attr("action"), data, function (info) {
$form.html(info);
});
});
//$("#interface").submit(function () {
// return false;
//});
Since the form is not being replaced, and the event is on the form, you no longer need to re-bind anything.
I wrote an array to pass variables in the GET to a search page. The search page only has 4 fields but I'm only passing the most important variables, first name and last. Here is the array:
<?php echo "<td><a href='" . matry::base_to('test/trace', array('first'=>$patient->first , 'last' =>$patient->last)) . "'><ul class='controls'>
<li id='check_orders'><`span class='symbols'>L</span><span class='label'>Skip Trace</span></li>
</ul></a></td>";?>
When the page loads i'm just echoing the _GET to pre populate the first and last input fields on that page..
What I'm looking for is a script that will execute the search with the first and last name fields populated as that page loads automatically. Additionally, when the search is executed it's populating in an iframe. (forgot about that part)~!
I tried using:
<script>document.getElementById('stack').submit();</script>
<form action='http://xxxx.yyyyyyy.com/stuffhere' name='es' target="my_iframe" id="stack">
with no avail.
Your <script> is running before the <form> exists.
Move the <script> below the <form>.
You are calling the submit function before the form is even loaded on the page.
Place the script tag after the closing form tag or call submit on document ready or window onload.
<form id-"stack">
... form fields...
</form>
<script>document.getElementById('stack').submit();</script>
or
<script>$(function(){$('#stack').submit();})</script>
Please imagine this simple example:
<html>
<head>
<script type="text/javascript">
function body_onload() {
var form = document.getElementById('theform');
form.submit();
}
</script>
</head>
<body onload="body_onload()">
<form id="theform" action="action.php">
<input type="hidden" name="query" id="query" value="foo" />
</form>
</body>
</html>
It will submit the form after the page has loaded.
But are you really searching for a non AJAX solution?
Try this, been using this on a redirect page for a while. This of course needs to be below the from so it is run after the browser process the form.
<script type="text/javascript">
function send(o)
{
var f = document.getElementById("theForm");
f.submit();
}
send();
</script>
If you want to submit the form when the page loads you should change your code to this:
<script>window.onload = function(){ document.getElementById('stack').submit(); }</script>
However this will redirect the user (as if they have clicked a form submit button). To avoid this you will need to use AJAX (I recommend using jQuery to do this). See example below:
$(document).ready(function(e) {
var form_data = $("#form_id").serialize();
var form_url = $("#form_id").attr("action");
var form_method = $("#form_id").attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false
});
});
See this page for more info on using AJAX