I'm attempting an AJAX call via a form submission
FORM:
<form action="subscribe.php" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="Enter Email">
<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
<p class="error"></p>
</form>
JAVASCRIPT:
var $form = $('#mc-embedded-subscribe-form'),
timer;
if($form.length > 0) {
$('#mc-embedded-subscribe').on('click', function(e){
var hasError = false,
emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/,
email = $("input.email").val(),
error = $('.error');
error.is(':visible') ? error.fadeOut("slow", checkEmail) : checkEmail();
function checkEmail() {
if (email == "") {
error.text('Enter an email').fadeIn();
$("#mce-EMAIL").focus();
hasError = true;
} else if(!emailReg.test(email)) {
$("#mce-EMAIL").focus();
error.text('Enter a valid email').fadeIn();
hasError = true;
}
}
if(hasError == true) { return false; }
$.ajax({
url: $form.attr('action'),
type: 'post',
data: {
email: $('#mce-EMAIL').val()
},
success: function(data) {
if(data === '1') {
console.log(data);
console.log('success');
launchSubscriptionPopup();
} else {
error.text('There was an error');
}
},
error: function(data) {
console.log(data);
}
});
e.preventDefault();
});
}
to subscribe.php
SUBSCRIBE.PHP:
$email = $_REQUEST['email'];
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
// $insertdate = date("Y-m-d H:i:s");
// $db = db_connect();
// $query = $db->query("INSERT INTO newsletter_coupon_codes VALUES ('$insertdate', '$email', '1')");
echo 1;
}
die();
db_connect():
function db_connect() {
include('/home/includes/dbconnect.php'); // holds the blow variables
# $db = new mysqli($dbhost, $dbuser, $dbpw, $dbname);
if (!$db) {
throw new Exception('Could not connect to database server');
}
else {
$db->autocommit(TRUE);
return $db;
}
}
All of this works fine. The AJAX call is made to subscribe.php and 1 is returned to the AJAX call.
Now I want to record the email and date to a database. If I un-comment the two DB lines in the subscribe.php, the AJAX call fails. Nothing is returned. The DB entry is created, but no 1 is returned, so I can't proceed with JavaScript calls.
If I view the subscribe.php stand-alone, it also works, just fine. It adds the DB entry and echos a 1.
Is there any reason why adding the DB layer to this would cause the subscribe.php to not return the value 1 to my AJAX request?
Probably you have a white space out their
Then just do trim
if($.trim(data) === '1')
and this should work
Your query is invalid due to using "" everywhere
$query = $db->query("INSERT INTO newsletter_coupon_codes VALUES ('" . date("Y-m-d H:i:s") . "', '" . $email . "', '1')");
becomes
INSERT INTO newsletter_coupon_codes VALUES ('Y-m-d H:i:s'
Its failing silently as there's no fail trap and so the ajax is returning blank check your error_log and you'll see the error in there.
instead do date as mysql date insert since its not a user input just a now so do
$query = $db->query("INSERT INTO newsletter_coupon_codes VALUES ('NOW()', '$email', '1')");
or prepare your date outside of the query
$insertdate = date("Y-m-d H:i:s");
$query = $db->query("INSERT INTO newsletter_coupon_codes VALUES ('$insertdate', '$email', '1')");
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
After i searched for this solution on this site, nothing i found. Here is basic php code, just for testing.
index.php
<input type="checkbox" name="chk" id="chk" value="1" />
<button type="button" name="" id="submit">TEST</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var check = $('#chk').val();
$.ajax({
url:"qry.php",
method:"POST",
data: {check:check},
success:function(data)
{
//alert(data);
window.location.reload();
}
});
});
});
</script>
qry.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "check";
// Create connection
$connect = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
if($_REQUEST['chk'] == true){
$stok = '1';
}
elseif ($_REQUEST['chk'] == false) {
$stok = '0';
}
$query = "INSERT INTO test(checked) VALUES('$stok')";
$result = mysqli_query($connect, $query);
if ($result === TRUE) {
echo "Zahtev je uspešno poslat!";
} else {
echo "Error: " . $query . "<br>" . $connect->error;
}
?>
How to set checkbox checked true or false into mysql and then echo if in html? It's always set to 0 in mysql boolen.
<input type="hidden" name="chk" id="chk" value="1" <?php if ($checked == '1') {echo 'checked';} else {} ?>/>
I tried everything from this site and nothing works.
Try this Jquery. This will get rid of the always value 1 problem you're having. What this code does is when you click on the "submit" button it check the status of your check box. If the check box is checked then the code will take the checked check box value and send that in the ajax function if it's not checked then the value 0 get assigned and that will be sent using the ajax.
Doing this will reduce the work has to be done by the back end PHP. I also made some changes to your PHP code as well.
$(document).ready(function() {
$(document).on('click', '#submit', function() {
if ($("#chk").is(":checked")) {
var chk = $('#chk').val();
}else{
chk = 0;
}
$.ajax({
url: "qry.php",
method: "POST",
data: {
check: chk
},
success: function(data) {
//alert(data);
window.location.reload();
}
});
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="chk" id="chk" value="1" />
<button type="button" name="" id="submit">TEST</button>
You will see that the way I'm inserting the data is a bit different from the way you have done. I'm using mysqli_ prepared statements which makes SQL injection a hard to do.
$query = $connect -> prepare("INSERT INTO test(checked) VALUES (?)";
$query -> bind_param("i", $_REQUEST['check']);
if ($query -> execute()) {
echo "Zahtev je uspešno poslat!";
} else {
echo "Error: " . $query . "<br>" . $connect->error;
}
jsFiddle if you want to test it.
You write the value into check, but read it back from $_REQUEST['chk']. That won't work. Change that to $_REQUEST['check'].
You are using val() to get the state of the checkbox, you should use checked.
Also, you are possibly open to SQL injection, start using prepared statements.
Add another line while sending the AJAX request.
While sending the value of checkbox, send 1 or 0.
It will reduce our work at PHP end.
So, the code should be:
var check = $('#chk').is(":checked");
check = (check) ? 1 : 0;
Final code should be:
<input type="checkbox" name="chk" id="chk" value="1" />
<button type="button" name="" id="submit">TEST</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var check = $('#chk').val();
check = (check) ? 1 : 0;
$.ajax({
url:"qry.php",
method:"POST",
data: {check:check},
success:function(data) {
//alert(data);
window.location.reload();
}
});
});
});
</script>
And PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "check";
// Create connection
$connect = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
$stok = $_REQUEST['chk'];
$query = "INSERT INTO test(checked) VALUES('$stok')";
$result = mysqli_query($connect, $query);
if ($result === TRUE) {
echo "Zahtev je uspešno poslat!";
}
else {
echo "Error: " . $query . "<br>" . $connect->error;
}
?>
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.
So, I'm new to using PHP but want to add whatever a user enters into this form into a database.
However, I'm getting an error for each index of name, role, and wage. It seems that it isn't picking that up.
HTML:
<form id="input" name="input" action="employees.php" method="post">
<div id="boxes">
<input type="text" name="name" placeholder="Input" class="name" required><br/>
<input type="text" name="role" placeholder="Role" class="role" required><br/>
<input type="number" step="any" name="wage" placeholder="Wage" class="wage" required>
<br />
<br />
</div>
<button type="submit" onsubmit="return ajaxFunction()" class="button">Submit</button>
<button type="reset" class="button">Reset</button>
</form>
PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "employees";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br/>";
$name2 = $_POST['name'];
$role2 = $_POST['role'];
$wage2 = $_POST['wage'];
if (mysql_query("INSERT INTO employees VALUES ('$name2', '$role2', '$wage2')"))
echo "Successfully inserted";
else
echo "Insertion failed";
$conn->close();
?>
I also have some javascript set up to catch the values of each field and to send them to the PHP file. I'm probably doing something very wrong... but anyway here's the JS:
function ajaxFunction() {
var name = $('.name').val();
var role = $('.role').val();
var wage = $('.wage').val();
var dataString = '&name1' + name + '&role1' + role + '&wage1' + wage;
$.post('employees.php', {name1:name, role1:role, wage1:wage}, function(data){
$('#main').html(data);
});
if (name == '' || role == '' || wage == '') {
alert("Please fill in all fields.");
} else {
$.ajax({
type: "POST",
url: "employees.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
}
In your Ajax dataString is
var dataString = '&name1' + name + '&role1' + role + '&wage1' + wage;
But in your PHP
$name2 = $_POST['name'];
$role2 = $_POST['role'];
$wage2 = $_POST['wage'];
Should be
$name2 = $_POST['name1'];
$role2 = $_POST['role1'];
$wage2 = $_POST['wage1'];
The undefined error means that your data is not found, this is happening because your php is looking for a POST index of "name" whereas javascript is sending "name1".
There are a few issues with the setup that can be greatly improved here.
Firstly the onsubmit needs moved into the form tag.
<form onsubmit="return isFormValid()" id="input" name="input" action="employees.php" method="post">
Secondly you don't actually need to actually make an ajax request from Javascript because the return on submit is saying if the returned value of the js function is true submit the form otherwise don't. Therefore we just need to return a true or false based on form validation.
Here is the updated JS function.
function isFormValid(){
var name = $('.name').val(),
role = $('.role').val(),
wage = $('.wage').val(),
data = [name, role, wage],
isValid = true;
data.forEach(function(el){
if( isValid && !el.trim() ){
alert("Please fill in all fields.");
isValid = false;
}
});
return isValid;
}
There are also some security concerns regarding MySQL injection from how the form data is being entered into the database without being escaped.
A quick solution is to add a basic PHP method to escape the strings before hitting the database.
// add at the top of your php file
function escape($value){
return mysql_real_escape_string($value);
}
// then update your variables
$name2 = escape($_POST['name']);
$role2 = escape($_POST['role']);
$wage2 = escape($_POST['wage']);
You can read more about mysql injection and how to prevent it here:
http://php.net/manual/en/function.mysql-real-escape-string.php
EDIT ---------------------------
I've simplified the JS and removed the token issue you were having. If you add more input fields you can simply add a new variable to store it's value and add that variable name to the data array.
I've also updated the function name in both the JS and the html as it relates more to the purpose of the task.
Here is a working example:
http://codepen.io/davidbattersby/pen/LVabQe
obviously the php file doesn't exist so will point to a blank page if submission passes validation, it will alert and not send if invalid.