I am trying create an email subscription input box using JQuery, but for some reason, the inputted email addresses are not inserting into the MySql database, can anyone help me?
Here is the code I have in my newsletter.js file:
jQuery(function($){
var validateRegexps = {
email: /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/,
"default": /.{4}/
}
if ($("#newsletter form").length == 0) return
var defaultMessage = $("#newsletter").attr("data-default")
var subscribedMessage = $("#newsletter").attr("data-subscribed")
var newsletterForm = $("#newsletter form")
/* newsletter code */
function newsletter(send) {
var subscribe = true
newsletterForm.find('input[type="submit"]').val(subscribe ? "Sign Up" : "Unsubscribe")
var email = newsletterForm.find('input[name="email"]')
var check = true
if (email.val() == defaultMessage || email.val() == subscribedMessage) {
email.val("")
if (!send) check = false
}
if (check) {
if(validateRegexps["email"].test(email.val())) {
// valid mail
email.removeClass("error")
if (send) {
$.post("php/newsletter.php",{add: email.val()}, function(data) {
email.val(subscribedMessage)
});
email.val("sending")
}
} else {
// invalid mail
email.addClass("error")
}
}
return false
}
function restore(e) {
var jqEl = $(e.currentTarget)
if (jqEl.val() == "") {
jqEl.val(defaultMessage)
}
return true
}
function signUp() {
return newsletter(false)
}
function signUpAndSend() {
return newsletter(true)
}
newsletterForm.find('input[name="email"]').focus(signUp).focusout(restore)
newsletterForm.change(signUp)
newsletterForm.submit(signUpAndSend)
});
Here is the code in my newsletter.php file:
require("config.php");
$db = mysql_connect($dbhost, $dbuser, $dbpassword);
mysql_select_db($dbdatabase, $db);
$subsql = "INSERT INTO subscribe(email) VALUES(".$_POST['add'].");";
mysql_query($subsql);
And here is the code in my other php page to display the input box:
<div id="newsletter" data-default="youremail#yourdomain.com" data-subscribed="Thank you for subscribing.">
<form action="#" method="POST">
<input type="text" name="email" value="youremail#yourdomain.com" />
<input type="submit" value="submit" />
</form>
<h2>Sign Up to Our Newsletter!</h2>
</div>
Any help is greatly appreciated. Thank you very much in advance!!!
Hmm! Looking at your code does not directly point to any errors but the most obvious issue seems to be in the INSERT query that the email address isn't enclosed in single-quotes. Please draft your query like:
$subsql = "INSERT INTO subscribe(email) VALUES('" . $_POST['add'] . "');";
Hopefully the above INSERT should work fine. If the issue still exists though, try finding out if the query might be generating any errors:
$subsql = "INSERT INTO subscribe(email) VALUES('" . $_POST['add'] . "');";
mysql_query($subsql);
if (mysql_error()) {
echo mysql_error();
}
If no errors are found and the issue still exists, it might make sense to look into other basics, like:
Is $_POST['add'] available in "newsletter.php"?
Is MySQL connection correctly established in "newsletter.php"?
Is there any JavaScript issue that the POST request isn't send at all or perhaps send with an empty email address?
Hope this helps!
Related
I have a checkbox that dynamically updates a MySQL database when it is checked/unchecked using PHP and Ajax.
I am now trying to pass the users name so that the Ajax script can update the database with the users full name.
I have the name held in a variable called $full_name. I cannot seem to get this working though. Please see the code below:
Javascript:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function chkit(uid, chk) {
chk=document.getElementById("chk").checked;
$.ajax({
type: 'GET',
url: 'ajax.php',
data: { chkYesNo: chk, record_id: uid, full_name: user},
success:function(data){
// successful request; do something with the div background color
if(data==1)
{
$("#replace").addClass("checked_div_status").removeClass("replace");//removing first class and adding second class
}
else
{
$("#replace").addClass("replace").removeClass("checked_div_status");//removing second class and adding first class
}
}
});
}
</script>
HTML:
<?php
$record_id = $_GET['veh_id'];
include '../dbconnect.php';
//fetching data from database
$select=mysql_fetch_array(mysql_query("select invoice_checked from vehicle_details where veh_id = '$record_id' "));
?>
<!--The checkbox whose enable to change div his background color and onclick call function to update database-->
<table width=“100%”>
<td id="replace2" class="<?php if($select['invoice_checked']==1) { echo 'checked_div_status2'; } else{ echo 'replace2'; } ?>">
<input name="chk2" type="checkbox" id="chk2" value="1" onclick="chkit2(<?php echo $record_id;?>,'chk2');" <?php if($select['invoice_checked']==1) { echo 'checked'; } else{ echo ''; } ?> />
Invoice Checked
</td>
</table>
Ajax.php:
<?php
mysql_connect("server", "username", "password") or die("Could not connect: " . mysql_error());
mysql_select_db("database");
//here $get variable receive checkbox value true(1) either false(0)
$get=$_GET['chkYesNo'];
//here $get_id variable receive value of current id that you passed
$get_id=$_GET['record_id'];
$get_user=$_GET['full_name'];
if($get=="true")
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='1', check_user='".$get_user."' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
else
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='0', check_user='0' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
?>
Any help would be greatly received.
Thanks,
John
Some debug lession for you. Please, check my comments:
// Do not need to replicate your code, if the same things happens in it.
//instead, use a condition to set your variables, and use these variables later.
if ($get == "true") {
$hpi_registered = 1;
//Escape your variable to avoid sql injection
$checkUser = mysqli_real_escape_string($conn, $_GET["full_name"]);
} else {
$hpi_registered = 0;
$checkUser = 0;
}
//Store your query in a variable, so you can debug / dump it
//Let's dump it, see, what is your query, and try to run in directly in sql.
//Maybe it has syntax error.
$sql = "UPDATE vehicle_details SET"
. " hpi_registered='" . intval($hpi_registered) . "',"
. " check_user='" . $checkUser . "'"
. " WHERE veh_id='" . intval($get_id) . "'";
mysqli_query($conn, $sql);
//What happens, if you run it directly in sql? If this fails, now here is your
//error.
$sql = "SELECT hpi_registered"
. " FROM vehicle_details"
. " WHERE veh_id='" . intval($get_id) . "'";
//Do the same like previous query.
$res = mysqli_query($conn, $sql);
$select = mysqli_fetch_array($res);
echo $select['hpi_registered'];
DO NOT use mysql functions, because they are deprecated. Use mysqli or PDO instead.
Avoid sql injection by escaping your variables.
I'm working on a REST api that people can download and throw on their server and use with little to no programming knowledge. https://github.com/evanstoddard/REST-Easy.
I'm using ajax for the setup page and php returns a string for ajax to see and decide whether to move on to the next step or tell the user to fix an error. It seemed to be working fine and then all of a sudden it won't go past the first step.
In my javascript I have the return value from php printed in my log. The first step is for the user to enter mysql server information such as the server url, username, and password. If a connection is created 'success' is returned. I appear to be getting ' success'. With a space or indent in there.
I commented out a lot of code I was working on before this error had occurred and the error is still there. I also added an extra indentation to my if block to check the return and the script succeeded so somewhere an extra bit is being added.
I don't really want to post my code here because there is A LOT of it and there are a bunch of moving parts which probably isn't the best way to go.
Here's a quick rundown of how this works:
User input(html form)->ajax->data handling php script->class_database.php(prints success->ajax->html
Applicable code:
Html:
<form onsubmit="stepTwo('#stepOneForm'); return false;" id="stepOneForm">
<input type="hidden" name="task" value="1" />
<input type="text" class="inputText" id="serverURL" name="serverURL" placeholder="MySQL Server:" /><br />
<input type="text" class="inputText" id="serverUsername" name="serverUsername" placeholder="Username:" /><br />
<input type="text" class="inputText" id="serverPassword" name="serverPassword" placeholder="Password:" /><br />
<input type="submit" class="blueButton" value="Connect" />
</form>
Javascript(AJAX):
function setupForm(form){
//console.log('Form function called.');
var formData = $(form).serialize();
$.ajax({
type: "POST",
url: "data/data_setup.php",
data: formData,
success: function(result) {
console.log(result)
function showAndTell(hide, show){
$(show).slideDown(600);
$(hide).delay(300).slideUp(600);
}
function showMessage(message, type, holdMessage){
var messageContainer = "#messageContainer";
var messageText = "#messageText";
var messageImage = "#messageImage";
var errorImage = "<img src='images/error.png' alt='Error' height='60px' width='60px' />";
var successImage = "<img src='images/success.png' alt='Error' height='60px' width='60px' />";
if (type === 'error'){
$(messageText).empty()
$(messageImage).empty()
$(messageText).append(message)
$(messageImage).append(errorImage)
$(messageContainer).slideDown(500)
if (!holdMessage) {
$(messageContainer).delay(7000).slideUp(500)
}
}
else if(type === 'success'){
$(messageText).empty()
$(messageImage).empty()
$(messageText).append(message)
$(messageImage).append(successImage)
$(messageContainer).slideDown(500)
if (!holdMessage) {
$(messageContainer).delay(7000).slideUp(500)
}
}
}
if(result === 'success'){
showAndTell('#stepOne', '#stepTwo');
showMessage('Successfully connected to MySQL database.', 'success');
}
else if (result === 'badaccess') {
showMessage('Unsuccessful. Please recheck information.', 'error');
}
else if (result === 'nserver') {
showMessage('Please enter a server URL.', 'error');
$('#serverURL').css('background', '#ffdadb');
}
else if (result === 'nserverusername') {
showMessage('Please enter a server username.', 'error');
$('#serverUsername').css('background', '#ffdadb');
}
else if (result === 'ndatabase') {
showMessage('No database with that name. Create it? Yes | No', 'error', true);
}
else if (result === 'database') {
showMessage('Successfully connected to that database.');
showAndTell('#stepTwo', '#stepThree');
}
else {
showMessage('Unknown error. Please try again later.', 'error');
}
}
});
}
PHP data handling script:
<?php
//Include rest class
require_once('../../classes/class_rest.php');
//Get variables
$task = $_POST['task'];
$database_server = $_POST['serverURL'];
$database_username = $_POST['serverUsername'];
$database_password = $_POST['serverPassword'];
$rest_name = $_POST['restName'];
$username = $_POST['username'];
$password = $_POST['password'];
$confPassword = $_POST['confirm'];
$emailAddress = $_POST['emailAddress'];
$api_name = $_POST['apiName'];
$database_name = $_POST['databaseName'];
$table_prefix = $_POST['tablePrefix'];
if ($task == 1){
if($database_server == ''){
print('nserver');
}
else if($database_username == ''){
print('nserverusername');
}
else{
connectSQL($database_server, $database_username, $database_password);
}
}
else if ($task == 2){
if($rest_name == ''){
print('nrest');
}
else{
databaseDoesExist($rest_name);
}
}
else if ($task == 3){
if($username == ''){
print('nuser');
die();
}
if($emailAddress == ''){
print('nemail');
die();
}
if(!$confPassword == $password){
print('nconf');
die();
}
insertUser($username, $emailAddress, $password);
}
else if ($task == 4){
}
else if ($task == 5){
}
else if ($task == 6){
}
else if($task == 9){
createInitialDatabase();
}
else if($task == 10){
createConfigFile();
}
?>
Function in class_database.php:
//Validates sql information
function connectSQL($server, $username, $password){
//Create sql connection
$con = mysqli_connect($server, $username, $password);
//Checks if connection was successful
if (mysqli_connect_errno($con)){
//Print 'badaccess' for ajax
print('badaccess');
}
//Run if connection successful
else{
//Print 'success' for ajax
print('success');
//Adds session variables for other sql commands later on
$_SESSION['server'] = $server;
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
}
Few comments to your handling script:
* make sure there's no white space before the opening <?php and as well, nothing after the trailing ?> which, btw, can be omitted as well (did you know?).
* what about so called BOM in case of UTF-8 codified source codes? You may wanna choose an editor or editor setting that doesn't write BOM at the beginning of UTF files.
* instead of, print('badaccess'); you might use die('badaccess'); – it will print the argument and stop the script execution.
* at require_once (and directives alike) it's recommended to omit the parenthesis
* consider rewriting long if...else statement dealing with $task to one switch().
it's easy to unintentionally leak a space from php code (space before in any included file), try ob_start() at the begining of "PHP data handling script" and ob_end_clean() just before "print('success')" at connectSql
After the ?> in one of my classes, there was an indent and that's what was causing my problems... programming sucks sometimes.
I was wandering how you would go about sending a form to different pages.
If there is an error in the form, stay on the page, showing an error and if there is no error go onto another page
here is my code
<form id = "form" action = "./?page=markandfeedback" method = "post">
<br>
Mark for:
<INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar" value="Enter Student Number" style="min-width:165px;">
<input type="button" value = 'Continue' onclick="validate()">
<?
$studID = $_POST['txtChar'];
$module2 = $_SESSION['module'];
$ex = $_POST['exer'];
$studerr = array();
$sql = 'SELECT * FROM `student`, `modules` WHERE `studentID` = '.$studID.' AND `moduleCode` = '.$_SESSION['module'];
$result = mysql_query ($sql);
echo $_SESSION['module'];
if(isset($studID)){
if($result == null){
$studerr[] = "No Student with that ";
print_r($studerr);
}
$_SESSION['student'] = $studID;
}
echo' <SCRIPT TYPE="text/javascript" LANGUAGE="javascript">
function validate() {
if('.$result.' == null)
{
return false
}
else
{
return true;
}
}
</script>';
?>
</form>
cheers
Very briefly (without knowing other details):
if (!empty($errorMessage)) {
echo $errorMessage;
} else {
header("Location: http://domain.com/success.php");
}
Have you searched something about that ???
YOu can use normal php validation for error checking and
if(there is no error )
{
header('location: redirect2page.php')
}
else
{
show errors
}
you have to do simple javascript validation in form submit if error occures it will return false so, thats remain on same page
like
function validate()
{
if(document.getElementById('elementid').value=='')
{
return false;
}
else
{
return true;
}
just call this function on submit button click
So I'm working on app that involves leveraging user profile data from FB. But not all users maintain the same data, so I'm using functions to determine which data is missing and then request the appropriate data from the user. These requests come from a database. A basic example of the function looks like this:
function getEmploymentInfo () {
if (isset($this->employer) and (!isset($this->jobtitle))) {
$id = 1;
} elseif (!isset($this->employer)) {
$id = 2;
}
echo $this->get_profile($id);
}
And the get profile function looks like this:
function get_profile($id) {
$dsn = "mysql:host=localhost;dbname=software";
$username = "root"; // database username
$password = "*******"; // database password
try {
$enter = new PDO($dsn, $username, $password);
$sql = "SELECT response FROM getprofile WHERE response_id = ? ";
$new_item = $enter->prepare($sql);
$new_item->setFetchmode(PDO::FETCH_ASSOC);
$new_item->execute(array($id));
foreach($new_item as $nw) {
return $nw['response'];
}
} catch (Exception $e) {
echo $e->getMessage();
exit;
}
return "";
}
And $id=1 coming from the database looks like this:
<script type="text/javascript">
function getJobTitle(){
document.getElementById("JobTitle").hidden = true;
document.getElementById("two").hidden = false;
}
function getStartDate(){
document.getElementById("StartDate").hidden = true;
document.getElementById("three").hidden = false;
}
function getEndDate(){
document.getElementById("EndDate").hidden = true;
document.getElementById("four").hidden = false;
}
<?php
echo "$objUser->employer";
?>
<form action="newprofile.php" method="post">
<p><a id="JobTitle" href="#" onclick="getJobTitle()">Add Job Title</a><input type="text" name="jobtitle" id="two" hidden="true" value="Add Job Title"></input></p>
<p><a id="StartDate" href="#" onclick="getStartDate()">Add Start Date</a><input type="text" name="startdate" id="three" hidden="true" value="Add Start Date"></input></p>
<p><a id="EndDate" href="#" onclick="getEndDate()">Add End Date</a><input type="text" name="enddate" id="four" hidden="true" value="Add End Date"></input></p>
<input type="submit" value="submit"></form>
But when this code returns from the database to the page echo "$objUser->employer"; doesn't populate. Meanwhile if I write that code directly on the page it works. What gives?
Databases just store text, not actual instantiated objects. The returned value has no way of knowing what $objUser was when you stored all that text.
There's a lot of things wrong with the way you're trying to go about doing this, you shouldn't be storing all that code in the database for every row. But the most simple way to answer this and point you in the right direction, is that you need to serialize objects in order to store them in the database, and unserialize them after pulling the record out of the database, in order to use them again.
I have a newsletter for one of my sites and I can't the email posted to the mysql database.
Here is the html form code:
subscribe
<h2>newsletter</h2>
<br /><input type="text" name="email" value="" id="email" />
<input type="button" name="submit" onclick="submit_it()" value="OK" />
<script type="text/javascript" charset="utf-8">
function submit_it() {
var cate_value = $('#cate').val();
var email_value = $('#email').val();
$.post("subscribe.php", { email: email_value , cate: category_value }, function(response) {
if (response!='') {alert(response)};
alert('ok');
});
}
</script>
</body>
And here is the php processing code:
$host = "localhost";
$user = "some_user";
$password = "some_pass";
$database = "news";
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
function sql_quote($value) {
$value = str_replace('<?','',$value);
$value = str_replace('script','',$value);
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value) . "'";
} else {
if ((string)$value[0] == '0') {
$value = "'" . mysql_real_escape_string($value) . "'";
}}
return $value;
}
$q = "INSERT INTO emails (email,cate) VALUES (".sql_quote($_POST['email']).",".$_POST['cate'].")";
mysql_query($q);
?>
Any help would be much appreciated because I've been fooling with this for the last 5hrs trying to make it work and I just can't figure it out plus I can't look at it anymore. My eyes hurt now. lol Thanks again.
You should definitely rewrite your code as hobodave suggests. I think something is wrong with your db configuration, though. Try this in the meantime, to execute your query:
$result = mysql_query($q);
if( $result ){
echo( 'OK' );
} else {
echo( 'Invalid query: ' . mysql_error() );
}
Your PHP sql_quote function is very naive with it's str_replace() filtering. It is trivial to bypass this and insert unwanted data in your database.
I suggest the following rewrite of your code:
<?php
$host = "localhost";
$user = "some_user";
$password = "some_pass";
$database = "newsletter";
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
function sql_quote($value)
{
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
return mysql_real_escape_string($value);
}
$email = $_POST['email'];
$category = $_POST['category'];
if (filter_var($email, FILTER_VALIDATE_EMAIL)
&& FALSE !== filter_var($category, FILTER_VALIDATE_INT)
) {
$q = sprintf("INSERT INTO emails (email, category) VALUES ('%s', '%s')",
sql_quote($email),
sql_quote($category)
);
// execute query
} else {
// Do what you want with invalid data
}
I'd also suggest the following changes:
Disable magic_quotes_runtime so you don't need to check, thus you can do away with sql_quote entirely
Use mysqli
Edit:
Why are you even using AJAX to process this form submission? I don't see any benefit in it. You're not doing anything special, just submitting a form.
I'd suggest removing the AJAX altogether and just using the submit button as it's intended.
If you insist though, you can at least temporarily remove it to simplify your testing.
You have a syntax error in your query try this
$email = sql_quote($_POST['email']);
$category = $_POST['category'];
$q = "INSERT INTO emails (email,category) VALUES ('$email','$category')";
You have to use data as key for your data.
$.ajax(url: "ajax_subscribe.php",
method : 'POST',
data: { email: email_value , category: category_value },
success: function(response) {
if (response!='') {alert(response)};
alert('Thank You !');
});