I have a program which I am able to add datas without javascript. But I would like to use AJAX and I do not know why it does not work. When I click Add button it does happen nothing and I do not see the data in phpmyadmin. Can anyone help me?
index.php:
session_start();
require_once("auth.php");
require_once("control.php");
<div class="well well-sm bs-component">
<div class="form-group row add">
<form method="post" action="">
<div class="col-md-12">
<label for="content" class="control-label">Your Comment</label>
<input type="hidden" name="uid" value="<?= $id; ?>">
<input type="hidden" name="date" value="<?= date('Y-m-d H:i:s') ?>">
<textarea id="content" name="content" class="form-control" rows="3" placeholder="Enter your comment..." required></textarea>
<p class="error text-center alert alert-danger hidden"></p>
</div>
<div class="addButton col-md-12">
<button class="btn" type="submit" id="add" name="add">
<span class="glyphicon glyphicon-plus"></span> SEND
</button>
</div>
</div>
</form>
</div>
control.php:
//ADD COMMENT
if ( isset($_POST['add']) ) {
$id = $_POST['uid'];
$date = $_POST['date'];
$content = $_POST['content'];
$sql= "INSERT INTO posts (uid, content, date) VALUES ('$id', '$content', '$date')";
if (!$mysqli->query($sql)) {
header("location: error.php");
}
}
Javascript:
$("#add").click(function() {
var formData = {
'name': $('#content').val()
};
$.ajax({
type: 'post',
url: 'control.php',
data: formData,
success: function(data) {
if ((data.errors)){
$('.error').removeClass('hidden');
$('.error').text(data.errors.name);
}
else {
$('.error').addClass('hidden');
$('#table').prepend("<div class='item" + data.id + " mess'><div class='btn-group-sm'><button class='edit-modal btn btn-circle' data-id=" + data.id + " data-name=" + data.name +"><span class='glyphicon glyphicon-pencil'></span></button><button class='delete-modal btn btn-circle' data-id=" + data.id + " data-name=" + data.name +"><span class='glyphicon glyphicon-trash'></span></button></div><article class='myMessage'><p>" + data.name + "</p></article></div><div class='clear' style='clear: both;''></div>");
}
},
});
$('#content').val('');
});
You are sending only this as the $_POST data:
var formData = {
'name': $('#content').val()
};
Which should result only to $_POST['name'] => VALUE
But you are reading from $_POST['content']; and other vars.
You also check for $_POST['add'] which is not being sent by your AJAX.
Change the key, you are using to send/read the data on one side and also try to add the other keys/values to your data, e.g.
var formData = {
'add': 'yes',
'content': $('#content').val(),
'uid': SOMEVALUE,
'date': SOMEVALUE
};
The uid and the date are things you might wanna create in your control.php dynamically anyway. But then don't read them from $_POST
ADDITION: Further reading with an example that matches your use case: https://scotch.io/tutorials/submitting-ajax-forms-with-jquery
you are just passing name. you have to pass uid and date also
var formData = {
'name': $('#content').val()
};
with this.
give id to uid and date textfield
var formData = {
'name': $('#content').val(),
'uid': $('#uid').val(),
'date': $('#date').val(),
};
in control.php database connection is necessary. without it record will not inserted
Related
I'm working on a personal project, where I've more forms than one (comment forms under each post). Each form I give a number according to post id.
<form id="postCommentsForm<?php echo $ansRow['id'];?>" class="form">
<div class="input-group mb-3">
<a href="user/<?php echo $username;?>">
<img class="p-1 m-0" src="images/<?php echo $userAvatar;?>" width="35" height="35" alt="<?php echo $userAvatar;?> profile picture">
</a>
<input name="post_comment<?php echo $ansRow['id'];?>" id="add_comments" type="text" autofocus autocomplete="off" class="add_comments form-control pl-3 pr-3" placeholder="<?php echo $userFname;?>, type something" aria-label="Recipient's username" aria-describedby="button-form">
<input type="text" hidden id="question_id" name="question_id" value="<?php echo $row['id'];?>">
<input type="text" hidden id="answer_id" name="answer_id" value="<?php echo $ansRow['id'];?>">
<input type="text" hidden id="session_id" name="session_id" value="<?php echo $_SESSION['id'];?>">
<div class="input-group-append">
<button class="btn btn-secondary submit-comments" type="submit" name="submit_comment<?php echo $ansRow['id'];?>" id="postComments">Comment</button>
</div>
</div>
</form>
javascript code
$(document).ready(function() {
$("[id^=postCommentsForm]").on("submit", function(e) {
e.preventDefault();
var add_comments = $("#add_comments").val();
var question_id = $("#question_id").val();
var answer_id = $("#answer_id").val();
// var session_id = $("#session_id").val();
if(add_comments == "" ){
$("#error-message").html("All fields are required!").slideDown();
$("#success-message").slideUp();
}else{
//Ajax
$.ajax({
url: "include/forms-data/comments.php",
type: "POST",
data: {
add_comments: add_comments,
question_id: question_id,
answer_id: answer_id
},
success: function(data) {
if (data != 0) {
$("[id^=postCommentsForm").trigger("reset");
$("#success-message").html("Question Added Successfully!").slideDown();
$("#error-message").slideUp();
} else {
//alert("Can't save record");
$("#error-message").html("Something went wrong!").slideDown();
$("#success-message").slideUp();
}
}
});
}
});
});
How I can fetch #comments(postID here), and submit form data successfully under the postID?
I hope I define well the question.
Jquery's "starts with selector" can help. check out here
$(document).ready(function() {
$("[id^=comments]").click(function(e) {
var element_id = this.getAttribute("id");
});
});
Live Demo:
$(document).ready(function() {
$("[id^=comments]").click(function(e) {
console.log($(this).attr('id'));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='comments1'>b</button>
<button id='comments2'>a</button>
i have a list of clients on a page, each client has an icon to click on to edit the client details.
<i class="fas fa-user-edit gray openModal" data-modal="modal2" client="'.$client['id'].'"></i>
Everything is good up to this point. click the icon the proper modal opens and it triggers the js file just fine. (I did alot of console logs to ensure). The client variable in my jquery file holds fine and i'm able to get it passed to the php file.
in the php file i'm able to pull the information into an array and i was able to just echo the $client['firstName'] and have it show in the console.
when i moved to getting that information and parse it as the Json is when i got lost. Can someone please help me take my result and load into my form fields. The code i have now may be totally off because i've been playing with different code from different searches.
form (shortened to two fields for ease of example)
<form id="form" class="editClient ajax" action="ajax/processForm.php"
method="post">
<input type="hidden" id="refreshUrl" value="?
page=clients&action=view&client=<?php echo $client['id'];?>">
<input type="hidden" name="client" value="<?php echo $client['id'];?>">
<div class="title">
Client Name
</div>
<div class="row">
<!-- first name -->
<div class="inline">
<input type="text" id="firstName" name="firstName" value="<?php echo $client['firstName']; ?>" autocomplete="nope" required>
<br>
<label for="firstName">First Name<span>*</span></label>
</div>
<!-- last name -->
<div class="inline">
<input type="text" id="lastName" name="lastName" value="<?php echo $client['lastName']; ?>" autocomplete="nope" required>
<br>
<label for="lastName">Last Name<span>*</span></label>
</div>
</form>
javascript/jquery file
$('.openModal').on('click', function() {
//$('body, html, div').scrollTop(0);
var that = $(this),
client = that.attr('client');
$.ajax({
type: "post",
url: "ajax/getClient.php",
data: {id:client},
success: function(response){
var result = JSON.parse(response);
var data = result.rows;
$("#firstName").val(data[0]);
}
})
});
php file
<?php
include('../functions.php');
$sql = 'SELECT * FROM clients WHERE id="'.$_POST['id'].'"';
$result = query($sql);
confirmQuery($result);
$data = fetchArray($result);
echo json_encode(['response' => $data, 'response' => true]);
?>
UPDATED ----------
Here is my final js file that allowed my form values to be set.
$('.openModal').on('click', function() {
var that = $(this),
client = that.attr('client');
$.ajax({
type: "post",
url: "ajax/getClient.php",
data: {id:client},
success: function(response){
var result = JSON.parse(response);
$("select#primaryContact").append( $("<option>")
.val(result[0].primaryContact)
.html(result[0].primaryContact)
);
$("select#primaryContact").append( $("<option>")
.val("")
.html("")
);
if (result[0].email !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].email)
.html(result[0].email)
);
}
if (result[0].phoneCell !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].phoneCell)
.html(result[0].phoneCell)
);
}
if (result[0].phoneHome !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].phoneHome)
.html(result[0].phoneHome)
);
}
$("input#firstName").val(result[0].firstName);
$("input#lastName").val(result[0].lastName);
$("input#address").val(result[0].address);
$("input#city").val(result[0].city);
$("input#zip").val(result[0].zip);
$("input#email").val(result[0].email);
$("input#phoneCell").val(result[0].phoneCell);
$("input#phoneHome").val(result[0].phoneHome);
$("input#phoneFax").val(result[0].phoneFax);
$("input#source").val(result[0].source);
$("input#referBy").val(result[0].referBy);
$("input#client").val(result[0].id);
}
})
});
This code almost works, it inserts into the db and it is giving feedback on the page to say it has updated. However I am getting undefined index between lines 5-8 in the insert_message.php and my database is filling with blank entries (except the date).
Apologies for being new to jquery and AJAX. Need some help.
form
<form enctype='multipart/form-data' action='insert_message.php' method='POST' id='contact_form'>
<div class="row">
<div class="col-xs-6">
<div class='form-group'>
<label for='email'>Email:</label>
<input class='form-control' type='email' id='email' name='email' required='required' maxlength='35'/>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-6">
<div class='form-group'>
<label for='subject'>Subject:</label>
<input class='form-control' type='text' id='subject' name='subject' required='required' maxlength='35'/>
</div>
</div>
</div>
<div class="form-group">
<label for='message'>Message:</label>
<textarea class="form-control" placeholder="Message" id='message' required="required"></textarea>
</div>
<input type="hidden" name="reciever" id='receiver' value="Admin">
<input class='btn btn-primary' id='submit' type='submit' value='submit' >
</form>
<span id="result"></span>
jquery
<script>
$(document).ready(function(){
$("#submit").click( function(e) {
e.preventDefault();
var message1 = $('message').val();
var sender1 = $('sender').val();
var receiver1 = $('receiver').val();
var subject1 = $('subject').val();
$.post("insert_message.php", {message:message1, sender:sender1, receiver:receiver1, subject:subject1}, function(info) { $("#result").html(info);
});
clearInput();
});
$("#contact_form").submit( function() {
return false;
});
function clearInput() {
$("#contact_form :input").each( function() {
$(this).val('');
});
}
});
</script>
insert_message.php
<?php
include("connections/conn.php");
$getsubject = mysqli_escape_string($conn,$_POST["subject1"]);
$getmessage = mysqli_escape_string($conn,$_POST["message1"]);
$getsender = mysqli_escape_string($conn,$_POST["sender1"]);
$getreceiver = mysqli_escape_string($conn,$_POST["receiver1"]);
$date = date("Y-m-d");
$insertmessage = "INSERT INTO messages (id,subject,message,date,sender,receiver) VALUES (NULL,'$getsubject','$getmessage','$date','$getsender','$getreceiver')";
$insert = mysqli_query($conn, $insertmessage) ;
if($insert){
echo "Message Sent";
}else{
echo "Message did not send";
}
UPDATE
attempted alternative way but I still get the undefined index in the inser_message.php
$(document).ready(function(){
$("#submit").click( function(e) {
e.preventDefault();
$.ajax({
url: "insert_message.php",
type: "POST",
data: $("#contact_form").serialize(),
success: function(result){
$("#result").html(result);
}
});
});
});
You have several problems in both JS and PHP.
Adjust typo in input hidden where actually name="reciever" instead of name="receiver";
In your $("#submit").click() function you're trying to selecting elements with an invalid selector (e.g. $('message').val() instead of $("#message").val());
Adjust $_POST keys by removing 1 at end. If you have any doubt, print the whole array print_r($_POST);
This is not an error but a suggestion. Since you require conn.php to do your job, I would use require instead of include.
Remove the $conn and the 1's from your 'get' block and, for example:
$getsubject = mysqli_escape_string($_POST["subject"]);
$getmessage = mysqli_escape_string($_POST["message"]);
$getsender = mysqli_escape_string($_POST["sender"]);
$getreceiver = mysqli_escape_string($_POST["receiver"]);
this my code and the problem is that when i am sending email call form id then email is not sending when i remove form id then email is sending
Htmlcode and after html is js code
this my code and the problem is that when i am sending email call form id then email is not sending when i remove form id then email is sending
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="col-sm-5 col-sm-offset-1">
<div class="form-group">
<label>Name *</label>
<input type="text" name="name" class="form-control" required="required">
</div>
<div class="form-group">
<label>Email *</label>
<input type="email" name="email" class="form-control" required="required">
</div>
<div class="form-group">
<label>Phone</label>
<input type="number" class="form-control">
</div>
<div class="form-group">
<label>Company Name</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<label>Subject *</label>
<input type="text" name="subject" class="form-control" required="required">
</div>
<div class="form-group">
<label>Message *</label>
<textarea name="message" id="message" required="required" class="form-control" rows="8"></textarea>
</div>
<div class="form-group">
<button type="submit" name="submit" class="btn btn-primary btn-lg" required="required">Submit Message</button>
</div>
</div>
</form>
--
ajax code
var form = $('#main-contact-form');
form.submit(function(event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
beforeSend: function() {
form.prepend(form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn());
}
}).done(function(data) {
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
});
});
php code
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Thank you for contact us. As early as possible we will contact you '
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'email#email.com';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
This is what your ajax call should look like
$('#main-contact-form').on('submit', function(event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url : $(this).attr('action'),
data : $(this).serialize(),
dataType : 'json',
type : 'POST',
beforeSend : function() {
form.prepend(form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn());
}
}).done(function(data) {
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
});
});
make sure your ajax response which is
function(data)
is really an object variable
because if not this code will not execute because of error of data.message
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
also kindly check your network status check the response of that ajax request
using the dev tools F12
UPDATED ANSWER BELOW
so your response is json but still need to be parse in your javascript.
SOLUTION: Parse your ajax response to make it json object
data = JSON.parse(data);
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
The problem is, that you don't send your form data with the ajax-call.
Like adeneo wrote, you only have to add one line to your code.
data : $(this).serialize(),
Setting the data-type is relevant, because the destination needs to know in which format the data is sent.
Try using the Jquery-POST-function. It looks much better in the code.
Friends I am submitting the form on clicking the submit button and simultaneously i am displaying the just submitted data in the modal.So as soon as i hit the submit button ,the data gets submitted and a modal appears with the data just submitted.Everything is working fine with my code but the only problem that the data does not gets displayed in the modal.
Here is the code for submitting the form-
$("#savep").click(function(e){
e.preventDefault();
formData = $('form.pform').serialize() + '&'
+ encodeURI($(this).attr('name'))
+ '='
+ encodeURI($(this).attr('value'));
$.ajax({
type: "POST",
url: "data1_post.php",
data: formData,
success: function(msg){
$('input[type="text"], textarea').val('');
$('#entrysavedmodal').modal('show');
},
error: function(){
alert("failure");
}
});
});
Here is modal which gets displayed when i click on submit button-
<div id="entrysavedmodal" class="modal fade" role="dialog">
<div class="modal-dialog" style="width:1000px;">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span class="glyphicon glyphicon-plus"></span> Saved Entry</h4>
</div>
<div class="modal-body">
<form class="form-horizontal savedform" id="savedform">
<div class="form-group">
<label class="control-label col-xs-2">Date:</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="datepreview" name="datepreview"
value = "<?php
include('db.php');
$sql = "SELECT `date` FROM tran ORDER BY id DESC limit 1";
$result = mysqli_query($conn,$sql);
$rows = mysqli_fetch_assoc($result);
$date = $rows['date'];
echo $date;
?>" readonly /> //this field does not show anything and none of the fields show any data.
</div>
<label class="control-label col-xs-2">v_no:</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="v_nopreview" name="v_no" autocomplete="off" readonly /> //same problem
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info" id="print" name="print" >Print</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
Date field does not show the date value from database and v_nopreview field also does not show anything.
I have tried to give as much details as possible but in case if you need anything then let me know.Please let me know why the data is not being displayed inside the input fields in modal.
Thanks in advance.
Edited part
Here is the data1_post.php code-
<?php
include('db.php');
$sql = "INSERT INTO `table1` (`date`, `v_no`, `name`,`narration`,`stk_y_n`)
VALUES ( '".$_POST['date']."','".$_POST['v_no']."', '".$_POST['user']."','".$_POST['narration']."', 'No')";
if ($conn->query($sql) === TRUE){
echo "saved";
}
else
{
echo "not saved";
}
?>
As I understand, you expect execution of php code each time after js event. But PHP is a server-side language, it interprets only once, when you request the pages.
So your php code will load some content form DB after refreshing, then you clear input's value before displaying model and as it can't be executed again - you see empty modal.
I recommend you to return saved data from "data1_post.php" and than process it in success callback
UPDATE
if you want to present saved data, your php code would look like the following
include('db.php');
$response = ["success" => false];
$sql = "INSERT INTO `table1` (`date`, `v_no`, `name`,`narration`,`stk_y_n`)
VALUES ( '".$_POST['date']."','".$_POST['v_no']."', '".$_POST['user']."','".$_POST['narration']."', 'No')";
if ($conn->query($sql) === TRUE){
$sql = "SELECT `date` FROM tran ORDER BY id DESC limit 1";
$result = mysqli_query($conn,$sql);
$rows = mysqli_fetch_assoc($result);
$response = ["success" => true, "date" => $rows['date']];
}
header('Content-type: application/json');
echo json_encode($response);
and js
$("#savep").click(function(e){
e.preventDefault();
formData = $('form.pform').serialize() + '&'
+ encodeURI($(this).attr('name'))
+ '='
+ encodeURI($(this).attr('value'));
$.ajax({
type: "POST",
url: "data1_post.php",
data: formData,
success: function(response){
$('input[type="text"], textarea').val('');
if (response.success) {
$('#datepreview').val(response.date);
$('#entrysavedmodal').modal('show');
} else {
alert("failure");
}
},
error: function () {
alert("failure");
}
});
});