Passing data from ajax to php to mysql weird problems - javascript

I asked a similar question earlier, but think I got the wrong point across and learned more about security than fixing the problem I'm having. I am having trouble with my ajax request to post data into a php script and then submit it to a database.
Just to make it clear, the site is local and I will have nobody creating an account besides me and I will be the only one accessing it. I will make it secure once I get this step finished.
Current error I am getting: none, but no data after the success in alert("success" + data)
I have googled/worked for 10+ hours just on this... Any help would be greatly appreciated as I am just learning.
Here is my Javascript:
var firstname = String($("#firstname").val());
var lastname = String($("#lastname").val());
var username = String($("#username").val());
var email = String($("#email").val());
var password = String($("#password").val());
Here is the AJAX:
$.ajax({
type: 'POST',
url: 'create_account.php',
data: {firstname_php: firstname,
lastname_php: lastname,
username_php: username,
email_php: email,
password_php: password},
success: function(data) {
alert("success" + data);
}
});
create_account.php:
$firstname = $_POST['firstname_php'];
$lastname = $_POST['lastname_php'];
$username = $_POST['username_php'];
$email = $_POST['email_php'];
$password = $_POST['password_php'];
echo "$firstname";
// Create connection
$connection = mysqli_connect("localhost","root","root","MyDatabase");
// Check connection
if (mysql_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO users (user_id, user_firstname, user_lastname, user_username, user_email, user_password) VALUES (0, '$firstname', '$lastname', '$username', '$email', '$password)'";
$result = mysqli_query($connection,$sql);
mysqli_close($connection);

You have a single quote in the wrong place in your query:
VALUES (0, '$firstname', '$lastname', '$username', '$email', '$password)'";
^^^
try this:
VALUES (0, '$firstname', '$lastname', '$username', '$email', '$password')";

Everything looks fine in the javascript and ajax (at least as well as I can tell without seeing the html source as well.
However you have at least one php error; mysql_connect_errno doesn't exist and wouldn't be called in relation to the mysqli connector.
so try this instead:
$firstname = $_POST['firstname_php'];
$lastname = $_POST['lastname_php'];
$username = $_POST['username_php'];
$email = $_POST['email_php'];
$password = $_POST['password_php'];
echo "$firstname";
// Create connection
$connection = mysqli_connect("localhost","root","root","MyDatabase");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO users (user_id, user_firstname, user_lastname, user_username, user_email, user_password) VALUES (0, '$firstname', '$lastname', '$username', '$email', '$password')";
$result = mysqli_query($connection,$sql);
mysqli_close($connection);
I haven't used the mysqli connector but other than that it looks fine to me. If it still doesn't work I suggest enabling full php debug info - for example adding this to the top of the php file:
ini_set("display_errors", "1");
error_reporting(E_ALL);
EDIT: as hanlet stated you also have a single quote/apos in the wrong spot. (fixed in my example code)

Related

Capturing an IP Address with Ajax involved

I have a button that when pressed, allows the user to see a catalog. I am not collecting any information from the user at this point. I am only collecting what catalog they downloaded. I would like to change this to collect their IP Addresses to insert into my database.
Would all I have to do is create a variable in my PHP file like this:
$ip = $_SERVER["REMOTE_ADDR"];
Then add it into my PDO statement for inserting into the db?
I have read that many recommend checking $_SERVER["HTTP_X_FORWARDED_FOR"] as well. How could I check both and assign it to the one variable?
Am I doing this correctly?
AJAX
$('.downloadButton').on('click', function (event) {
$.ajax({
url: 'downloadCatalogSend.php',
type: 'POST',
data: {
catalog_name: catalog_name,
button_triggered: button_triggered
}
});
});
PHP
$ip = $_SERVER["REMOTE_ADDR"];
try {
$con = getConfig('pdo');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$catalog_download_insert = "INSERT INTO catalog_download_now
(catalog_name, button_triggered, date_sent, $ip)
VALUES(?, ?, NOW(), ?)
";
$catalog_download_stmt = $con->prepare($catalog_download_insert);
$catalog_download_stmt->execute(array($catalog_name, $button_triggered, $ip));
$hasError = false;
echo $hasError;
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
Use the null coalesce operator:
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"] ?? $_SERVER["REMOTE_ADDR"];
This will prefer HTTP_X_FORWARDED_FOR (the client IP if the request came from a proxy) if it is set, else fall back to REMOTE_ADDR (the actual IP the request came from.)
Caveat: HTTP_X_FORWARDED_FOR can be easily forged by the client.
Also note, you have this:
$catalog_download_insert = "INSERT INTO catalog_download_now
(catalog_name, button_triggered, date_sent, $ip)
VALUES(?, ?, NOW(), ?)
";
Drop that dollar sign from $ip -- that should be the field name, not the value you're trying to store in it.

Creating Javascript array via php

After spending an embarrassing number of hours on this, I still can't figure out an answer. I have a Javascript/HTML program that has a large dynamic table in it with lots of buttons in the cells of the table. I'd like to send the user's selections of buttons to a database when the user is finished with the page. I will then use those in the receiving php program to display a graph. I've got all of the values of the buttons into a Javascript array, so now I'd like to send the entire array and then use them as a Javascript array in the new program. Every time I try this, I get no results. Here is an example based on what I've found on stackoverflow:
Sending program:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<script>
var ourObj={};
ourObj.data="4";
ourObj.arPoints = [{'x':1, 'y': 2},{'x': 2.3, 'y': 3.3},{'x': -1, 'y': -4}];
$.ajax({
url: 'testb2.php',
type: 'post',
data: {"points" : JSON.stringify(ourObj)},
success: function(data) {
alert("success");
}
});
</script>
</html>
Receiving php program:
<?php>
// Test if our data came through
echo "starting";
if (isset($_POST["points"])) {
// Decode our JSON into PHP objects we can use
$points = json_decode($_POST["points"]);
// Access our object's data and array values.
echo "Data is: " . $points->data . "<br>";
echo "Point 1: " . $points->arPoints[0]->x . ", " . $points->arPoints[0]->y;
$servername = "localhost";
$username = "xxx";
$password = "yyy";
$dbname = "zzz";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "
INSERT INTO FootprintAction(UserID, ActionValue, fpID)
VALUES (?, ?, ?);
";
if ($stmt = mysqli_prepare($conn, $sql)) {
mysqli_stmt_bind_param($stmt, "iss", $points->data, "1", "1");
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
} else {
//echo "no result from attempt to insert people into fpAction". "<br>";
//echo $sql;
}
}
?>
What I get is a blank screen from the sending program with only an alert saying "success" (i.e., no answer from the receiving program) and no insertion into the database.
Can you suggest what I am doing wrong? Or even better, is there a simple way using php to get a javascript array from a client-side program to a server-side program? The array I'm trying to send is a set of string data, without labels; here's a row of the array:
actions[ 5] = new Array( "Install Photovoltaic (Solar) Panels","6.33","1020","33121","0","25","149.8","0","0","0","1","1","Photovoltaic (solar) systems allow you to produce green electricity on your own rooftop. Vendors often offer both purchase and lease options. ","3","1.5","10","5.75","0");
I'd like to end up with a Javascript array in the receiving program identical to that in the sending program.
Thanks!!!

$_GET PHP is misbehaving

I'm a javascript newbie and I'm writing an application using javascript with php on the server side, I'm trying to use AJAX to send data to my php script. This is my code below
Javascript:
$(document).on("click", ".uib_w_18", function(evt)
{
var lecturer = document.getElementById("reg_name").value;
//var lecturer = $("#reg_name").val();
var dept = document.getElementById("reg_dept").value;
var level = document.getElementById("reg_level").value;
var course = document.getElementById("reg_course").value;
var start = document.getElementById("reg_time_1").value;
var ade = 2;
window.alert(lecturer);
var dataString = '?ade=' + ade+'&lecturer='+lecturer+'&dept='+dept +'&level='+level+'&course='+course+'&start='+start;
$.ajax({
type: "GET",
url: 'http://localhost/my_queries.php',
data: dataString,
success: window.alert ("I've been to localhost.")
});
window.alert(dataString);
});
and on the server side:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbname = "myDatabase";
$dbpass = null;
//Connect to MySQL Server
echo "yo";
$con = mysqli_connect($dbhost, $dbuser,$dbpass,$dbname);
$level = $_GET['level'];
$lecturer = $_GET['lecturer'];
$sql = "INSERT INTO level1(message, department)
VALUES ($level,'Jane')";
$sql2 = "INSERT INTO level1(message, department)
VALUES ($lecturer,'Jane')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
?>
now the problem is '$sql1' executes successfully but '$sql2' doesn't. I've been on this for a while and found out that $_GET in the script only works for numerical data. I've confirmed that the problem is not from the data type of my table, I can insert literal strings directly from PHP, I'm also confirmed that "dataString" collects data just like I want it to. (window.alert(dataString);) displays correct output.
I feel like I'm missing something very basic but I just can't figure out what it is. and i felt extra pairs of eyes would help, any help would be appreciated, Thank you.
The proper way to pass "dynamic" SQL queries is like so :
$sql = "INSERT INTO level1(message, department)
VALUES ('".$level."','Jane')";
$sql2 = "INSERT INTO level1(message, department)
VALUES ('".$lecturer."','Jane')";

Registration form isn't properly Connecting to MySQL

Ok, so I've successfully linked a Contact Form for my website to a MySQL database and I'm super stoked about figuring it out, however on my registration page my code isn't working. I ran this connection check:
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
echo "It's Working!";
}
and it says: "It's working!" So i know i've established a connection to my SQL database.
Let me try to clarify further:
I've got 2 main files for this particular program (obviously we won't be needing to care about styles.css or the linked files for other pages in my site): register.php and db.php. Here is my code for both. It's simply a project website so i don't care if people see/use my code... It's not working anyway so knock yourselves out, LOL!
First, db.php:
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'forms1');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
Now here's the php in register.php, which I've place at the top BEFORE any HTML at all:
include ("db.php");
$msg = "";
if(isset($_POST["submit"]))
{
$name = $_POST["name"];
$lname = $_POST["lname"];
$a1 = $_POST["a1"];
$a2 = $_POST["a2"];
$city = $_POST["city"];
$state = $_POST["state"];
$zip = $_POST["zip"];
$phone = $_POST["phone"];
$email = $_POST["email"];
$password = $_POST["password"];
$name = mysqli_real_escape_string($db, $name);
$lname = mysqli_real_escape_string($db, $lname);
$a1 = mysqli_real_escape_string($db, $a1);
$a2 = mysqli_real_escape_string($db, $a2);
$city = mysqli_real_escape_string($db, $city);
$state = mysqli_real_escape_string($db, $state);
$zip = mysqli_real_escape_string($db, $zip);
$phone = mysqli_real_escape_string($db, $phone);
$email = mysqli_real_escape_string($db, $email);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
$sql="SELECT email FROM users WHERE email='$email'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
$msg = "Sorry...This email already exist...";
}
else
{
$query = mysqli_query($db, "INSERT INTO users(name,lname,a1, a2, city, state, zip, phone, email, password) VALUES ('$name', '$lname', '$a1', '$a2', '$city', '$state', '$zip', '$phone', '$email', '$password')");
if($query)
{
$msg = "Thank You! you are now registered.";
}
}
}
mysqli_close($db);
I should probably mention that JavaScript is included in the HEAD section of my HTML:
(function(H){H.className=H.className.replace(/\bno-js\b/,'js')})(document.documentElement)
$(document).ready(function() {
$('form.required-form').simpleValidate({
errorElement: 'em',
ajaxRequest: true,
completeCallback: function($el) {
var formData = $el.serialize();
}
});
});
$("form[name='form1']").submit(function(){
.... JS code ....
return error;
});
</script>
<script type= "text/javascript">
var RecaptchaOptions = {
theme: 'clean'
};
Well, I tried to include the HTML code for the form but it wasn't appearing properly, but believe me when i tell you that ALL the inputs of the the form fields have a name="" that corresponds to the fields within my table within my database within MySQL. The HTML is most certainly not the problem. I've check syntax and spelling over and over. It's not the HTML. Somewhere there is an error, though.
PLEASE HELP!!!
Thank you all very much.
-Maj
P.S. I purposely deleted the opening and closing php/html tags here in these examples so it'd be easier to read, but i have them placed in my original code.
After that if($query){ } block try adding else { print(mysqli_error($db)); }
perhaps there's an error, but what is the response you got from register.php?
you should start to debug your source code, but if you don't use a debugger, put some "die(SOME VARIABLE);" to locate your trouble area and without javascript, for the first. Just use some simple html-formular and to get row datas, put the answer into <PRE> tags ( or use curl in a terminal, i like this way, but for you it is not necessary ).
If you don't debug your php-code or you your browser-relevant-code, means "html, css, javascript, ..." (you can see with firebug, what data you are sending and what is coming back), you can use echo "INSERT .... BLA ...$VAR ...;" and copy-paste the SQL-Statement and testing it in PhpMyAdmin, to see you get a proper statement, maybe there is a type-converting-problem or many other thinks are possible.
If everything is going well, it is probably some trouble in your javascript-code. But probably you need to convert a type of some variable, you should copy and paste your SQL-Statement and execute it in phpmyadmin to make a verification of your SQL-Statements which you put in your Php-Code. Cheers.

Having Issue on Getting Second Session Variable in JavaScript

I have a PHP file getting data from my SQL database and I am trying to set and get two session variables like $_SESSION['fname'] and $_SESSION['userID'] by $theFName and $theId.
$email = $_POST['email'];
$pass = $_POST['pass'];
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DATABASE);
$sql = "SELECT id, email, fname, lname, type FROM users WHERE `email`=? AND `pass`=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ss', $email,$pass);
$stmt->execute();
$stmt->bind_result($theId,$theEmail,$theFName,$theLname,$theType);
if ($stmt->fetch()) {
echo 'true';
$_SESSION['LOGIN_STATUS'] = true;
$_SESSION['fname'] = $theFName;
$_SESSION['userID'] = $theId;
} else {
echo 'false';
}
in JavaScript file I have
<script>
var tok = "var UID = "<?php echo $_SESSION['userID']; ?>";
console.log("The Id is " + UID)
</script>
but I am getting empty string!
can you please let me know what I am doing wrong?
I'm not quite sure I understand what you are trying to do in the JS file, but it is not valid JS in any case - the quotes don't match and it seems like you are trying to do an assignment inside a string.
I think what you are looking for is something more along the lines of this:
<script>
var UID = "<?php echo $_SESSION['userID']; ?>";
console.log("The Id is " + UID)
</script>
However, please note that dynamically generating JS files using PHP is likely not the best way to go about this. Check out this SO answer on the various methods you can use to pass variables from PHP to JS, along with their various pros and cons.

Categories