Wordpress ajax form submission without using wordpress functions possible? - php

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

Related

AJAX : PHP login ajax does'nt work

I have a login form using ajax and a php code. The issue is that is always returns an error instead of logging me into the system. I have spent days trying to find the error but I can't.
php :
<?php
include 'db.php';
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$cek = mysqli_query($conn, "SELECT * FROM user_csr WHERE email='$email' AND csr_pwd='$password'");
if(mysqli_num_rows($cek)>0)
{
echo 'true';
}
else
{
echo 'false';
}
?>
ajax :
function ceklogin(){
var email = document.getElementById('mail').value;
var password = document.getElementById('pass').value;
$.ajax({
url: 'tes.php',
method: 'POST',
data: {email: email, password: password},
success: function(html) {
if(html == 'true')
{
alert("login success");
}
else
{
alert("login failed");
}
}
});
}
<form>
<input type="email" name="email" id="mail" required>
<input type="password" name="password" id="pass" required>
<button type="submit" class="w3ls-cart" onclick="ceklogin()">Sign In</button>
</form>
the result of an alert is 'login failed'. but email and passwords are in accordance with the database.Hope anyone can help me out on this one, thanks in advance.
This should work. Just make sure you have a DIV as identified below to show your result.
function ceklogin() {
var email = document.getElementById('mail').value;
var password = document.getElementById('pass').value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("resultDiv").innerHTML = this.responseText;
}
};
var sentInfo = "email=" + email + "&password=" + password;
xhttp.open("POST", "YourPHPFileHERE.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(sentInfo);
}
you should try adding "===" in your if condition.
` if(html === 'true')
{
alert("login success");
}
else
{
alert("login failed");
}`

getting data using ajax php jquery

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

jQuery AJAX php Login Not passing data properly

I get a Failure object Object notice. I have looked at multiple examples and still can't figure out the error. I believe my AJAX is not set up properly. The PHP should be good to go, I have a local database and use jQuery with AJAX to handle the request and the response. The page should redirect to the dashboard.php when I have success with logging in.
Here is the form:
<div class="row">
<div class="col-xs-12 text-center">
<h1 class="text_white bad_login">
Log In Please
</h1>
</div>
<div class="col-xs-12 col-sm-4 col-sm-offset-4">
<form class="text_white" method="post" action="/login.php">
<div class="form-group">
<label for="username">User Name:</label>
<input name="username" type="text" class="form-control" id="username" placeholder="User Name">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input name="password" type="password" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-default" id="login" name="login">Log In</button>
</form>
</div>
</div>
Here is the PHP:
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// grab form fields and save as php variables
$username = '';
$password = '';
// if (isset($_POST['name'], $_POST['passphrase'])){
// $username = $_POST['name'];
// echo $username;
//
// $password = $_POST['pass'];
// echo $password;
// }
// else {
// $username = null;
// $password = null;
// }
if (isset($_POST['password'])){
$password = $_POST['password'];
//echo $password;
}
else {
$password = null;
}
if (isset($_POST['username'])){
$username = $_POST['username'];
//echo $username;
}
else {
$username = null;
}
// create query to run on database
$qry = "SELECT username, password FROM user WHERE username='".$username. "' AND password='".$password. "' ";
$result = mysqli_query($conn, $qry) or die(mysqli_error($conn));
$num_row = mysqli_num_rows($result);
$row = mysqli_fetch_assoc($result);
// check to see if it is only 1 match and then save that information to the session for later use
if( $num_row == 1 ) {
$_SESSION['username'] = $row['username'];
//echo $_SESSION['username'];
$_SESSION['password'] = $row['password'];
//echo $_SESSION['password'];
}
else {
echo ' FALSE! ';
}
// $result->json_encode($result);
echo json_encode($result);
}
//close the connection
$conn->close();
Here is the AJAX which i believe contains the error:
//jQuery(document).ready(function($){
// $('#login').click(function(event){
// event.preventDefault();
// var username = $('#username').val();
// var password = $('#password').val();
//
// if ( $('#username').val() === '' || $('#password').val() === '') {
// $('.bad_login').text('PLEASE ENTER BOTH USERNAME AND PASSWORD');
// }
//
// $.ajax({
// type: 'POST',
// url: '/ChurchCheckIn/login.php',
// dataType: 'json',
// data: 'username='+username+'&password='+password,
//// data: { username : username, password : password},
// success: function(data){
//// if(data === 'true') {
// window.location='/ChurchCheckIn/dashboard.php';
// console.log('if true.... ' + data);
//// }
//// else {
//// $('.bad_login').text('WRONG USERNAME OR PASSWORD TRY AGAIN PLEASE...');
//// console.log('bad html test for other stuff' + data);
//// }
// },
//// fail: function(data){
//// jQuery.parseJSON(data);
//// console.log('failure' + data);
//// $('.bad_login').text('WRONG USERNAME OR PASSWORD TRY AGAIN PLEASE...');
//// },
//// done: function() {
//// console.log('success' + data);
//// window.location='/ChurchCheckIn/dashboard.php';
//// },
// beforeSend:function() {
// $('.bad_login').text('Loading....');
// }
// });
// return false;
// });
//});
jQuery(document).ready(function ($) {
$('#login').click(function (event) {
event.preventDefault();
var username = $('#username').val();
var password = $('#password').val();
var response = {};
if ($('#username').val() === '' || $('#password').val() === '') {
$('.bad_login').text('PLEASE ENTER BOTH USERNAME AND PASSWORD');
}
var request = $.ajax({
url: '/ChurchCheckIn/login.php',
type: 'POST',
data: 'username='+username+'&password='+password,
dataType: 'json'
});
request.done(function (data) {
response = $.parseJSON(data);
console.log(response);
if (response.success == 'true') {
console.log('success' + data);
window.location = '/ChurchCheckIn/dashboard.php';
} else {
console.log('data came back false');
}
});
request.fail(function (data) {
console.log('failure' + data);
$('.bad_login').text('WRONG USERNAME OR PASSWORD TRY AGAIN PLEASE...');
});
});
});
I have tried multiple ways, i believe one sends an object and the other expects to receive a string. I don't believe I am way offbase, I even made sure to use the newest practices. mysqli in my php and the newer form of success with my jQuery.
Try using data as Javascript object
var request = $.ajax({
url: '/ChurchCheckIn/login.php',
type: 'POST',
data: {username: username, password: password}
dataType: 'json'
});
if that didn't work, use JSON.stringify around the data object, but it should work because jQuery converts the data object automatically.
I believe in a row:
if (response.success == 'true') {
}
there is no element success try check if response variable is not empty.

mySQLi is breaking AJAX request?

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')");

Trouble getting one item into MySQL db

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();
});

Categories