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();
});
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 am using the jquery validate plugin to send data from form to mysql database. the validation works well but after the button is clicked, the data isnt submitted to the database. but no response or error is generated. i think the error is in ajax part.
The below file is db_connect.php, it executes .both echo are working
<?php
echo "hello";
/* Database connection start */
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "upscfpyl_test";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
echo "hi";
//exit();
}
else{
echo "hi2";
}
?>
index.html - some code given below the div error is displayed but the content in it is hi2. I dont know why it has the content hi2. I had used echo "hi2"; in db_connect.php [code given at the end] but did not return it to ajax.
<div id="error"></div>
<form id="signupForm" method="post" action="#">
<input type="submit" class="btn btn-primary" value="Sign Up" id="button1" name="btn-save">
</form>
Ajax part :
$.ajax({
type: 'POST',
dataType: 'text',
url: 'js/php/register.php',
data: {
name1: name,
email1: email,
mobile1: mobile,
gender1: gender,
password1: passwords
},
beforeSend: function() {
$("#error").fadeOut();
document.getElementById("button1").disabled = true; // this works
},
success : function(response) {
if(response==1)
{
$("#error").fadeIn(1000, function()
{
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> Sorry email already taken !</div>');
document.getElementById("button1").disabled = false;
});
}
else if(response=="registered")
{
window.location = "dashboard.html";
}
else {
$("#error").fadeIn(1000, function()
{
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+response+' !</div>');
document.getElementById("button1").disabled = false;
});
}
}
});
register.php - to submit to database
<?php
include_once("db_connect.php");
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name=test_input($_POST['name1']); // Fetching Values from URL.
$email=test_input($_POST['email1']);
$gender=test_input($_POST['gender1']);
$mobile=test_input($_POST['mobile1']);
$password= test_input(sha1($_POST['password1'])); // Password Encryption, If you like you can also leave sha1.
echo "pranav"; // these dont work
echo $name+$email+$gender; // this also doesnt work
// Check if e-mail address syntax is valid or not
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Sanitizing email(Remove unexpected symbol like <,>,?,#,!, etc.)
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo $email;
}
else{
$result = mysql_query("SELECT * FROM users WHERE email='$email'");
$data = mysql_num_rows($result);
if(($data)==0){
$query = mysql_query("insert into users(name, email, password, gender, mobile) values ('$name', '$email', '$password', '$gender', '$mobile')"); // Insert query
if($query){
echo "registered";
}
else
{
echo "Error....!!";
}
}
else
{
echo "1";
}
}
}
?>
You can open your browser console for checking logs.
if the dataType is JSON, it means that your server is returning a json. But this is not the case see https://api.jquery.com/jQuery.ajax/
Try this code for your data serialization:
$("#your_form_id").submit(function(e){
e.preventDefault();
var datas = $(this).serialize();
$.ajax({
data: datas,
// Or this
data: 'key1=' + value1 + '&key2=' + value2 + '&key3=' + value3,
// to match your server response
dataType: "text"
// Error warning
.fail(function() {
alert( "error" );
})
});
});
With the validation code of the form, we could better help you
Have a problem to call my server.php to add some values into db.
server.php:
<?php
$db = new PDO('mysql:host=localhost;dbname=test','user','password');
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$stmt = $db->prepare("INSERT INTO user (name,email,phone,address) VALUES(?,?,?,?)");
$stmt->bindParam(1,$name);
$stmt->bindParam(2,$email);
$stmt->bindParam(3,$phone);
$stmt->bindParam(4,$address);
$stmt->execute();
echo "data saved";
?>
Calling the server.php directly, the data will be saved.
But from my Html/Ajax code it will not:
<script>
function saveData(){
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var address = $('#address').val();
$.ajax({
type: "POST",
url: "server.php",
data: "name=" +name+"&email="+email+"&phone="+phone+"&address="+address,
}).done(function(data){
alert('success');
$('#result').html("<br/><div> class='alert alert-info'>" + data +"</div>");
)};
return false;
</script>
The alert('success') won't be called also #result div isn't filled.
Whats wrong with this 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
If I click on submit button using only php, data are recorded in mysql.
Through ajax _autosave.php only update works. Insert does not work. going crazy.... can not understand
ajax code in first.php
<script type="text/javascript">
$(document).ready(function() {
setInterval(function (){
var date_day1=$("#date_day1").val();
var amount1=$("#amount1").val();
DATA = 'date_day1=' + date_day1 + '&amount1=' + amount1;
$.ajax({
type: "POST",
url: "_autosave.php",
data: DATA,
cache: false,
/*success: function(){
$(".done").show().html("Saved as a draft!");
}*/
});
setTimeout(function(){
$(".done").hide();
}, 1000);// 15 seconds
}, 3000);// 1 minute
});
</script>
HTML input
<td><input type="text" name="date_day1" id="date_day1" value="<?php echo $_POST['date_day1']?>" size="1"></td>
<td><input type="text" name="amount1" id="amount1" value="<?php echo $_POST['amount1']?>" size="5"></td>
Part of php code that is identical in first.php and _autosave.php
$date_day1 = $_POST['date_day1'];
$amount1 = $_POST['amount1'];
if ($stmt = mysqli_prepare($mysqli, "SELECT RecordDay FROM 2_1_journal WHERE RecordDay = ? ")) {
$stmt->bind_param('s', $date_day1);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($RecordDay);
$stmt->fetch();
//echo $RecordDay .' $RecordDay<br>';
}
if ($RecordDay == $date_day1) {
if ($stmt = mysqli_prepare($mysqli, "UPDATE 2_1_journal SET Amount = ? WHERE RecordDay = ? ") ) {
$stmt->bind_param( 'ds', $amount1 , $date_day1 );
$stmt->execute();
/*echo $date_day1 .' date_day1<br>';
echo $amount1 .' amount1<br>';*/
}
}
else {
if ($stmt = mysqli_prepare($mysqli, "insert into 2_1_journal
(RecordDay, Amount, DebitAccount, CreditAccount)
values(?,?,?,? )")) {
$stmt->bind_param('sdss', $date_day1, $amount1, $debit1, $credit1 );
$stmt->execute(); //execute above insertion
}
}
Update works in both files (called from both files). Insert works only if called without ajax. What is wrong?
Update
Finally found what was wrong. If $_POST is not set (not send), nothing is recorded in mysql. However no error message after execution. Simply need to remember that all variables here $stmt->bind_param('sdss', $date_day1, $amount1, $debit1, $credit1 ); must exist.
The data syntax might be the reason, use this format:
data: { key1: "value1", key2: "value2" }
See this example from: http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
so, for your case try:
$.ajax({
type: "POST",
url: "_autosave.php",
data: {date_day1:$("#date_day1").val(), amount1: $("#amount1").val()},
cache: false,
});
in insert you binding 5 parameters instead of 4