I have a form that posts to a php handler which saves the data from the form into a database.
I don't think the save function is the problem. I think its a problem with the $_POST merging the forms data. When I view the sql table, the data is there but all the values are appearing in one column so the variables are being passed from the form correctly.
This is my code:
$name = isset($_POST['name']) ? $_POST['name'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$com_dis = isset($_POST['comment']) ? $_POST['comment'] : '';
$id = isset($_POST['id']) ? $_POST['id'] : '';
$lowercase = strtolower($email);
$image = md5( $lowercase );
try{
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = 'INSERT INTO comments ( com_name, com_email, com_dis, post_id_fk ) VALUES ( :name, :email, :com_dis, :id )';
$st = $conn->prepare ( $sql );
$st->bindValue( ":name", $name, PDO::PARAM_STR );
$st->bindValue( ":email", $email, PDO::PARAM_STR );
$st->bindValue( ":com_dis", $com_dis, PDO::PARAM_STR );
$st->bindValue( ":id", $id, PDO::PARAM_INT );
$st->execute();
$conn = null;
}catch(PDOException $e ){
echo "QUERY FAILED" . $e->getMessage();
};
If I use $id = $_POST['id'] for all the variables, it gets an unidentified index error thrown. When I print $_POST it displays an array where the array is called name and the contents are just the rest of the variables which is the same data stored in the table.
How do I either get the data to save correctly or stop $_POST from merging the variable so they? save in the correct columns?
This is my form:
<form action="#" method="post">
<input type="hidden" name="id" id="id" value="<?php echo $id; ?>"/><br />
<span class="titles">Name</span><span class="star">*</span><br /><input type="text" name="name" id="name"/><br />
<span class="titles">Email</span><span class="star">*</span><br /><input type="text" name="email" id="email"/><br />
Comment<br /><textarea name="comment" id="comment"></textarea><br />
<input type="submit" class="submit" value=" Submit Comment " />
</form>
The form is passed via AJAX:
$(function() {
$(".submit").click(function() {
name = $("#name").val();
var email = $("#email").val();
var comment = $("#comment").val();
var id = $("#id").val();
var dataString = 'name='+ name + 'email=' + email + 'comment=' + comment + 'id=' + id;
if(name=='' || email=='' || comment==''){
alert('Please Give Valid Details');
}
else{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "commentajax.php",
data: dataString,
cache: false,
success: function(html){
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
document.getElementById('email').value='';
document.getElementById('name').value='';
document.getElementById('comment').value='';
$("#name").focus();
$("#flash").hide();
}
});
}
return false;
});
You need to concatenate your data string:
var dataString = 'name='+ name + 'email=' + email + 'comment=' + comment + 'id=' + id;
should be
var dataString = 'name='+ name + '&email=' + email + '&comment=' + comment + '&id=' + id;
Related
I'm currently making a site on Wordpress and need a form to be submitted via ajax is it possible to do this without using Wordpress functions? My current code has no errors and returns a success message without updating the database. I don't understand why it's not working please have a look at my simplified version -
This is the form HTML -
<form action="" method="post" id="formAppointment" name="appointmentform">
<input type="text" name="message_first_name" value="" placeholder="First name" id="appointmentFirstName">
<input type="text" name="message_last_name" value="" placeholder="Last name" id="appointmentLastName">
<input type="tel" name="message_phone" value="" placeholder="Phone" id="appointmentPhone">
<input type="submit" id='appointmentSubmit' class='xAnim' name="submit">
</form>
This is the jquery AJAX -
$("#formAppointment").submit(function(e){
var firstname = $("#appointmentFirstName").val();
var lastname = $('#appointmentLastName').val();
var phone = $('#appointmentPhone').val();
var dataString = 'message_first_name='+ firstname + '&message_last_name=' + lastname + '&message_phone=' + phone;
if(firstname.trim() == "" || lastname.trim() == "" || phone.trim() == ""){
alert('missing information');
e.preventDefault();
} else {
// AJAX Code To submit Form.
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
cache: false,
success: function(result){
console.log(dataString);
alert('success');
}
});
}
return false;
});
This is the php located in process.php
include "config.php";
$patientfirstname = htmlspecialchars($_POST['message_first_name']);
$patientlastname = htmlspecialchars($_POST['message_last_name']);
$patientcontactnumber = htmlspecialchars($_POST['message_phone']);
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO data_table (firstname, lastname, phonenumber ) VALUES ('$patientfirstname', '$patientlastname', '$patientcontactnumber')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
You have to pass data as object, not as dataString.
$("#formAppointment").submit(function(e) {
e.preventDefault();
var firstname = $("#appointmentFirstName").val();
var lastname = $('#appointmentLastName').val();
var phone = $('#appointmentPhone').val();
// var dataString = 'message_first_name=' + firstname + '&message_last_name=' + lastname + '&message_phone=' + phone;
var data = {
"message_first_name": firstname,
"message_last_name": lastname,
"message_phone": phone,
}
if (firstname.trim() == "" || lastname.trim() == "" || phone.trim() == "") {
alert('missing information');
} else {
// AJAX Code To submit Form.
$.ajax({
type: "POST",
url: "process.php",
data: data,
cache: false,
success: function(result) {
console.log(result);
alert('success');
}
});
}
});
NOTE: You are missing email and message in the code. So the line if(firstname.trim() == "" || lastname.trim() == "" || email.trim() == "" || message.trim() == "") may raise some errors and js skips the execution of remaining code
I made a submit form using php and ajax and don't get it why it doesn't work.
My code:
ex1.php
<form id="myForm">
<p> Firstname: <input type="text" name= "firstName"</p>
<p> Lastname<input type="text" name = "lastName" id="lastName"</p>
<p> Password: <input type="password" name= "password" id="myPass"> </p>
<p> Email: <input type="text" name="email" id="myEmail"></p>
<p> Age: <input type="text" name="age" id="myAge"> </p>
<input type="submit" value="submit" id="subm">
</form>
<script>
$(document).ready(function(){
$("#subm").click(function(){
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var password = $("#myPass").val();
var email = $("#myEmail").val();
var age = $("#myAge").val();
var dataString = "Firstname: " + firstName + ", Lastname: " + lastName + ", Email: " + email + " , Password: " + password + "Age: " + age;
$.ajax({
type: "POST",
url: "ex1Ex.php",
data: dataString,
cache: false,
succes: function(result){
alert(result);
}
});
});
});
externFile:
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$password = $_POST['password'];
$email = $_POST['email'];
$age = $_POST['age'];
echo 'jsjsjs';
?>
When I enter the values, after pressing the button, in console it appears
ex1?firstName=a&lastName=ww&password=111&email=a&age=11:59 POST http://local.healix/ex1Ex.php 500 (Internal Server Error)
The problem must be with the file ex1Ex.php, but I don't get it what.Any suggestions?
Change your jquery function like following.
$(document).ready(function () {
$("#subm").click(function (event) {
event.preventDefault();
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var password = $("#myPass").val();
var email = $("#myEmail").val();
var age = $("#myAge").val();
var dataString = "Firstname: " + firstName + ", Lastname: " + lastName + ", Email: " + email + " , Password: " + password + "Age: " + age;
$.ajax({
type: "POST",
url: "ex1Ex.php",
data: dataString,
cache: false,
success: function (result) {
alert(result);
}
});
});
});
I think you have to prevent the default php form submission using event.preventDefault();
Also, please correct the spelling mistake; you have written succes: instead of success:
Pass your data out in an object .ajax will deal with that nicely converting it into the $_POST array. You also dont need to go through interim declared variables, get the data right out of the DOM straight into the data property of the .ajax call
$(document).ready(function(){
$("#subm").click(function(e){
// stop the form submitting in the normal way as well as through AJAX
e.preventDefault();
$.ajax({
type: "POST",
url: "ex1Ex.php",
data: {Firstname: $("#firstName").val(),
Lastname: $("#lastName").val(),
Email: $("#myEmail").val(),
Password: $("#myPass").val(),
Age: $("#myAge").val()
},
//cache: false,
success: function(result){ // spelling corrected
alert(result);
}
});
});
});
Then remember that whatever the name you use for each parameter in the javascript is the name that will be used in the $_POST array so if you use Firstname in javascript you should expect a $_POST['Firstname'] (case sensitive)
<?php
$firstName = $_POST['Firstname'];
$lastName = $_POST['Lastname'];
$password = $_POST['Password'];
$email = $_POST['Email'];
$age = $_POST['Age'];
//echo "I received: $firstName, $lastName, $password, $email, $age";
// or better still while testing
echo json_encode($_POST);
?>
I think the problem with keys which you have used while posting in from ajax request eg. for first name its "Firstname" and you are accessing it with key 'firstName'
php post array is case sensitive
inside my function.php I added new top level admin menu. I added input fields and inside it and put it into html form element.
<form id="prices_form" method="post" action="">
<div style=font-weight:bold;font-size:16px;>Location 1</div>
<input id="location1" name="location1" type="text" />
<input type="hidden" name="count" value="1" />
<div style=font-weight:bold;font-size:16px;>Location 2</div>
<input class="input" id="location2" name="location2" type="text" placeholder="Type something"/>
<div style=font-weight:bold;font-size:16px;>Price(KN)</div>
<input type="number" id="price" name="price" min="0" step="0.01"/><br>
<input id="submit" name="submit" type="submit" value="Save prices" />
</form>
Then I added php where I call ajax via ajax-admin.php and gives user possibility to use ajax. So I want to add input fields into database on submit click.
function ajax_savePrice(){
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$location1 = $_POST['location1'];
$location2 = $_POST['location2'];
$price = $_POST['price'];
$result = $conn->query("SELECT * FROM prices WHERE location1 = '$location1' AND location2='$location2' OR location1 = '$location2' AND location2='$location1'");
$row_count = $result->num_rows;
if ($row_count >= 1) {
echo 'That locations are already inserted. Do you want to update price?';
} else {
$query = "INSERT INTO prices (location1, location2, price) VALUES(?, ?, ?)";
$statement = $conn->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('ssi', $location1, $location2, $price);
if ($statement->execute()) {
print 'Success! ID of last inserted record is : ' . $statement->insert_id . '<br />';
} else {
die('Error : (' . $conn->errno . ') ' . $conn->error);
}
$statement->close();
}
}
function ajax_savePrice_init(){
wp_register_script('ajax-savePrice-script', get_template_directory_uri() . '/ajax-savePrice-script.js', array('jquery') );
wp_enqueue_script('ajax-savePrice-script');
wp_localize_script( 'ajax-savePrice-script', 'ajax_savePrice_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => home_url(),
'loadingmessage' => __('Sending data, please wait...')
));
// Enable the user with no privileges to run ajax_login() in AJAX
add_action( 'wp_ajax_nopriv_ajaxsavePrice', 'ajaxsavePrice' );
add_action( 'wp_ajax_ajaxsavePrice', 'ajaxsavePrice' );
}
add_action('init', 'ajax_savePrice_init');
And I made .js file to proccess ajax request:
jQuery(document).ready(function($) {
// Perform AJAX login on form submit
$('#prices_form').on('submit', function(e){
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_savePrice_object.ajaxurl,
data: {
'action': 'ajaxsavePrice',
'location1': $('#location1').val(),
'location2': $('#location2').val(),
'price': $('#price').val() },
success: function(data){
$('#prices_form').hide();
}
});
e.preventDefault();
});
});
Page reloads and nothing happens...
Any hint?
EDIT:
I succeed to call ajax and added 3 echo-s to my php so I can get response via server.
$result = $conn->query("SELECT * FROM prices WHERE location1 = '$location1' AND location2='$location2' OR location1 = '$location2' AND location2='$location1'");
$row_count = $result->num_rows;
if ($row_count >= 1) {
// echo 'That locations are already inserted. Do you want to update price?';
echo 'exist';
} else {
$query = "INSERT INTO prices (location1, location2, price) VALUES(?, ?, ?)";
$statement = $conn->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('ssi', $location1, $location2, $price);
if ($statement->execute()) {
// print 'Success! ID of last inserted record is : ' . $statement->insert_id . '<br />';
echo 'yes';
} else {
//die('Error : (' . $conn->errno . ') ' . $conn->error);
echo 'no';
}
$statement->close();
}
Now in my js:
location1=$("#location1").val();
location2=$("#location2").val();
price=$("#price").val();
data: "location1="+location1+"location2="+location2+"price="+price,
success: function(html){
if(html==='exist')
{
$("#prices_form").fadeOut("normal");
}
else
{
$("#aaa").fadeOut("normal");
}
},
beforeSend:function()
{
}
});
return false;
});
So whatever I enter in my input fields and post to php I got this else part. I tried with all 3 states that php can return to js but always else get executed.
Any hint now?
Name your form in html as -
<form id="prices_form" name="pricesForm" method="post" action="">
Try JSON.stringify() data before sending with the AJAX like below -
var data = JSON.stringify({
action: 'ajaxsavePrice',
location1: $('#location1').val(),
location2: $('#location2').val(),
price: $('#price').val()
});
And then replace your ajax call on form submit as below-
$('form.pricesForm').on('submit', function(e){
e.preventDefault();
$.ajax({
method: 'POST',
dataType: 'json',
url: ajax_savePrice_object.ajaxurl, // also check this if it returns the correct url
data: data,
success: function(res){
$('#prices_form').hide();
}
});
});
Hope this helps.
I have a raw commenting system where one can post comments. When the post button is clicked, an AJAX request is sent to the php file (process.php). In process.php, there's a while loop which retrieves all the comments and sends back to the index.php file as data.
Problem is When I post two comments, the comment which I posted before the current one is shown in the div specified!
index.php
if(isset($_POST['text'])){
if(!empty($_POST['text'])){
$text = $_POST['text'];
$query = mysql_query("INSERT INTO `test` VALUES('', '$text')");
}
}
?>
<form action="" class="comment_post" method="POST">
<input type="text" name="text">
<input type="submit" value="POST">
</form>
<hr>
<div id="comments">
</div>
<script>
$('form.comment_post').on('submit', function(){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value= that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data
});
return false;
});
$('input[type=submit]').click(function(){
$.ajax({
type : 'POST',
url : 'process.php',
data : {action: 'retrieve'},
success : function(data){
$('#comments').html(data);
}
});
});
</script>
process.php
if(isset($_POST['action']) && !empty($_POST['action'])){
$action = $_POST['action'];
if($action == 'retrieve'){
$data = mysql_query("SELECT * FROM `test`");
if(mysql_num_rows($data) != 0){
while($row = mysql_fetch_assoc($data)){
$text = $row['text'];
echo '<div class="each_comment">'.$text.'</div><br>';
}
} else {
echo 'No data to retrieve';
}
}
}
?>
first extend your database by a column "dateCreated"
then use this insert code:
$query = mysql_query("INSERT INTO `test`,`dateCreated` VALUES('', '$text','NOW()')");
in your process.php use the code like this:
$data = mysql_query("SELECT * FROM `test` ORDER BY `dateCreated` DESC ");
I'm having a perplexing problem--I'm managing to get one value, extracted from a text box, successfully inserted into my table but the other (also from a text box) is not going in. Before the AJAX call, I've alerted my datastring to make sure both values are correct, and they are. When I look in the database, however, only the name value is entered and email is blank.
HTML:
<div id="basic-modal-content">
<h3>Please Alert me when this is Available</h3>
<p>Your Name: <input type="text" id="alert_name"/></p>
<p>Email Address: <input type="text" id="alert_email"/></p>
<button id="alert_submit">Submit</button>
</div>
Javascript:
$('#alert_submit').click(function(){
var datastring = 'name='+ $('#alert_name').val() + '&email=' + $('#alert_email').val();
alert(datastring);
$.ajax({
type: "POST",
url: "process_email.php",
data: datastring,
success: function(data) {
}
});
alert ("We've received your request and will alert you once the directory is available. Thank you.");
$.modal.close();
});
PHP:
$name = $_POST['name'];
$email = $_POST['email'];
try {
$conn = new PDO('mysql:host=blah;dbname=blah', '-', '-');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("INSERT INTO email_alerts(name, email) VALUES(':name, :email)");
$stmt->execute(array('name' => $name, 'email' => $email));
//$affected_rows = $stmt->rowCount();
$conn = null;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
$conn = null;
}
try this code please
$('#alert_submit').click(function(){
$.ajax({
type: "POST",
url: "process_email.php?name="+$('#alert_name').val() +"&email="+ $('#alert_email').val(),
success: function(data) {
}
});
alert ("We've received your request and will alert you once the directory is available. Thank you.");
$.modal.close();
});