I have a website I'm building and it is set up so that when a link is pressed on the left, the page content is loaded in a div on the right.
<div id="right-column">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
var dataReturn='';
function makeRequest(url){
$('#preloader').show();
$.get(url, function(data) {
$('#resultDiv').html(data);
$('#preloader').hide();
});
}
function makePostRequest(url, params){
$('#preloader').show();
$.post(url,params, function(data){
$('#resultDiv').html(data);
$('#preloader').hide();
});
}
</script>
</head>
<body>
<div id="preloader"></div>
<div id="resultDiv">
<h3>Welcome <?php echo $user_identity;?></h3>
<h5>Message: <?php echo $wpdb->get_var("SELECT message FROM staff_misc");?></h5>
</div>
</div>
Now this works fine for the links loading the content they're supposed to... now my question is. One of the pages has a form with the following code:
<h3>Admin Message</h3>
<form id="message" method="post" action="Admin/message.php">
<input type="text" style="width:700px;" value="Set A New Message" name="admin-message"/>
<input class="submit" type="submit" name="submit" value="Submit">
</form>
<?php
if ( isset ( $_POST['submit'] ) ) //If submit is hit
{
$message = $_POST["admin-message"];
$wpdb->query("UPDATE staff_misc set Message = '$message' where id = '1'");
?><b>New Message Set:</b> <?php echo $wpdb->get_var("SELECT message FROM staff_misc");?><?php
}
If that form is submitted, it refreshes the whole page rather than reloading the content back in to the AJAX div. How do I go about making it so that page loads back in to the AJAX div rather than refreshing the entire page and losing the left column with the links.
You can either capture the submit event on the form, cancel the default action, and redirect it to your own form handler, then submit via AJAX.....or you can change the submit button to a regular button that calls your form handler, then submit via AJAX.
I think it would be something like this:
<script>
$("#message").submit(function() {
// do something...
// this will prevent the event from bubbling and keep the page from refreshing
return false;
});
</script>
You should have a submit handler for that form, and make sure to return false at the end of your function, to stop the default action for the form.
$('#message').on('submit', function() {
$.post('Admin/message.php', $('#message').serialize(), function( html ){
// do something with return message
});
return false;
});
First Page:
<h3>Admin Message</h3>
<form id="message" method="post" action="Admin/message.php">
<input type="text" style="width:700px;" value="Set A New Message" name="admin-message" id="admin-message" />
<input class="submit" type="submit" name="submit" value="Submit">
</form>
<div id="result"></div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
$(".submit").click(function(e){
//Prevent the entire page from refreshig
e.preventDefault();
$.get("ajax.php?admin-message=" + $("#admin-message").val(), function(result){
$("#result").html(result);
});
});
</script>
ajax.php
<?php
if ( isset ( $_POST['submit'] ) ) //If submit is hit
{
$message = $_POST["admin-message"];
$wpdb->query("UPDATE staff_misc set Message = '$message' where id = '1'");
?><b>New Message Set:</b> <?php echo $wpdb->get_var("SELECT message FROM staff_misc");?><?php
}
?>
Related
I have a form. My objective is send and insert the values of the form to my database. Then
Clear the input of the form
Show the successful message.
Like this:
My problems:When I press the "save" button, I am redirected to another page.
This is the operating error:
and change the page
¿What is the problem on my code?
html
<html>
<head><title>Insert Data Into MySQL: jQuery + AJAX + PHP</title></head>
<body>
<form id="myForm" action="userInfo.php" method="post">
Name: <input type="text" name="name" /><br />
Age : <input type="text" name="age" /><br />
<button type="submit" id="sub">Save</button>
</form>
<span id="result"></span>
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/elscript.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js">
</script>
</body>
</html
This is my script
$("#myForm").submit( function(e) {
// Prevent the normal form submission event
e.preventDefault();
// Create an object of the form
var form = $(this);
// Make an AJAX request
$.post(this.action, form.serializeArray(), function(info) {
// Clear the form
form[0].reset();
// Display message
$("#result").html(info);
});
});
Finally, my code to insert
<?php
$conn = mysql_connect('localhost', 'root', '');
$db = mysql_select_db('practicas');
$name = $_POST['name'];
$age = $_POST['age'];
if(mysql_query("INSERT INTO ajaxtabla VALUES('$name', '$age')"))
echo "Successfully Inserted";
else
echo "Insertion Failed";
?>
Thanks for help me
You can simplify the code by having just one event handler for when you submit the form. Additionally, you need to include e.preventDefault() which prevents the normal function of the submit button.
$("#myForm").submit( function(e) {
// Prevent the normal form submission event
e.preventDefault();
// Create an object of the form
var form = $(this);
// Make an AJAX request
$.post(this.action, form.serializeArray(), function(info) {
// Clear the form
form[0].reset();
// Display message
$("#result").html(info);
});
});
Give your button a type attribute as well to ensure your form submits upon clicking.
<button type="submit" id="sub">Save</button>
Demo
$(function() {
$("#myForm").submit(function(e) {
// Prevent the normal form submission event
e.preventDefault();
console.log('onsubmit event handler triggered');
// Create an object of the form
var form = $(this);
// Make an AJAX request
/*$.post(this.action, form.serializeArray(), function(info) {
// Clear the form
form[0].reset();
// Display message
$("#result").html(info);
});*/
// fake AJAX request
setTimeout(function(){
// Clear the form
form[0].reset();
// Display message
$("#result").html('Successfully Inserted');
}, 3000);
});
});
<form id="myForm" action="userInfo.php" method="post">
Name: <input type="text" name="name" /><br /> Age : <input type="text" name="age" /><br />
<button type="submit" id="sub">Save</button>
</form>
<span id="result"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
In ajax you are posting the form with its action so it will be redirected confirm
If you don't want to redirect then send ajax request like this
$.ajax({
method:post,
url:"File name you want to send request"
}).done(function(response){
});
I have an index.php page that I want to receive information from a user in a textArea, and, upon hitting save, the variable should be posted to another page called changePage.inc.php. Once the post variable has been set onto the other page, the changePage.inc.php should redirect away from the original index.php to a page called secondPage.php.
variable in jquery on index.php -> same variable as a post on changePage.inc.php
-> user is redirected off of index.php to secondPage.php, as instructed by changePage.inc.php
File named index.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script>
$(document).ready(function(){
$('#saveForm').submit(function(event){
event.preventDefault();
var message = "";
var changeText = function(){
message = "You wrote: " + $('#text').val();
};
var send = function(){
if(message !== ""){
$.post("includes/changePage.inc.php", {message: message});
window.location.href = "includes/changePage.inc.php";
}
};
changeText();
send();
});
});
</script>
<body>
<textArea id="text"></textArea>
<form id="saveForm" action="includes/changePage.inc.php" method="POST">
<button type="submit" id="saveButton">Save!</button>
</form>
</body>
</html>
File name changePage.inc.php
<?php
session_start();
if(isset($_POST['message'])){
header("Location: ../secondPage.php");
}
exit();
File named secondPage.php
<?php
echo 'Hello World';
?>
With the code as it is right now, it gets to changePage.inc.php, but not secondPage.php. I believe that the post variable is either not being set at all, or being set too late (maybe this is because of a race condition).
I have asked this question before and thought that an answer using function(data) within the $.post() method to create an object with $.parseJSON(data) was going to work. But upon running the code, errors were generated, so now I am asking it again. This is the previous attempt: POST variable from jquery redirecting but is not set
Redirect to secondPage.php in the Javascript, not PHP. And do it in the callback function of $.post so it waits for the script to complete.
var send = function(){
if(message !== ""){
$.post("includes/changePage.inc.php", {message: message}, function() {
window.location.href = "includes/secondPage.php";
});
}
};
But much simpler would be to just add message as an input in the form, and let the form submit normally.
$("#saveForm").submit(function() {
$("#message").val("You wrote: " + $("#text").val());
}
<textArea id="text"></textArea>
<form id="saveForm" action="includes/changePage.inc.php" method="POST">
<input type="hidden" name="message" id="message">
<button type="submit" id="saveButton">Save!</button>
</form>
Don't leave the page just after triggering an AJAX request, wait for the result using the callback.
$.post("includes/changePage.inc.php", {message: message}, function (data) {
// here you see 'Hello World' in your browser console
console.log(data);
// here you don't see anything in your browser window because it is no POST
window.location.href = "includes/changePage.inc.php";
});
But why to trigger an ajax request and redirect to the same page afterwards...
Maybe this is what's intended (second try):
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
</head>
<body>
<script>
$(document).ready(function(){
$('#saveForm').submit(function(event){
// NO: event.preventDefault();
var message = "";
var changeText = function(){
message = "You wrote: " + $('#text').val();
};
changeText();
// Check for text as message can't be empty here
if (!$('#text').val()){
// preventDefault() here if text is empty
event.preventDefault();
}
});
});
</script>
<form id="saveForm" action="includes/changePage.inc.php" method="POST">
<!-- put textarea inside your form, and write tags in lowercase -->
<textarea id="text"></textarea>
<button type="submit" id="saveButton">Save!</button>
</form>
</body>
</html>
I have this code.
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form action = "" method = "POST" id = "form">
<img src = "circle.gif" id="loading" style="display:none; "/>
<input type="text" name = "text2">
<input type="submit" name="submit2" value="Send">
</form>
<?
if (isset($_POST['submit2'])){
echo $_POST['text2'];
}
?>
<script>
$('#form').submit(function(e) {
$('#loading').show();
return false;
});
</script>
</body>
</html>
I want to store in my db the value written in the textbox using PHP, and while it's being saved, I want to show a gif using jQuery, once the page is loaded, this gif should be removed.
Then, If I don't comment nothing, gif appears when submit button is submitted but echo fails.
If I comment the jQuery script, PHP echoes the vale written.
If I comment the PHP script, gif is shown but no echo of course...
How could I do what i'm asking. I know that my full script does until only showing the gif, but this without this I can't continue.
You can achieve your desired behaviour, but you need to do it by submitting an AJAX request to the server and then handling the return value. So basically you'd add this ajax request to the click or submit event of the form, and handle the behaviour and request via javascript.
Perhaps something like this:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form action = "formSubmitHandler.php" method = "POST" id = "form">
<img src = "circle.gif" id="loading" style="display:none; "/>
<input type="text" name = "text2">
<input type="submit" name="submit2" value="Send">
</form>
<script>
$(document).ready(function(){
$('#form').submit(function(){
// Show the loading icon before the processing begins
$('#loading').show();
// Send the query/form details to the server
jQuery.ajax({
data: $(this).serialize(),
url: this.action,
type: this.method,
success: function(results) {
// Now that the processing has finished, you
// can hide the loading icon
$('#loading').hide();
// perhaps display some other message etc
}
})
return false;
});
});
</script>
</body>
</html>
I`m trying to make somethig like login with jquery. There should be a validation on text fields to echo error message. If the form is completely validated then function in jquery should update the div, where there is the input form and change it to the session name. But There is a problem, when posted form is validated then div remains empty, there is no session name.
HTML:
<html>
<head>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
jQuery(function(){
jQuery('#form').submit(function(){
jQuery.ajax({
type: 'POST',
url: jQuery('#form').attr('action'),
data: jQuery('#form').serialize(),
success: function(data){
if(data == 'success'){
jQuery('#user').load(location.href+' #user>*');
}else{
jQuery('#info').html(data);
}
}
});
return false;
});
});
</script>
</head>
<body>
<div id="user">
<div id="info"></div>
<?php
session_start();
if(isset($_SESSION['user'])){
echo $_SESSION['user'];
}else{
echo '
<form method="post" action="session.php" id="form">
<input type="text" name="user" />
<input type="submit" name="do" value="ok" />
</form>
';
}
?>
</div>
</body>
</html>
PHP:
<?php
$user = mysql_real_escape_string($_POST['user']);
if(empty($user)){
echo 'psc';
}else{
echo 'success';
session_start();
$_SESSION['user'] = $user;
}
?>
I think type: 'POST' in your ajax call is usually done in lower case: type: 'post'. I am not sure if this is the issue, but you may want to try it.
Aside from that, the other problem with your code is that you are not preventing the form from being submitted. So basically you are sending an ajax message, but then immediately loading a new page with the default submit that occurs when clicking the submit button. I would think that this has the effect of loading a blank page?
To fix this you could add to your submit handler the following lines:
jQuery('#form').submit(function(event){
event.preventDefault();
Notice I have added event to the handlers arguments, and then called the preventDefault() method to stop the form from actually submitting. Returning false in the handler does not do this for you.
this a simple example in how to submit form using the Jquery form plugins and retrieving data using html format
html Code
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#htmlForm').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#htmlExampleTarget',
// success identifies the function to invoke when the server response
// has been received; here we apply a fade-in effect to the new content
success: function() {
$('#htmlExampleTarget').fadeIn('slow');
}
});
});
</script>
</head>
<body>
<form id="htmlForm" action="post.php" method="post">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>
PHP Code
<?php
echo '<div style="background-color:#ffa; padding:20px">' . $_POST['message'] . '</div>';
?>
this just work fine
what i need to know if what if i need to Serialize the form fields so how to pass this option through the JS function
also i want show a loading message while form processed
how should i do that too
thank you
To serailize and post that to a php page, you need only jQuery in your page. no other plugin needed
$("#htmlForm").submit(function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData}, function(data) {
//do whatever with the response here
});
});
If you want to show a loading message, you can do that before you start the post call.
Assuming you have div with id "divProgress" present in your page
HTML
<div id="divProgress" style="display:none;"></div>
Script
$(function(){
$("#htmlForm").submit(function(){
$("#divProgress").html("Please wait...").fadeIn(400,function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData},function(data) {
//do whatever with the response here
});
});
});
});
The answer posted by Shyju should work just fine. I think the 'dat' should be given in quotes.
$.post("post.php", { 'dat': serializedData},function(data) {
...
}
OR simply,
$.post("post.php", serializedData, function(data) {
...
}
and access the data using $_POST in PHP.
NOTE: Sorry, I have not tested the code, but it should work.
Phery library does this behind the scenes for you, just create the form with and it will submit your inputs in form automatically. http://phery-php-ajax.net/
<?php
Phery::instance()->set(array(
'remote-function' => function($data){
return PheryResponse::factory('#htmlExampleTarget')->fadeIn('slow');
}
))->process();
?>
<?php echo Phery::form_for('remote-function', 'post.php', array('id' => ''); ?> //outputs <form data-remote="remote-function">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>