Creating Javascript array via php - javascript

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!!!

Related

Securely communicate with mysql server (MariaDB) using javascript and php (NO jQuery)

I am trying to achieve two things:
(1) Get text from a contenteditable div, use javascript to send that text to php, use php to send that data to a MySQL database and save it
(2) retrieve the saved data/text and reinsert it into a contentedtiable div
All of this whilst NOT using jQuery
What I've got so far:
index.html
<body>
<div contenteditable="true" id="editable"></div>
<button onClick="send_data();">Save text</button>
<button onClick="retrieve_data();">Get text</button>
</body>
javascript.js
function send_data() {
var php_file = "connection.php";
var http_connection = new XMLHttpRequest();
http_connection.open("POST", php_file, true);
http_connection.onreadystatechange = function() {
if(http_connection.readyState == 4 && http_connection.status == 200) {
alert(http_connection.responseText);
}
}
http_connection.send(document.getElementById('editable').innerText);
}
function retrieve_data() {
// I do not know what to put here
}
connection.php
<?php
$servername = "localhost";
$username = "mysql_user";
$password = "secure_password";
$dbname = "some_database";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
if(!conn) {
echo 'No connection';
}
if(!mysqli_select_db($conn,'some_database')) {
echo "No database";
}
$some_val = $_GET['text']
$sql = "SELECT text FROM some_database";
$result = $conn->query($sql);
echo $result;
$conn->close();
?>
Edit: what my code fails to do is to upload text as well as recieve text.
Some problems in the js:
http_c is not defined
readyState is spelled incorrectly
the send method needs to be outside the onreadystatechange callback
Once those things are corrected, program should give different, which is not to say expected, result.
Other things:
The js is sending a 'POST' request. The php is looking for $_GET["text"] which will give undefined error. I'm speculation this $sql = "SELECT text FROM some_database"; will fail (if it reaches that line) unless there is a table in the database named "some_database".
Suggest, for starters, get the ajax working by short-circuiting the code in connection.php to something like
echo "You are here";
exit;
Then gradually working forward between the js and the php until programs give you what you want.

Having issues interpreting json inside php and passing it to mysql

I am new to php and I am not sure how to debug this.
I am trying to pass json to a php page and then send that data to mySQL.
I think it is having issues interpreting the data inside the php file or getting the information to the php page. When I open the php file it gives signs that it is properly accessing the database.
Here is my javascript code:
var request = new XMLHttpRequest();
request.open('POST', 'http://website/saveF.php', true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
request.send(bInfo);
This is taking information in and passing it to a php file to then be added to a mySQL database.
Here is my php code:
This is decoding the jSon and then itterating over each entry inside the array. It then asks the question if it has a website listed or not and stores it into the appropriate table.
//as long as the connection is good then we keep it live.
include_once "head.php";
if ($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
//gettting the information from the front end (index.html)
$inputJSON = file_get_contents('php://input');
//decode all the previously encoded information
$postThings = json_decode($inputJSON, TRUE);
$input = filter_var($postThings, FILTER_SANITIZE_STRING);
//create a variable the is the total length of our array
$totalNum = count($input);
//arrays start at 0
$i = 0;
//you can see where this is going. We have a while loop that will continue as long as i is less than totalnum. Ask me why i didn't use a for loop.... I don't have an answer.
while($i < $totalNum){
$var0 = $input[$i][0];
$var1 = $input[$i][1];
$var2 = $input[$i][2];
$var3 = $input[$i][3];
$var4 = $input[$i][4];
$var5 = $input[$i][5];
$var6 = $input[$i][6];
if($var1 == "Not Listed") {
$sql = "INSERT INTO missing(cName, website, rating, phone, id, address, placeType) VALUES ('$var0', '$var1', '$var2', '$var3', '$var4', '$var5', '$var6')";
}else{
//here we set the information into the database.
$sql = "INSERT INTO companies(cName, website, rating, phone, id, address, placeType) VALUES ('$var0', '$var1', '$var2', '$var3', '$var4', '$var5', '$var6')";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$i++;
}
First, note that this line:
$input = filter_var($postThings, FILTER_SANITIZE_STRING);
Will return FALSE if sanitization fails on any of the array elements. In your code, you should be testing if($input) immediately after the sanitization.
Furthermore, you will want to sanitize your inputs further to avoid SQL injection and XSS attacks. (e.g. remove SQL escape characters and other injectable characters).
http://php.net/manual/en/mysqli.real-escape-string.php
Last, it is recommended that you use bound parameters or fully sanitized inputs to avoid a SQL injection attack.

I cannot get the AJAX code to accept the value from "onclick"

I apologize for the grammatical errors in my writing, I am not very good in language at all. Conceptually, I have some knowledge in software however, I have never written a line of code...
MY SOFTWARE DESCRIPTION:
I have thousands of songs/videos parked in my computer. Computer audio is connected to AV receiver and video is connected to a TV (for video). I'd like to write a piece code that I can play the music/video from the mobile devices, remotely. Here is my sequence for playing song:
use XAMMP, create the database holding the list of song/video names
completed and working
create html page, connect to the database, read, and display song names
completed and working
when click on the song name, a SongID is passed to Ajax code for posting SongID back to the server and then update the database with PlayID
I cannot get Ajax code working here!
other code will read PlayID from the database and play the song via VLC player
Any help would be appreciated.
<!DOCTYPE html>
<html>
<body>
<div id = "SongList">
<?php
// Connect to mysql database
$servername = "localhost";
$username = "NangHa";
$password = "";
$dbname = "ListSong";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// retrieve song list from mysql database table nangha_SongList
$sql = "SELECT * FROM nangha_SongList";
$result = $conn->query($sql);
if ($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$song = (string)$row["SongID"] . " - " . $row["SongName"];
?>
<!-- display list of songs with the onclick to call addSongFunction
and pass the song id - $row["SongID"]
-->
<p id = "<?php echo $song;?>" onclick="addSongFunction(<?php echo $row["SongID"];?>)"><?php echo $song;?></p>
<?php
}
}
// close the database connection
mysqli_close($conn);
?>
<script>
function addSongFunction(SongID){
//convert song id to integer for testing
var songID_STR = SongID.toString();
var ID_SONG = SongID;
// pass song id string to SongSearch div for testing
document.getElementById("SongSearch").innerHTML = songID_STR;
// display song id
alert(+ ID_SONG);
// SO FAR IS GOOD UP TO THIS POINT
// JUST DON'T KNOW HOW TO GET AJAX WORKING
$.ajax({
type: "POST",
data: {
songID: ID_SONG
},
url: "UpdateKaraoke.php",
dataType: "json",
async: true,
beforeSend: function(){
alert(good);
$(".ajaxTest").text("Trying to update ...");
},
success: function(data){
alert(+ data.a);
}
});
}
</script>
</div>
</body>
</html>

PHP code not returning correct MySQL result

I'm querying a set of data from MySQL on a hosted server. When I did it on my local machine, it worked fine, but on the hosted server, it's not returning anything. The weird thing is, when I use this GUI for the hosted environment to run the same query, it does return the results.
So here are some codes, etc.
This is index.php:
<?php
$servername = "username.db.theservername.ether.com";
$mysqllogin = "username";
$mysqlpassword = "thepassword";
$dbName = "StepsMath";
$conn = new mysqli($servername, $mysqllogin, $mysqlpassword, $dbName);
if($conn->connect_error){
die ("connection failed: " . $conn->connect_error);
echo "connection failed.";
}
$set_name = 'test_set';
$query = "select word, definition from word_list where set_name = '$set_name'";
$result = $conn->query($query);
$conn->close();
// *********************************************
echo $query; // <-------- *******this prints the query*******
// *********************************************
$result = mysqli_fetch_array($result);
?>
<!DOCTYPE html>
<html lang="en"><head>
<title>this is a title</title>
<script type="text/javascript">
var json = '<?= json_encode($result) ?>';
var word_list = JSON.parse(json);
console.log(word_list); //line 24
console.log(json); //line 25
function getUserId(){
return '<?= $user_id ?>';
}
if(!getUserId()) window.location = 'login.html';
</script>
</head>
<body>body stuff</body>
</html>
Table word_list only has three columns: word, definition, and set_name
The above code is supposed to return rows of words and definitions. Instead, as I check in the browser console, it returns the following:
{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}
This is the query that runs:
select word, definition from word_list where set_name = 'test_set'
If I copy that exact query and run it in the MySQL GUI in the hosted server,
the following is returned:
So to summarize the question, why is there a discrepancy in the result between the GUI and the code??
change this line:
$result = mysqli_fetch_array($result);
to this:
while ($row = mysqli_fetch_assoc($result)) {
$res[] = $row;
}
var_dump($res);
The information you previously got: {"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null} are all mysqli_result properties.
Read this, it will help you uderstand what you did wrong:http://php.net/manual/en/class.mysqli-result.php

Passing data from ajax to php to mysql weird problems

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)

Categories