Insert data into mysql database with php and ajax in wordpress - php

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.

Related

jQuery Ajax sending data to php with one button click but two different actions

What I'm trying to achieve is a user to follow another user without having to refresh the page. So far I've played around and had no problem inserting and deleting the rows in mysql table, but now when I'm trying with AJAX I can't get it to work.
jquery
$(document).ready(function(){
$("#followbutton").click(function(e) {
e.preventDefault();
var theuserid = $('#theuserid').val();
var thefollower = $('#thefollower').val();
$.ajax({
url: 'includes/followuser.inc.php',
type: 'post',
data: {'theuserid': theuserid, 'thefollower': thefollower, 'submitFollow': true},
success: function(response){
$('#followmessage').html(response);
$("#followmessage").show().delay(3000).fadeOut();
$('#followbutton').hide();
$('#unfollowbutton').show();
// $("#unfollowbutton").hover(function(){
// $(this).text("Unfollow");
// }, function(){
// $(this).text("Unfollow");
// });
}
});
});
});
$(document).ready(function(){
$("#unfollowbutton").click(function(e) {
e.preventDefault();
var theuserid = $('#theuserid').val();
var thefollower = $('#thefollower').val();
$.ajax({
url: 'includes/followuser.inc.php',
type: 'post',
data: {'theuserid': theuserid, 'thefollower': thefollower, 'submitUnfollow': true},
success: function(response){
$('#followmessage').html(response);
$("#followmessage").show().delay(3000).fadeOut();
$('#unfollowbutton').hide();
$('#followbutton').show();
//I want the button to change its text to Following and when hovering it should say unfollow if user is followed
}
});
});
});
followuser.inc.php
<?php
require_once 'dbh.inc.php';
require_once 'functions.inc.php';
if (isset($_POST["submitFollow"])){
$userthatisfollowed = $_POST["thefollower"];
$theuserid = $_POST["theuserid"];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt = $conn->prepare('INSERT INTO userfollow (thefollower, theuserid, followstatus) VALUES (?,?,?)');
$followstatus = 1;
$stmt->bind_param('sss', $userthatisfollowed, $theuserid, $followstatus);
$stmt->execute();
echo $response = "<span>Followed!</span>";
$stmt->close();
} else if(isset($_POST["submitUnfollow"])){
$userthatisfollowed = $_POST["thefollower"];
$theuserid = $_POST["theuserid"];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt = $conn->prepare('DELETE userfollow FROM userfollow WHERE thefollower = ? AND theuserid = ?');
$stmt->bind_param('ss', $userthatisfollowed, $theuserid);
$stmt->execute();
echo $response = "<span>Unfollowed!</span>";
$stmt->close();
} else {
echo "DID NOT WORK";
}
profile.php
if(isset($_SESSION["userid"]) && $_SESSION["userid"] != $userthatisfollowed) {
?>
<form action="<?php echo htmlspecialchars("includes/followuser.inc.php");?>" id="followform" method="post">
<?php
if ($resulted->num_rows > 0){
$subscribe_status = "Unfollow";
$subscribe_text = "Following";
} else {
$subscribe_status = "Follow";
$subscribe_text = "Follow";
}
echo "<button name='submit".$subscribe_status."' id ='unfollowbutton' type='submit' style='display:none'>";
echo "<span>".$subscribe_text."</span>";
echo "</button>";
echo "<button name='submit".$subscribe_status."' id ='followbutton' type='submit'>";
echo "<span>".$subscribe_text."</span>";
echo "</button>";
// echo "<button name='submit".$subscribe_status."' id ='notificationbell' type='submit' style='display:none'>";
// echo "<i class='fa fa-bell'></i>";
// echo "</button>";
echo "<div id='followmessage'></div>";
?>
<input type="hidden" name="theuserid" id="theuserid" value="<?php echo $_SESSION["userid"] ?>">
<input type="hidden" name="thefollower" id="thefollower" value="<?php echo $userthatisfollowed; ?>">
</form>
<?php
}
What's worth noting is that I'm getting the response DID NOT WORK which tells me that if(isset($_POST["submitUnfollow"])) is not set. However, If I try with if(isset($_POST["theuserid"]) && (isset($_POST["thefollower"])) then it actually works for the insert query but not for the delete query.
You're missing the submitFollow parameter in the data: object. Instead, you have followbutton: true, which isn't used by the PHP code. So change that to:
data: {'theuserid': theuserid, 'thefollower': thefollower, 'submitFolow': 'true'},
And for the unfollow button, use submitUnfollow instead.

ajax to submit php form to database, ajax part doesn't work

I'm very new to ajax so I followed a tutorial but I can't get it to work. I tried search this forum for an answer but with no luck..
HTML (a bit stripped down from classes and bootstrap-stuff)
<form id="editUserForm" role="form">
<input id="edit_employeenr" type="text" name="employeenr">
<input id="edit_name" type="text" name="name">
<select id="edit_membertype" name="membertype">
<option value="1">Admin</option>
<option value="2">Employee</option>
</select>
<input type="submit" value="Save">
</form>
<div id="editUserMsg">Successfully updated!</div>
JS
$(document).ready(function() {
$("#editUserMsg").hide();
$("#editUserForm").submit(function(event) {
event.preventDefault();
submitUserEdit();
});
function submitUserEdit(){
var dataString = $("#editUserForm").serialize();
$.ajax({
type: "POST",
url: "user_edit_process.php",
data: dataString,
success: function(text){
if (text == "success"){
userEditSuccess();
}
}
});
}
function userEditSuccess(){
$("#editUserMsg").show().delay(5000).fadeOut();
}
});
PHP (user_edit_process.php)
<?php
$employeenr = $_POST['employeenr'];
$name = $_POST['name'];
$membertype = $_POST['membertype'];
$stmt = $link->prepare("UPDATE users SET employeenr = ?, name = ?, membertype = ?");
$stmt->bind_param("isi", $employeenr, $name, $membertype);
$stmt->execute();
if ($stmt) {
echo 'success';
} else {
echo 'fail';
}
?>
if i put the $("#editUserMsg").show().dealy(5000).fadeOut(); just above the $.ajax the message appears, so that must mean that the ajax code isn't working correct. Any suggestions?
EDIT Solved. I had forgotten to include the file where the variable $link wes defined.
It seems that you have a problem in your either in your prepare statement or in the bind_parameter. You should always check for error, so I suggest you do like this to check for errors:
<?php
$employeenr = $_POST['employeenr'];
$name = $_POST['name'];
$membertype = $_POST['membertype'];
if (!($stmt = $mysqli->prepare("UPDATE users SET employeenr = ?, name = ?, membertype = ?"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (! $stmt->bind_param("isi", $employeenr, $name, $membertype)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
?>
and then in you JS, add this to your success method:
console.log(text);
Check your Firefox console (Ctrl-Shift-Q), and if there is an error you would find it under "Network" -> Click the "user_edit_process.php" in the list -> and in the right window under "Preview".
Is that all code that you have in user_edit_process.php?
Is the $link variable properly initialize?
You can try to comment part of your code in PHP file, and write something like below to test if you Ajax code work properly:
<?php
$employeenr = $_POST['employeenr'];
$name = $_POST['name'];
$membertype = $_POST['membertype'];
// $stmt = $link->prepare("UPDATE users SET employeenr = ?, name = ?, membertype = ?");
// $stmt->bind_param("isi", $employeenr, $name, $membertype);
// $stmt->execute();
if ($employeenr) {
echo 'success';
} else {
echo 'fail';
}
And then if you type something in first employeenr form input it should show Successfully updated!. If you leave this input empty and send form, it shouldn't show.

Updating database with an AJAX call using a particular id

I am attempting to do my first AJAX call and what I am trying to do is pretty simple, but my db is not being updated.
All I am trying to do is when I hit the accept button next to a user, for their id to be taken and sent with the new status 'Accepted' and for the status to change from 'Pending' to 'Accepted' for that particular user in my user_requests db table.
Nothing is being changed in the db and the only thing that is happening with the AJAX code is I get my #success message, but for maybe 0.3 of a second and it does not fade out.
Does anyone see what I am doing wrong in my attempt?
<h2>Pending User Requests</h2>
<br />
<div id="success" style="color: red;"></div>
<?php
$con = mysqli_connect("localhost", "root", "", "db");
$run = mysqli_query($con,"SELECT * FROM user_requests ORDER BY id DESC");
$numrows = mysqli_num_rows($run);
if( $numrows ) {
while($row = mysqli_fetch_assoc($run)){
//comment added by php-dev : condition could be set in the query -->
if($row['status'] == "Pending"){
$pending_id = $row['id'];
$pending_user_id = $row['user_id'];
$pending_firstname = $row['firstname'];
$pending_lastname = $row['lastname'];
$pending_username = $row['username'];
?>
<!-- comment added by php-dev : useless form tag -->
<form action="" method="POST" id="status">
<!-- comment added by php-dev : useless input field, no field name -->
<input type='hidden' value='<?php echo $pending_id; ?>' id='pending_id' />
<?php
// comment added by php-dev : comparing string to boolean value true
if ($pending_firstname == true) {
echo "Name - ". $pending_firstname . " " . $pending_lastname . "</br>"
. "Username - ". $pending_username . "</br></br>"
?>
<!-- comment added by php-dev : conditional form closing tag -->
</form>
<button class="approve" type="submit" form="status" name="approve"
value="<?= $pending_id; ?>">
Approve
</button>
<button id="deny" type="submit" form="status" name="deny" value="Denied">
Deny
</button>
<br><br><br>
<?php
// comment added by php-dev : else statement misplaced -->
;} else {
echo "There are no Pending Requests at this time.";
}
}
}
}
?>
My AJAX call...
<script>
$(document).ready(function(){
$('.approve').click(function(){
$.ajax({
url: 'userRequest_approve.php',
data: {
id: $(this).val(), //the value of what you clicked on
//you clicked on it so you know the status might as well hardcode it
status: 'Approved'
},
success: function(data) {
//do something with the data that got returned
// comment added by php-dev : for debug purposes, the #success should show
// the server reponse instead
$('#success').html('User Status Changed!');
//do something with the data that got returned
$('#success').delay(5000).fadeOut(400);
},
type: 'POST'
});
});
});
</script>
My userRequest_approve.php file to insert into db to update the status...
<?php
require_once 'core/init.php';
$term = mysql_escape_string($term); // Attack Prevention
$pending_id = $_POST['id'];
$status = $_POST['approve'];
$con = mysqli_connect("localhost","root","","db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $con->prepare(
"INSERT INTO user_requests (status, date_responded) VALUES (?, NOW())"
);
if ( false===$stmt ) {
// Check Errors for prepare
die('User Request update prepare() failed: ' . htmlspecialchars($con->error));
}
$stmt->bind_param('s', $status);
// comment added by php-dev : should be false === $stmt->bind_param ...
if ( false===$stmt ) {
// Check errors for binding parameters
die('User Request update bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->execute();
// comment added by php-dev : should be false === $stmt->execute ...
if ( false===$stmt ) {
die('User Status update execute() failed: ' . htmlspecialchars($stmt->error));
}
?>
If you want to update, you should try this:
$stmt = $con->prepare("UPDATE user_requests SET status=?, date_responded=NOW() WHERE id=?");
$stmt->bind_param('si', $status, $pending_id);
You also need a name attribute on your hidden so it'll be sent:
<input type='hidden' name='id' value='<?php echo $pending_id; ?>' id='pending_id'/>
Original Answer
I only see one issue:
This is the ajax request you're using:
$.ajax({
url: 'userRequest_approve.php',
data: {
id: $(this).val(), //<< id
status: 'Approved' //<< status
},
success: function(data) {
//do something with the data that got returned
$('#success').html('User Status Changed!');
$('#success').delay(5000).fadeOut(400);//do something with the data that got returned
},
type: 'POST'
});
Note that the data you're sending is id and status.
However, on the PHP side:
$pending_id = $_POST['id']; //yep
$status = $_POST['approve']; //does it exist?
You should be using
$status = $_POST['status'];

jQuery keyup function stops working when trying to insert into a database

This is a weird problem and I'm not sure how to approach it.
At the moment I'm trying to have the user enter an ingredient - a list of ingredients appears as you type with buttons next to them to add them which should insert them into SQL database.
The list population ceases to function when I uncomment
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
In the .click function of the add button.
Which is strange because it's like the .keyup function just stops working.
<html>
<head>
<title>Cocktails</title>
<script src="http://assets.absolutdrinks.com/api/addb-0.5.2.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<form>
<input type="text" name="ingredientinput" id="ingredientinput"><br>
</form>
<div id="ingredientlist">
</div>
<script>
$(document).ready(function(){
//ajax call to query cokctail DB
//handleData is callback function that handles result
function get_ingredients(query,handleData){
var apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
var rooturl = "http://addb.absolutdrinks.com/";
$.ajax({
type: "GET",
url: rooturl + "/quickSearch/ingredients/" + query + "/",
dataType: 'jsonp',
data: {apiKey:apikey},
success: function(data) {
handleData(data);
},
error: function(){
//error
}
});
}
//when text is entered - quicksearch the database
$("#ingredientinput").keyup(function(){
query = $(this).val(); //value of textbox
divlist = ""; //list of ingredients
objectlist = {};
if (query.length > 0){
//set loading image on keypress
$("#ingredientlist").html("<img src='images/spinner.gif' alt='loading' height='24' width='24'>");
//pass query to ajax call and handle result
get_ingredients(query,function(data){
console.log(data);
//build list of ingredients
$.each(data["result"], function(key, value){
divlist += "<div id='" + value["id"] + "'>" + value["name"] + "<button class='addbutton' type='button' id = '"+value["id"]+"'>+</button></div>";
objectlist[value["id"]] = value;
//clicking button dumps object to file?
});
$("#ingredientlist").html(divlist); //populate div ingredientlist with results
divlist = ""; //clear html builder
});
console.log("input query:" + query);
}
else{
$("#ingredientlist").html(""); //if no input clear list
}
});
$("#ingredientlist").on('click','button.addbutton',function(){
$("#ingredientlist").on('click','button.addbutton',function(){
current = objectlist[this.id];
sqlquery = current["description"] + "," + current["id"] + "," + current["isAlcoholid"] + "," + current["isBaseSpirit"] + "," + current["isCarbonated"] + "," + current["isJuice"] + "," + current["languageBranch"] + "," + current["name"] + "," + current["type"];
console.log(sqlquery);
<?php
$servername = "localhost";
$username = "root";
$password = "**";
$dbname = "ingredients";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql = "INSERT INTO cocktails (description, id, isAlcoholic, isBaseSpirit, isCarbonated, isJuice, languageBranch, name, type)
VALUES ('test','test','test','test','test','test','test','test','test',)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
?>
});
});
});
</script>
</body>
</html>
You can't just embed a save query from within javascript like you are doing. This is a server side function that needs to happen, and return a result (Almost like you're doing with your get_ingredients function.)
My suggestion, is create a save_ingredients function that works through ajax to pass the information (In this case, the ingredient to save) to the server.
in saveingredients.php:
<?php
$servername = "localhost";
$username = "root";
$password = "**";
$dbname = "ingredients";
$conn = new mysqli($servername, $username, $password, $dbname);
$description = filter_input(INPUT_GET, 'description', $_GET['description'], FILTER_SANITIZE_SPECIAL_CHARS);
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$isAlcoholic = filter_input(INPUT_GET, 'isAlcoholic', FILTER_VALIDATE_BOOLEAN);
$isBaseSpirit = filter_input(INPUT_GET, 'isBaseSpirit', FILTER_VALIDATE_BOOLEAN);
$isCarbonated = filter_input(INPUT_GET, 'isCarbonated', FILTER_VALIDATE_BOOLEAN);
$isJuice = filter_input(INPUT_GET, 'isJuice', FILTER_VALIDATE_BOOLEAN);
$languageBranch = filter_input(INPUT_GET, 'languageBranch', FILTER_SANITIZE_SPECIAL_CHARS);
$name = filter_input(INPUT_GET, 'name', FILTER_SANITIZE_SPECIAL_CHARS);
$type = filter_input(INPUT_GET, 'type', FILTER_SANITIZE_SPECIAL_CHARS);
$sql = "INSERT INTO cocktails (description, id, isAlcoholic, isBaseSpirit, isCarbonated, isJuice, languageBranch, name, type)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ( $stmt = $conn->prepare($sql) )
{
$stmt->bind_param('sdsssssss', $description, $id, $isAlcoholic, $isBaseSpirit, $isJuice, $languageBranch, $name, $type);
if ($stmt->execute($sql) === TRUE) {
echo json_encode('error' => false);
} else {
echo json_encode('error' => 'MySQL Error: ' . $conn->error);
}
}
$conn->close($conn);
?>
A sample AJAX function:
function saveingredients(current) {
$.ajax({
url: 'saveingredients.php',
data: {
description: current["description"],
id: current["id"],
isAlcoholid: current["isAlcoholid"],
isBaseSpirit: current["isBaseSpirit"],
isCarbonated: current["isCarbonated"],
isJuice: current["isJuice"],
languageBranch: current["languageBranch"],
name: current["name"],
type: current["type"]
},
success: function(res) {
if ( res.error )
{
console.log(res.error);
}
else
{
//Do something here because it inserted correctly.
}
},
failure: function(err) {
console.log(err);
}
});
}

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

Categories