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
Related
I try to make an authentication using angualrJS and php. I tested it by console.log, when the password is incorrect I get error message, and when the password is correct I don't get anything, in this case, I want to be riderected to other view, how can I do please:
app.js
app.controller('loginCtrl', function($scope, $location,$state,$http,$window){
$scope.submit = function()
{
data = {
'NomClient' : $scope.NomClient,
'mdp' : $scope.mdp
};
$http.post('http://localhost/deb/login.php', data)
.success(function(data, status, headers, config)
{
// $window.location.href = '#/admin';
console.log(data);
})
.error(function(data, status, headers, config)
{
console.log('error');
});
}
});
login.php
<?php
$data = json_decode(file_get_contents("php://input"));
$connect = mysqli_connect("localhost", "root", "", "test");
if(count($data) > 0)
{
$NomClient=mysqli_real_escape_string($connect, $data->NomClient);
$mdp=mysqli_real_escape_string($connect, $data->mdp);
$query = 'SELECT * FROM `client` WHERE NomClient = "'.$NomClient.'" AND mdp= "'.$mdp.'"';
$q = mysqli_query($connect , $query);
if(mysqli_num_rows($q) > 0 )
{
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $NomClient;
}
else
{
echo 'The username or password are incorrect!';
}
}
?>
As you see, I have a comment line in app.js: // $window.location.href = '#/admin'; I put it as comment because when I put it, it redirects me to admin view however the password is incorrect.
Thanks in advance
With AngularJS you can use the $location service
$Location - Documentation
Try using:
$location.path("your new path here")
For an example: please refer to the following answer to another post:
https://stackoverflow.com/a/14387747/7018180
Try this code in login.php
if(mysqli_num_rows($q) > 0 )
{
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $NomClient;
$result['code'] = 200;
$result['message'] ='Logged In';
}
else
{
$result['code'] = 603;
$result['message'] ='The username or password are incorrect!';
}
$resultstring = json_encode($result);
$resultstring = str_replace("null",'""',$resultstring);
echo $resultstring ;
die;
And check result code in js if it is 200 then it will be in succes other wise in error.
Change .success\.error to .then(), Change your code like :
$http.post('http://localhost/deb/login.php', data).then(function(response) {
console.log(response.data);
$window.location.href = '#/admin';
}, function(error) {
console.log('error');
});
.success is a property of $http service so if there would be some value in data variable the $window.location is eventually going to get called.. so to improve that you can use if condition inside $http service which would check the passed username and password with the response that it would get from the service and then in if condition you can redirect it to another page.
app.service('AuthenticationService', function ($http, $window){
this.login = function (username, password) {
return $http({
url: 'http://localhost/deb/login.php',
method: 'POST',
params: {
NomClient : username,
mdp : password
}
})
};
});
app.controller('loginCtrl', function ($scope, $state, $http, $window, AuthenticationService, $remember) {
$scope.submit = function()
{
AuthenticationService.login($scope.NomClient,$scope.mdp)
.then(function(response) {
if (response.data.NomClient == $scope.NomClient && response.data.mdp == $scope.mdp)
{
$state.go('application.home');
}
else {
alert('Credentials do not match our records. Please try again.');
}
})
}
});
and instead of $window.location you can use $state.go functionality of angularJS. It would redirect your page to the specific state that would be mentioned and it would look for that state in route file and would execute that state along with its templateUrl and controller.
Here's properly working code for your question tested properly. if you are still looking for a solution
app.js
app.controller('loginCtrl', function ($scope, $http,$state) {
$scope.submit = function ()
{
$scope.data = {
username: $scope.username,
password: $scope.password
}
$http.post('http://localhost/HTML5Application/public_html/login.php', {serviceData: $scope.data})
.success(function (data) {
alert(data);
$state.go('newState');
})
.error(function (data) {
alert("problem with service call");
});
};
});
login.php
$data = json_decode(file_get_contents("php://input"));
$connect = mysqli_connect("localhost", "root", "", "embroidery");
if (count($data) > 0) {
$username = mysqli_real_escape_string($connect, $data->serviceData->username);
$password = mysqli_real_escape_string($connect, $data->serviceData->password);
$query = 'SELECT * FROM `client` WHERE username = "' . $username . '" AND password= "' . $password . '"';
$q = mysqli_query($connect, $query);
if (mysqli_num_rows($q) > 0) {
$_SESSION["logged_in"] = true;
$_SESSION["name"] = $username;
echo $_SESSION["name"];
} else {
echo 'The username or password are incorrect!';
}
}
?>
login.html
<div class="list list-inset" ng-controller="loginCtrl">
<label class="item item-input">
<input type="text" placeholder="Username" required="" ng-model="username">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="password">
</label>
<button class="button button-block button-positive" name="submit" ng-click="submit()">Login</button>
</div>
Thank you all, this is the solution of this question, solved by "Mr_Perfect":
we have just to add a condittion in suceess:
$http.post('http://localhost/deb/login.php', data)
.success(function(data, status, headers, config,result)
{
console.log(data);
if(data.code == 200){
$state.go('admin');
}
})
.error(function(data, status, headers, config, rsult)
{
console.log('error');
});
Thanks to you all
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.
I'm trying to do a really simple login system using php. I have two files at the moment: index.php and verifyCredentials.php
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test Site</title>
</head>
<body>
<h1>Welcome to My Test Homepage!</h1>
<?php if ($_SESSION['logged_in'] != "true") : ?>
<form method="post" action="verifyCredentials.php">
Username: <input type="text" name="username" value=""/><br>
Password: <input type="password" name="password" value=""/><br>
<input type="submit" name="submit" value="Submit"/><br>
</form>
<?php else : ?>
<h2>You're logged in! :)</h2>
<?php endif ?>
<?php if($_GET['verferr']==1){echo "<b>Login failed: incorrect username or password.</b>";} ?>
</body>
</html>
verifyCredentials.php
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "myusername" && $password == "letmein")
{
$_SESSION['logged_in'] = "true";
header("Location: index.php");
exit;
}
else
{
$loginfailed_param = "?verferr=1";
header("Location: index.php" . $loginfailed_param);
exit;
}
?>
I've successfully made it so that if your username/password were incorrect (i.e. not equal to myusername and letmein), then it redirects to the login page and echo's an error message under the form.
I'm trying to make it so that when they do verify that the form on index.php, the form disappears and is replaced with some success text. But, when I type in myusername and letmein, it just redirects to the login without an error and the form still showing.
From the research I've done, I'm required to use the if-else php structure as shown in my index.php file if I want to have html in between my php nodes, but am I doing this incorrectly?
Can anyone tell what I am doing wrong here?
PHP Sessions require that you call session_start() at the top of every page where you use $_SESSION. I don't see it in your example.
If you are going to use sessions to store data make sure you have session_start(); at the top of every page you call. Otherwise it won't read in the session identifier and will assume you want to start a new one.
So at the top of your index.php and verifyCredentials.php add the command. But make sure you have it as the first line of code on the page. You will then need to add it to any page that is directly requested.
For example, if you have index.php and it includes form.php and nav.php, then only index.php will need the session_start(), but if you have a link to form_processing.php, then form_processing.php will need to have session_start() as well.
Aww, you accepted right as I had this ready. :(
Here is what you need to use. anyway..
(Also, you should use jQuery for better transitional effects, see below)
<?php
session_start();
$args = array(
'username' => FILTER_SANITIZE_SPECIAL_CHARS,
'password' => FILTER_SANITIZE_SPECIAL_CHARS);
$post = filter_input_array(INPUT_POST, $args);
if ($post) {
$username = $post['username'];
$password = $post['password'];
if($username == "myusername" && $password == "letmein") {
$_SESSION['logged_in'] = true;
header("Location: index.php");
exit;
} else {
$loginfailed_param = "?verferr=1";
header("Location: index.php" . $loginfailed_param);
exit;
}
}
if ($_SESSION['logged_in'] === true) {
//User has logged in
}
?>
Using jQuery
HTML
<div id="loginForm">
<form id="myLoginForm">
<input id="username">
<input id="password">
<button id="formSubmit" name="formSubmit">Submit Form</button>
<input style="display: none;" type="text" id="realSubmit" name="realSubmit" value="hidden">
</form>
</div>
<div id="successPage">
Thank you for loggging in...
</div>
<div id="loginHome">
Login Homepage
Welcome <span id="displayUsername"></span>
</div>
jQuery
(function($){
$(function(){
$("#formSubmit").on('click', function() {
var username= $("#username").val();
var password = $("#password").val();
var data = {username: username, password: password};
delegateAjax('../myAjax.php', data, 'POST');
});
});
function delegateAjax(url, data, responseType, dataType, callback) {
function successHandler(data) {
console.log("Ajax Success");
var responseData = $.parseJSON(data);
if (responseData.status === 'Success') {
$("#loginForm").fadeOut(1500, function() {
$("#successPage").fadeIn(1500, function() {
$(this).fadeOut(1500, function() {
$("#displayUsername").html(responseData.username);
$("#loginHome").fadeIn(1500);
});
});
});
}
};
function failureHandler(xhr, status, error) {
console.log("Ajax Error");
console.log(status);
console.log(error);
console.dir(xhr);
};
function handler404(xhr, status, error) {
console.log("404 Error");
console.log(status);
console.log(error);
console.dir(xhr);
};
function handler500(xhr, status, error) {
console.log("500 Error");
console.log(status);
console.log(error);
console.dir(xhr);
};
url = typeof url !== 'undefined' ? url : 'js/ajaxDefault.php';
data = typeof data !== 'undefined' ? data : new Object();
responseType = typeof responseType !== 'undefined' ? responseType : 'GET';
dataType = typeof dataType !== 'undefined' ? dataType : 'json';
callback = typeof callback !== 'undefined' ? callback : 'callback';
var jqxhr = $.ajax({url: url, type: responseType, cache: true, data: data, dataType: dataType, jsonp: callback,
statusCode: { 404: handler404, 500: handler500 }});
jqxhr.done(successHandler);
jqxhr.fail(failureHandler);
};
})(jQuery);
PHP
myAjax.php
<?php
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if (!IS_AJAX) {
$response['status'] = 'Error';
$response['message'] = 'Same Origin Policy Error';
echo json_encode($response);
exit;
}
$pos = strpos($_SERVER['HTTP_REFERER'], getenv('HTTP_HOST'));
if ($pos === false) {
$response['status'] = 'Error';
$response['message'] = 'Same Origin Policy Error';
echo json_encode($response);
exit;
}
function validUser($data) {
//connect to db and validate user
$dbi = new mysqliObject();
$params['string'] = $data['username'];
$dbi->newSelect($params);
$table = 'users';
$select = '*';
$where = '`username` = ? LIMIT 1';
if ($dbi->exec($table, $select, $where)) {
$result = $dbi->result[0];
return passwordVerify($result['password']); //true/false
} else {
//for debugging
//echo 'Last Error: '.$dbi->get('lastError').'<br>'."\r\n";
//echo 'Last Query: '.$dbi->get('lastQuery').'<br>'."\r\n";
return false;
}
}
$args = array(
'username' => FILTER_SANITIZE_SPECIAL_CHARS,
'password' => FILTER_SANITIZE_SPECIAL_CHARS);
$post = filter_input_array(INPUT_POST, $args);
if ($post) {
if (validUser($post)) {
$response['status'] = 'success';
$response['username'] = $username;
echo json_encode($response);
exit;
} else {
$response['status'] = 'Failed';
$response['message'] = 'Username/Password Invalid';
echo json_encode($response);
exit;
}
}
$response['status'] = 'Error';
$response['message'] = 'POST Data Invalid';
echo json_encode($response);
exit;
I'm going crazy! I'm trying to submit a form from jquery to php and insert a record in my database. I'm getting no error, but no record is being submitted. All works fine when I just go to the php page and put variables in the URL. But it doesn't work when I submit the variables via the jquery page. Can anyone help me out, please?
HTML:
<form id="tellusForm" >
<div class="formHead">Tell us your story</div>
<div id="thank">Thank you.</div>
<table cellpadding="5">
<tr><td>Name:</td><td><input id="tellName" type="text"/></td></tr>
<tr><td>Country of origin:</td><td><select id="tellCountry"></select></td></tr>
<tr><td>Age:</td><td><input type="text" id="tellAge"/></td></tr>
<tr><td>Occupation:</td><td><input type="text" id="tellOccupation"/></td></tr>
<tr><td>Email address:</td><td><input type="text" id="tellEmail"/></td></tr>
<tr><td>Phone number:</td><td><input type="text" id="tellPhone"/></td></tr>
<tr><td>A bit about you:</td><td><textarea id="tellAbout" style="width: 100%;"></textarea></td></tr>
<tr><td></td><td><input type="submit" value="Send" class="submit"/></td></tr>
</table>
</form>
jquery:
$('.submit').click(function(){
$.get('tellus.php', { name: "laura"}, function(data){
eval(data);
});
});
tellus.php:
<?php
require_once ('../constants_test.php');
$name = $_GET['name'];
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit;
}
$q = "Insert into tellus(`Name`) values ('" . $name . "')";
if ($db->query($q)) {
echo "console.log('you got it')";
};
$db->close();
?>
Thanks everyone who tried to help me! I ended up having to do it this way:
$.post("./tellus.php", {tellName:name}, function(data){
alert(data)
});
The ajax call must have had something that wasn't working.
Use serialize():
$("#tellusForm").on("submit", function() {
event.preventDefault();
$.ajax({
url: 'tellus.php',
data: $(this).serialize()
}).done(function(data) {
$(html).append(data);
});
});
Also make sure to have names on your form elements:
<input type="text" name="tellAge" id="tellAge" />
This topic is very common here so try searching for other posts - e.g. Submit form using AJAX and jQuery could work too.
The ajax call wasn't working because you are using $.serialize to serialize your form objects, which will return ;
{key:'tellName', value='name'} // <input name="tellName" value="name" />
whereas you are expecting a key:value pair. In order to get the data to send what you expecting, you should modify the object using this jQuery function:
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
}
And call it whenever you're submitting form. It will structure your form to have the key:value pair.
<form id="register">
<input type="text name="username" />
<input type="text" name="email" />
<input type="submit value="Register!" />
</form>
and the javascript (remember to include the serializeObject function)
$('#register').on('submit', function(){
var data = $(this).serializeObject()
// data will return {username: value, email:value}
$.post('process.php', data, function(response){
try{
var r = JSON.parse(response) // Check if the response is an object
console.log(JSON.stringify(r))
}
catch(e){
console.log(response) // The response is a string
}
})
})
Cheers!
I suggest you should use POST for actions which include insert/delete/update of data in database. It keeps the data safe.
If you want to still use GET and test out something. I suggest do not use jquery in the middle to handle the get. Submit button on click submits the form anyway, so the jquery $.get is unnecessary.
To your form element add
<form name='' action='tellus.php'>...</form>
This should fix the problem.
How about this one
jquery
$("#submit").click(function() {
formData = {
name: "abc"
}
$.ajax({
type: 'GET',
contentType: 'application/json',
url: "http://yourpage/tellus.php",
dataType: "json",
data: formData,
success: function(data) {
console.log(data.message);
},
error: function(data) {
console.log(data.message);
}
});
});
php
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_GET['name'])) {
$name = $_GET['name'];
// include db connect class
require_once ('../constants_test.php');
// connecting to db
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit;
}
// mysqli inserting a new row
$q = "INSERT INTO tellus('Name') values ('" . $name . "')";
// check if row inserted or not
if ($db->query($q)) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "you got it";
// echoing JSON response
echo json_encode($response);
$db->close();
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
$db->close();
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
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')");