update and show comment without reloading the webpage - php

i have the following jquery code, which is link to a html form which is link to a php script. the form should submit and the jquery code should update the comment and show the comment as if the page was referesh. but nothing happens when i hit submit i cant seem to see where or what i am doing wrong.
<script type="text/javascript">
$(function() {
//When submit button clicked
$('#submit').click(function(){
//Getting data from input fields
var sentby_val = $('#sent_by').val();
var message_val = $('#message').val();
$.post('comment.php', { username: sentby_val, message: message_val }, function(return_data){
//Response from script when comment inserted to database
alert(return_data);
//Clean fields
$('#sent_by').val('<?php print $_SESSION['email']?>');
$('#message').val('');
});
});
});
</script>
here is the html form
<form action='comment.php' method='post' style="width: 422px">
<input type='hidden' id="sent_by" name='sent_by' value="<?php print $_SESSION['email']?>"/>
<input type='hidden' id="hidden_id" name='hidden_id' value='<?php print $picid;?>'/>
<textarea name='message' id="message" value="make your comment" style="width: 450px; height: 70px">make your comment</textarea><br/>
<input type='submit' name='sub' value='comment' id="submit" style="border-style:none; float:right;" />
</form>
here is the comment.php // which shouldnt really be the problem
<?
$name = $_POST['sent_by'];
$picid= $_POST['hidden_id'];
$message = $_POST['message'];
$sub = $_POST['sub'];
if ($sub){if($name&&$message&&$picid)
{
$insert = mysql_query("INSERT INTO comment (name,message,picid) VALUES ('$name','$message','$picid')" );
}
else
{
echo "Please enter a comment";
}
header("location:../profile.php?pic=$id");
?>
please help what am i missing or not seeing

Try this:
<script type="text/javascript">
$(function() {
//When submit button clicked
$('#submit').click(function(){
//Getting data from input fields
var sentby_val = $('#sent_by').val();
var message_val = $('#message').val();
$.post('comment.php', { username: sentby_val, message: message_val }, function(return_data){
//Response from script when comment inserted to database
alert(return_data);
//Clean fields
$('#sent_by').val('<?php print $_SESSION['email']?>');
$('#message').val('');
});
// Overrides default click handler.
// Without this the form will be submitted
return false;
});
});
</script>

Related

Problems about keep in the page with ajax

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){
});

Type input characters in html form need match - jQuery?

How do I type in a HTML textbox and if the first 3 characters dont match a set variable - then display an error? I need to lose the error and display text next to the input after the 3rd character
I'm thinking jQuery, AJAX, PHP - not sure. I just don't want to use an alert box.
And this needs to be before a user enters the submit button...
<form>
<input type="text" id="test"/><br>
<input type="button" id="txt" value="Submit" />
</form>
$(document).ready(function(){
$("#txt").click(function(){
var text = $("#test").val();
var comparingText = "yes";
if (text != comparingText){
alert( $("#test").val());
}
});
});
It will show this alert after write yes.
you can use it as you want.
$( "#test" ).keyup(function() {
var test = $( "#test" ).val();
if(test == 'yes'){
alert( "your Error msg" );
}
});
You can use a <span> element, next to the <input> element to display an error message and, as you said, avoid using the alert box.
JS
HTML
<form>
<input type="text" id="test" oninput="submitData(this.value)"/>
<span id="textError"></span><br/>
<input type="button" id="txt" value="Submit" />
</form>
JS
function submitData(input) {
if (input != "yes") {
document.getElementById("textError").innerHTML = "Your Error MSG";
} else {
document.getElementById("textError").innerHTML = "";
}
}
JS + jQuery
In this case I'm taking Mamunur Rashid's answer to complement the code.
HTML
<form>
<input type="text" id="test"/> <span id="textError"></span><br/>
<input type="button" id="txt" value="Submit" />
</form>
jQuery
$(document).ready(function(){
$("#test").keyup(function(){
var test = $("#test").val();
if (test != "yes") {
$("#textError").html("Your Error MSG");
} else {
$("#textError").html("");
}
});
});

trying to auto submit form after text input

Here is how the form is supposed to execute:
<script>
$(document).ready(function(){
$("#submit").click(function(){
//access token stuff
var token = $("#link_input").val(); ... etc</script>
.
I am trying to auto submit this info once it exceeds 10 characters. Normally you fill out the text area in the input field and you click submit. Upon clicking the submit button the JS validates the text in the input box and if it's valid it executes. How can I auto-submit the text in the input box without having to click the submit button?
<script language="JavaScript" type="text/JavaScript">
var x=10;//nr characters
function submitT(t,f){
if(t.value.length==x){
f.submit()
}
}
</script>
<input id="link_input" onkeyup="submitT(this,this.form)" autofocus="true" autocomplete="off" placeholder="http://www.facebook.com/connect/login_success.html#access_token=AAAZDCiOS6Ls0BAMUKJDvLZCTgZDZD" style="width: 600px;margin-left: -11%;" value="" name="url">
<br/>
<div id="Wait" style="display:none;"><center>Processing your form<br><img src="http://i.imgur.com/kKqSe.gif"></center></div>
<br/>
<center>
<img src="http://i.imgur.com/eA6fv.png" style="border:0px;padding-top:5px;">
$('#link_input').on('keyup', function() {
if($(this).val().length > 10) {
$('form').submit();
}
});
Just test against keyup similar to what you have already.
<form action='someplace' id='myform' method='post'>
<input type='text' id='link_input' ...other stuff />
</form>
jquery:
$('#link_input').on('keyup',function(){
var val = $(this).val();
var len = val.length;
if(len == 10){
$('#myform').submit();
}
});
Rename your btn from submit to btnSubmit.
The id of submit is going to mess with f.submit()

Submitting forms thru in PHP on jQuery

I have a registration form that is currently in a popup modal window coded in jQuery. I have a PHP submit button on the bottom and I have added jQuery code that stops the button from submitting. This is because it will stop my modal window from closing when I submit the page. My issue now is that submitting the form would be impossible. Is there a way to submit my form over all this crowded pop-ups and jQuery? Say is it possible to use AJAX or jQuery to submit the form and allow my PHP to handle it.
Since I am writing in PHP, there is quite a bit of server side validation going on, so the point of this is to allow my viewers to fix their validation mistakes before the modal window closes.
Here is my jQuery, I didnt bother to mess with that anymore as it does what I need.
$(document).ready(function() {
$('a.modal-window').click(function() {
//Getting the variable's value from a link
var loginBox = $(this).attr('href');
$(loginBox).fadeIn(300);
var popMargTop = ($(loginBox).height() + 24) / 2;
var popMargLeft = ($(loginBox).width() + 24) / 2;
$(loginBox).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
// Add the mask to body
$('body').append('<div id="mask"></div>');
$('#mask').fadeIn(300);
return false;
});
// When clicking on the button close or the mask layer the popup closed
$('a.close, #mask').live('click', function() {
$('#mask , .login-popup').fadeOut(300 , function() {
$('#mask').remove();
});
return false;
});
});
Here is the code I used to stop the form from submitting:
$(function () {
$(':submit').click(function (event) {
event.preventDefault();
// submit the form dynamically
});
});
and below is my form, it might not matter although its there for the viewing.
<form method="post" id="loginform" action="<?php echo $_SERVER['PHP_SELF']?>">
<table style="color: white;">
<tr><th style="float:left;">Register a new account with us.</th></tr>
<tr><td>Username</td><td><input type="text" name="txtUser"/></td></tr>
<tr><td>Password</td><td><input type="text" name="txtPass"/></td></tr>
<tr><td>Email</td><td><input type="text" name="txtEmail"/></td></tr>
<tr><td>Confirm Email</td><td><input type="text" name="txtEmail2"/></td></tr>
<tr><td>First Name</td><td><input type="text" name="txtFname"/></td></tr>
<tr><td>Last Name</td><td><input type="text" name="txtLname"/></td></tr>
<tr><td>Address</td><td><input type="text" name="txtAddress"/></td></tr>
<tr><td>City</td><td><input type="text" name="txtCity"/></td></tr>
<tr><td>Postal Code</td><td><input type="text" name="txtPostal"/></td></tr>
<tr><td>Birth Year</td><td><input type="text" name="txtBirth"/></td></tr>
<tr><td>Gender</td><td><input type="radio" id="radio-1-1" name="radicalSex" class="regular-radio" value="m" selected="true" /><label for="radio-1-1"></label> Male</td></tr>
<tr><td></td><td><input type="radio" id="radio-1-2" name="radicalSex" class="regular-radio" value="f"/><label for="radio-1-2"></label> Female</td></tr>
<tr><td colspan='2' style="color: #FF6600;float:left;font-size:70%;"><?php echo $Error;?></td></tr>
<tr><td colspan="2"><input type="submit" name="btnRegister" ID="btnBlueTemp" value="Submit Registration" /></td></tr>
<tr><td colspan='2' style="float:left; font-size:70%;">Address information is optional</td></tr>
</table>
</form>
Let me give you an example of how you can do that .
<html>
<head>
<title></title>
<script src="js/jquery-1.7.2.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
function validate(name, addr){
if(name=="") {
alert('Name is Blank');
return false;
} else if(addr=="") {
alert('Address is Blank');
return false;
} else {
return true;
}
}
$("#save").click(function(event){
event.preventDefault();
var name = $("#name").val();
var addr = $("#addr").val();
if(validate(name,addr)){
$.ajax({
type:'POST',
data:'name='+name+'&addr='+addr,
url:'test2.php',
success:function(data) {
alert(data);
}
})
}
});
});
</script>
</head>
<body>
<form name="frm" method="POST" action="">
<input type="text" name="name" id="name" value=""/><br>
<input type="text" name="addr" id="addr" value="" /><br>
<input type="submit" name="save" id="save" value="Save"/>
</form>
</body>
</html>
Now in test2.php You can do your php codes
<?php
if(isset($_POST['name'])) {
echo $_POST['name'];
}
?>
Hope this gives you an Idea.
You need to serialize the form data before posting it to PHP.
<script type="text/javascript">
var frm = $('#loginform');
frm.submit(function () {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('submitted');
}
});
return false;//stop actual form submit
});
</script>
Then, submit your form via ajax
Jquery AJAX
On AJAX URL on which the request is sent, you can write necessary codes for validation and return accordingly. For eg. if some one the form element doesn't meet the validation, you can throw the flag accordingly as json value.
Its possible, why not.
Once you have done all the input validation at client side, just submit the form...
$("#loginform").submit();
Then you will have your server do the rest of the validation.
If you want to stay in the page and show the validation output from server, the. You should submit using Ajax.
It will send your form data to server, then you can do server validation, and output any errors. You will get this in your Ajax complete handler, which you can use to show error messages to user.
To stop the form from reloading the page you needn't call any prevent methods as a simple script request would do the trick.
For instance,
$('#loginForm').submit(function() {
// Do the relevant tasks needed here, form is already prevented from being submitted
});
Check out this demo for more information on what I am referring to

Ajax Load - Form Submission

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
}
?>

Categories