I have this PHP page that grabs the response's from a form (well i hope it does) and then inputs the data into a table. I then echo the response from the table on the same page. Im using ajax on the form page to send over the form values and on success of the ajax call load the data into a div. this is all done without a refresh, however no information is being sent and it just refresh's the page
my php page -
<?php
$comment_name = $_POST["name"];
$comment_body = $_POST["comment"];
$film_no = $_POST["hidden"];
echo $comment_name;
echo $comment_body;
echo $film_no;
// Connects to your Database
mysql_connect("localhost", "****", "****") or die(mysql_error());
mysql_select_db("ignitet1_CheckFilm") or die(mysql_error());
$query1 = "INSERT INTO film_comments (comments_id,film_no,name,comment)
VALUES ('','$film_no', '$comment_name','$comment_body')";
$runquery1 = mysql_query($query1)or die(mysql_error());
$getComments = mysql_query("SELECT * FROM film_comments where film_no = '$film_no'")
or die(mysql_error());
while($info = mysql_fetch_array($getComments))
{
echo "<p>";
echo $info['name'];
echo ":</p>";
echo "<p>";
echo $info['comment'];
echo "</p>";
echo "<p>Comment posted on:";
echo $info['timestamp'];
echo "</p>";
echo "</div>";
?>
my form and javascript code
<form id="ContactForm2" onsubmit="return submitForm()" >
<div> <input type="hidden" name="hidden" id="hidden" value="2">
<label for="name">Your Name</label>
<input type="text" name="name" id="name" />
<label for="body">Comment Body</label>
<textarea name="comment" id="comment" cols="20" rows="5"></textarea>
<input type="submit" id="comment" class="button" value="Submit" />
<div class="form_result"> </div>
</form> </div>
<script>
function submitForm() {
$.ajax({type:'POST', url: 'comment.php', data:$('#ContactForm2').serialize(), success: function(response) {
$('#ContactForm2').find('.form_result').html(response);
}});
}
Everything i try seems to not work. help would be much appreciated! :)
Try this with your php its working fine for me.
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#sub').click(function(){
$.ajax({type:'POST', url: 'comment.php', data:$('#ContactForm2').serialize(), success: function(response) {
$('#ContactForm2').find('.form_result').html(response);
}});
});
})
</script>
<body>
<div>
<form id="ContactForm2"> > <input type="hidden" name="hidden" id="hidden" value="2">
<label for="name">Your Name</label>
<input type="text" name="name" id="name" />
<label for="comment">Comment Body</label>
<textarea name="comment" id="comment" cols="20" rows="5"></textarea>
<input type="button" id="sub" class="button" value="Submit" />
<div class="form_result"> </div>
</form> </div>
</body>
</html>
Related
Here is my php code:
<?php
try{
//Need to make a connection
$con=new PDO("mysql:host=localhost;dbname=courseraassignment","root","");
$statementUpdate=$con->prepare("select * from position
where profile_id=:profile_id");
$statementUpdate->execute(array(
':profile_id'=>$_REQUEST['profile_id']
));
foreach($statementUpdate as $row){
echo $row['year'];
echo $row['description'];
echo "<br>";
}
}catch(PDOException $e){
echo "error".$e->getMessage();
}
?>
From this PHP code, I wanted to achieve data including the year and description of the position table from the database.
Here is my complete html code:
<div class="container">
<h1>Ashiful Islam Prince's Resume Registry</h1>
<h1>Editing Profile for UMSI</h1>
<?php
if(isset($_SESSION['profile_error'])) {
$error = $_SESSION['profile_error'];
unset($_SESSION["profile_error"]);
echo '<span class="text-danger">';
echo $error;
echo '</span>';
}
?>
<form method="post">
<p>First Name:
<input type="text" name="first_name" value="<?php
echo $firstName;
?>"
></p><br>
<p>Last Name:
<input type="text" name="last_name" value="<?php
echo $lastName;
?>"</p>
<p>Email:
<input type="text" name="email" value="<?php
echo $Email;
?>"</p><br>
<span class="text-danger">
<?php
if(isset($email_sign_error))
echo $email_sign_error;
?>
</span>
<p>Headline:<br/>
<input type="text" name="headline" value="<?php
echo $Headline;
?>"</p>
<p>Summary:<br/>
<textarea name="summary" rows="8" cols="80">
<?php
echo $Summary;
?>
</textarea>
<p>Position : <input type="button" class="add_position" id="add_position"
name="addPosition" value="+">
<div class="position_fields" id="position_fields">
</div>
<p>
<input type="submit" value="Save" name="btn" class="btn btn-primary">
<input type="submit" name="cancel" value="Cancel">
</p>
</form>
</div>
</div>
</div>
Here is the part of code from above:
<div class="position_fields" id="position_fields">
</div>
In this part, I want to show these fetched values(The year and the description).
Here is my JQUERY code:
<script type="text/javascript">
$(document).ready(function(){
var countPos=0;
var add_button=$('#add_position');
var wrapper=$('#position_fields');
window.console && console.log('Document ready called');
//When the user clicks on the add button then It inserts these input fields
function addField(event){
if ( countPos >=9 ) {
alert("Maximum of nine position entries exceeded");
return;
}
countPos++;
window.console && console.log("Adding position "+countPos);
$(wrapper).append(
'<div id="position'+countPos+'"> \
<p>Year: <input type="text" name="year'+countPos+'" value="" /> \
<input type="button" value="-" \
onclick="$(\'#position'+countPos+'\').remove();return false;"></p> \
<textarea name="desc'+countPos+'" rows="8" cols="80"></textarea>\
</div>');
}
$(add_button).click(function(event){
addField();
});
addField();
});
</script>
This code is developed for handling the dynamic input field issues. When the user clicks to the add button then dynamic input fields will be displayed and these fields will be shown at the time of page loads as well.
I want to achieve:
Everything will be done as same as it is. But when the page loads these dynamic input fields will be displayed with values. How can I achieve my goal?
I have got a PHP contact form where I'm trying to implement Ajax to it to make it more user friendly because the contact form is a pop-up form using javascript/jQuery, so everytime the form is submitted it refreshes the page and you have to go back in the form to view the validation message.
Could you check what am I missing here please? I've been on it for sometime now and it still doesn't work. Please let me know if you want me to add the PHP script.
Ajax code:
jQuery(document).ready(function ($) {
$("#ajax-contact-form").submit(function () {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "demoform.php",
data: str,
success: function (msg) {
if (msg == 'OK') {
result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
$("#fields").hide();
} else {
result = msg;
}
$("#note").html(result);
}
});
return false;
});
});
HTML FORM
<center>
<p>Please complete the form below <br />to request a <br/> <span id="free_demo">FREE DEMO</span></p>
<div id="note"></div>
<div id="fields">
<form id="ajax-contact-form" enctype="multipart/form-data">
<div><input type="text" placeholder="Name" name="fullname" id="vpbfullname" value="<?php echo strip_tags($_POST["fullname"]); ?>" class="vpb_input_fields"> <?php echo $submission_status1; ?></div>
<div><input type="text" placeholder="E-Mail" name="email" id="email" value="<?php echo strip_tags($_POST["email"]); ?>" class="vpb_input_fields"><?php echo $submission_status2; ?></div>
<div><input type="text" placeholder="Company" name="company" id="company" value="<?php echo strip_tags($_POST["company"]); ?>" class="vpb_input_fields"><?php echo $submission_status3; ?></div>
<div><input type="text" placeholder="Telephone" name="phone" id="telephone" value="<?php echo strip_tags($_POST["phone"]); ?>" class="vpb_input_fields"><?php echo $submission_status4; ?></div>
<div class="vpb_captcha_wrappers"><input type="text" placeholder="Security Code" id="vpb_captcha_code" name="vpb_captcha_code" class="vpb_input_fields"> </div>
<br/><br/><br/>
Refresh Security Code</font>
<br/><br/>
<div class="vpb_captcha_wrapper"><img src="vasplusCaptcha.php?rand=<?php echo rand(); ?>" id='captchaimg' ></div><br clear="all"><br/>
<br clear="all">
<div><?php echo $submission_status; ?></div><!-- Display success or error messages -->
<div> </div>
<input type="hidden" id="submitted" name="submitted" value="1">
<input type="submit" class="vpb_general_button" value="Submit"></form> </div>
<br clear="all">
</center>
Any help would be great.. Thanks
Use preventDefault();
$("#ajax-contact-form").submit(function (e) {
e.preventDefault();
//....
};
This is preventing the form submit, but ajax call will happens.
you have to write onsubmit="return false" in your form tag like
Here is my form, from which i want to update the values. When i try this with simple php+html it works perfectly!! But when i try to post values through ajax call it doesn't work.Any suggestions please.
HTML
<form class="form-block" role="form" action="" method="post">
<div class="form-group">
<?php
$email=$_SESSION["login_email"];
$query=mysqli_query($con,"select * from customers where email='$email'");
while($row=mysqli_fetch_array($query,MYSQLI_ASSOC))
{
?>
<label for="name">Full Name</label>
<input type="text" name="name" class="form-control" id="name" value="<?= $row["name"]; ?>" placeholder="Full Name">
<label for="comment">Address</label>
<textarea class="form-control" name="address" id="address" rows="5" id="comment" ></textarea>
<label for="telephone">Telephone</label>
<input type="tel" class="form-control" name="phone" id="phone" placeholder="Enter Mobile Number" value="" >
<label for="city">City</label>
<input type="text" class="form-control" name="city" id="city" placeholder="Enter City" value="<?= $row["city"]; ?>" >
</div>
<?php
}?>
<input type="submit" class="btn btn-default" name="add" id="add" value="Update"/>
<span class='msg'></span>
<div id="error"></div>
</form>
AJAX
$(document).ready(function() {
$('#add').click(function()
{
$.ajax({
url: "address_update.php",
type: "POST",
async: true,
data: { Name:$("#name").val(),Address:$("#address").val(), Phone:$("#phone").val(), City:$("#city").val()}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
if(data)
{
//$('#output').html(data);
$("body").load("index.php?page=form");//.hide();//.fadeIn(1500).delay(6000);
}
else
{
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}}});
});});
PHP
<?php
include ("db/db.php");
session_start();
$name=$_POST['Name'];
$address=$_POST['Address'];
$phone=$_POST['Phone'];
$city=$_POST['City'];
$email=$_SESSION['login_email'];
$sql=mysqli_query($con,"Update customers set name='$name',address='$address',phone='$phone',city='$city' where email='$email'");
if($sql)
{
echo "updated";
}
This selector:
$('#add')
doesn't find anything. Because there is no HTML element in your markup with id="add".
You do have an element with name="add". So either add an id to that element:
<input id="add" type="submit" class="btn btn-default" name="add" value="Update"/>
or change your selector to target the existing element:
$('input[name="add"]')
Note: The same is also true of $('#address') and $('#phone'). No such elements exist in your markup. Take a look at the jQuery documentation for selectors.
Remove the IF loop mentioned under
if(isset($_SESSION["login_email"]))
Additionally, you nee to change the button type from submit to button
<input type="submit" class="btn btn-default" name="add" value="Update"/>
Above sends the form, whatever you add to the click event is done in parralel.
<input type="button" class="btn btn-default" name="add" value="Update"/>
only executes your JavaScript, when using:
$('input [name="add"]').click(function(){
// your improved ajax call here
}
Try this:
$.ajax({
.
.
data: {
'Name': $name,
'address': $address,
.
.
}
});
I would like to make the PHP echo I have appear in the div "preview". I want this because I don't want the page to refresh but to make the div "formbox" disappear and to show the echo in the "preview" div.
Does someone know what I am doing wrong?
HTML
<div id="preview"> </div>
<div id="formbox">
<form id="form" method="post" action="contactengine.php">
<label for="Name">Name:</label>
<input type="text" name="Name" id="Name" />
<label for="City">City:</label>
<input type="text" name="City" id="City" />
<label for="Email">Email:</label>
<input type="text" name="Email" id="Email" />
<label for="Message">Message:</label><br />
<textarea name="Message" rows="20" cols="20" id="Message"></textarea>
<input type="submit" name="submit" value="Submit" class="submit-button" />
</form>
</div>
jQuery
$('document').ready(function(){
$('#form').ajaxForm( {
target: '#preview',
success: function() {
$('#formbox').slideUp('fast');
}
});
});
PHP
if ($success){
echo "<h1>Thank You!";
}
Just use the result.
$('document').ready(function(){
$('#form').ajaxForm( {
target: '#preview',
success: function( result ) {
$('#formbox').slideUp('fast');
$('#preview').html(result);
}
});
});
JS
$(document).ready(function(){
$('.comment').bind("blur focus keydown keypress keyup", function(){recountss();});
$('input.comment_button').attr('disabled','disabled');
$('#form').submit(function(e){
tweet();
});
});
function recountss()
{
var maxlen=280;
var current = maxlen-$('.comment').val().length;
$('.counters').html(current);
if(current<0 || current==maxlen)
{
$('.counters').css('color','#D40D12');
$('input.comment_button').attr('disabled','disabled').addClass('inact');
}
else if (!$.trim($(".comment").val()))
{
$('input.comment_button').attr('disabled','disabled').addClass('inact');
}
else
$('input.comment_button').removeAttr('disabled').removeClass('inact');
if(current<10)
{
$('.counters').css('color','#D40D12');
}
else if(current<20)
{
$('.counters').css('color','#5C0002');
}
else
{
$('.counters').css('color','#C0C0C0');
}
HTML
<form method="post" action="" id="form">
<textarea name="comment" class="comment" id="ctextarea<?php echo $msg_id;?>" ></textarea>
<input type="hidden" name="uid" id="uid" value="<?php echo $uid; ?>"/>
<div class="p"></div>
<input type="submit" value="Comment" id="<?php echo $msg_id;?>" class="comment_button"/>
<span class="counters">
280
</span>
</form>
I using jquery.
I have more than 1 textarea, if I type in textarea-1, it work, button disabled if no any text and recount working good.
But if I type in textarea-2, textarea-3, textarea-N, it can't work.
So how can I do to make all works ?
Thank you.
If each <textarea> has its own maxlen=280, it would be better to change from using class - $('.comment') to id - $('#ctextarea-'+i) on all elements - <textarea>, <button>, <span>, etc.
This is untested, but should help point you in the right direction.
$(document).ready(function(){
var i=1;
var numtextarea = 1;
$('#form').find('textarea').each(function(){numtextarea++;} //find number of <textarea>'s
while(i<numtextarea){ // loop through each <textarea>
$('#ctextarea-'+i).bind("blur focus keydown keypress keyup", function(){recountss(i);});
$('#comment_button-'i).attr('disabled','disabled');
}
});
$('#form').submit(function(e){
tweet();
});
});
function recountss(i)
{
var maxlen=280;
var current = maxlen-$('#ctextarea-'+i).val().length;
$('#counters-'+i).html(current);
if(current<0 || current==maxlen)
{
$('#counters-'+i).css('color','#D40D12');
$('#comment_button-'+i).attr('disabled','disabled').addClass('inact');
}
else if (!$.trim($("#ctextarea-'+i).val())) {
$('#comment_button-'+i).attr('disabled','disabled').addClass('inact');
}
else
$('#comment_button-'+i).removeAttr('disabled').removeClass('inact');
if(current<10)
$('#counters-'+i).css('color','#D40D12');
else if(current<20)
$('#counters-'+i).css('color','#5C0002');
else
$('#counters-'+i).css('color','#C0C0C0');
}
And your form should look like -
<form method="post" action="" id="form">
<textarea name="comment" class="comment" id="ctextarea-1" ></textarea>
<input type="hidden" name="uid" id="uid" value="1"/>
<div class="p"></div>
<input type="submit" value="Comment" id="comment_button-1" class="comment_button"/>
<span id="counters-1">
280
</span>
<textarea name="comment" class="comment" id="ctextarea-2" ></textarea>
<input type="hidden" name="uid" id="uid" value="2"/>
<div class="p"></div>
<input type="submit" value="Comment" id="comment_button-2" class="comment_button"/>
<span id="counters-2">
280
</span>
...
<textarea name="comment" class="comment" id="ctextarea-N" ></textarea>
<input type="hidden" name="uid" id="uid" value="N"/>
<div class="p"></div>
<input type="submit" value="Comment" id="comment_button-N" class="comment_button"/>
<span id="counters-N">
280
</span>
</form>