Trouble with inserting JS variable into MySQL table with PHP with AJAX - javascript

I am a pretty much a beginner to all of these technologies, I have been stuck all day on what I thought would be a fairly simple process. Basically, I'm trying to pass a parameter in a JS function through to my PHP code using AJAX, and then inserting the parameter into my database.
The JS function in my .html file.
function pushData(paramData) {
$.ajax({
url: "databaseStuff.php",
type: "post",
data: paramData
});
}
I wish to insert into my SQL table whatever I have put into the Parameters. For example the below code should create 3 new database entries. I have these hooked up to buttons in my actual project.
pushData('It is Wednesday');
pushData('My Dudes');
pushData('AHHHHHHH!');
databaseStuff.php
<?php
$mysqli = new mysqli("localhost", "root", "default", "testDB");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " .
$mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$paramData = $_POST['paramData'];
$sql = "INSERT INTO testDBtable (Name, Text) VALUES ('Joe', '$paramData')";
?>
My PHP is successfully connecting to the MySQL DB since I am getting the proper 'localhost via TCP/IP' message, however, I am getting stuck on:
"Notice: Undefined index: paramData in C:\wamp64\www\databaseStuff.php on line 23
Help is appreciated! I am not concerned with SQL injection vulnerability as this code will never leave localhost.

Try writing your Ajax data parameters like this
data: {
'paramdata':paramdata
}
Also, you never actually queried your data.
mysqli_query($mysqli, $sql);
But with the error that you're getting, it's likely because of the ajax data parameters.

If you just want to correct your code, replace the AJAX query with this:
$.ajax({
url: "databaseStuff.php",
type: "post",
data: {'paramData': paramData}
});
However, you should not concatenate user input with sql query directly because of SQL injections, I suggest you to use parametrized queries. Here is the PHP manual page with explanation and examples

Related

404 not found - JS not sending variables to PHP

I am trying to send some variables to PHP script and then to upload them in MySQL db.
Here is my JS script:
$.ajax({
url: '/insert.php',
type: 'POST',
data: {endadres:endadres,stadres:stadres,amount_of_carriers:amount_of_carriers, price_finalized:price_finalized },
success: function(data) {
console.log(data);
}
})
All of variables are extisting inside the same function (I checked it via "alert()").
Here is my PHP code:
// Check connection
if($link === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_REQUEST['FirstName']);
$last_name = mysqli_real_escape_string($link, $_REQUEST['LastName']);
$start_adress = $_POST['startadress'];
$end_adress = $_POST['endadress'];
$Price = $_POST['finallprice'];
$CarriersQuant = $_POST['carriersamo'];
// Attempt insert query execution
$post = "INSERT INTO Orders (FirstName, LastName, StartAdress, EndAdress, Price, CarriersQuant) VALUES ('$first_name', '$last_name', '$start_adress', '$end_adress', '$Price', '$CarriersQuant')";
LastName and FirstName are taken from .html, and I can upload them into my DB, but I am not able to get variables from js.
Error from console:
The variable names in the ajax post doesn't correspond with what you try to extract in the receiving end (PHP). If you stick with these names in JavaScript:
data: {
endadres,
stadres,
amount_of_carriers,
price_finalized
},
You must use the same key to collect them in PHP:
$foo = $_POST["endadres"]
To debug, I often find it useful to add this debug output to see all posted variables:
var_dump($_POST);
On a second note (unrelated to your question though), your SQL insert statement is very dangerous. You are concatenating the variables directly from the external request into the database query string, which means that a potential offender could post something like:
carriersamo: "'; DROP TABLE Orders;"
which would drop your Orders table from your database. I recommend you read up on PHP's PDO module, where it's quite easy to prepare "safe" statements to the database. http://php.net/manual/en/book.pdo.php

Errors while parsing invalid JSON passed from PHP to AJAX

I'm trying to parse JSON sent by PHP.
JSON:
[{"id":"1","value":"1"},{"id":"4","value":"1"},{"id":"2","value":"1"},{"id":"3","value":"1"},{"id":"4","value":"1"}]
I'm trying to parse it to get the id and pass it to another JavaScript function and I'm continuously calling the PHP. When I tried $.ajax, $.get, $.getJSON and used JSON.parse and parseJSON, I get this error:
Uncaught SyntaxError: Unexpected token <
because the JSON looks like this:
id: id: id: html> 1id: 4id: 1id: 2id: 3id: 4id: id: id: >
I tried to fix it using JSON.stringify, which caused this error:
Cannot use 'in' operator to search for 'length' in
and now I'm stuck and have no idea how to fix this.
test.php:
<?php
$link = mysql_connect("localhost", "root", "password");
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db = mysql_select_db("example");
$sql = "select * from data";
$x = mysql_query($sql);
$emparray = array();
while ($row = mysql_fetch_assoc($x)) {
$emparray[] = $row;
}
echo json_encode($emparray);
mysql_close($link);
?>
heatmap.html:
<script>
$(window).ready(function(){
$.ajax({
url:'test.php',
data:"{'id':'1', 'value':'1'}",
contentType: "application/json; charset=utf-8",
datatype: 'json',
success: function (data){setInterval(function(){
/* if I use parseJSON(data), I get "Unexpedted token <"
error */
$.each(data, function (id, value){ // error occures here
liveHeatMap(id); //Never called
});
}, 10000)}});
});
</script>
I think the problem is that the JSON is invalid. I have tried so many things and looked at many other similar problems but I still cannot fix it.
Remove the contentType and dataType properties in your AJAX request, and use an object (rather than a string) for your data. In your success function, remove the setInterval and manually parse the JSON string returned using JSON.parse(data). This ensures you have the most control over the data to prevent jQuery from causing problems (and also makes it clearer). jQuery may be interfering with the data in the process and you want the complete raw data.
It looks like you're receiving HTML. Common causes:
Your AJAX URL is pointing to the incorrect place (and it may not seem obvious -- try ./test.php or using an absolute path).
Your PHP is not killed after echoing the JSON. Replace mysql_close($link) with die() as when the script ends, all database connections are automatically closed anyway.
If you're still having issues, run these commands and comment their output:
console.log(data);
console.log(typeof data);

Errors when attempting an ajax POST call to PHP to return SQL query variable to jquery

Im trying to trying to return a PHP variable which is made of a SQL query to the same database using jquery.
At the moment my method does not work but i cant figure out why. Currently getting the following messages on the PHP response along with the error alert configured in the js function:
Warning: Illegal offset type line 55
{"average":null}
Im very new to PHP and server side programming, so an explanation of where i am going wrong would be really good. I am sure it is just a really simple misunderstanding i have with how i am going about this.. its baffling me so far though!
javascript function to make ajax call to PHP page
so here i have defined an array and added 2 values to it to post to the PHP page.
once recieved i want PHP to change the value to one it will get by doing an SQL query
var javascriptvalue = []
javascriptvalue["id"] = "the id";
javascriptvalue["name"] = "the name";
function averageRecall() {
$.ajax({
type : 'POST',
url : 'recall.php',
data: JSON.stringify(javascriptvalue),
dataType : 'json',
success : function (result) {
console.log(result); // see too what we get in the request
console.log(result.average);
},
error : function () {
alert("error");
}
PHP:
Here PHP should run a query against the DB and return a single value into the variable $avg which will be passed to an array, coded to JSON and then echoed back into my JS callback function.
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$avg = $conn->query("SELECT AVG(`Answer`) AS AvgAnswer
FROM (
SELECT `multi1` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `multi2` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `multi3` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `multi4` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `multi5` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio1` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio2` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio3` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio4` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio5` AS Answer
FROM `zc_Answers`
) AS s1");
if (!$avg) {
echo 'Could not run query: ' . mysql_error();
exit;
}
header('Content-Type: application/json');
$avg2 = array('average' => $_POST[$avg]
);
echo json_encode($avg2);
$conn->close();
?>
First , try adding this to your php file because it doesn't return a JSON response :
header('Content-Type: application/json');
$avg = array(
'average' => $avgcalculation // you can try sending just a number to see if the script works excluding your query
);
echo json_encode($avg);
then , in your success function of javascript you have :
dataType : 'json',//So we need to do the header() step in php
success : function (result) {
console.log(result['average'])// ???????
},
You try to get an item of a javascript array by string index ... which is not possible.
1) You write dataType:json <<< So, the result variable is a object ! So you can access average value with :
success:function(result){
console.log(result); // see too what we get in the request
console.log(result.average); // thats all
}
UPDATE : in order to help you ._.
your php script is failing too because you are retrieving POST values that doesn't exist because you are not sending them !
Please read the documentation of $.ajax() here.
Try first with a simple script in php to see if your javascript works. Comment everything just let 2 lines.
header('Content-Type: application/json');
$avg = array(
'average' => $_POST["javascriptvalue"]
);
echo json_encode($avg);
then in your javascript file add the data tag (because you need to retrieve data in your server !)
data:{
javascriptvalue:"I'm sending this to php so it can be retrieved in my php script"
},
Finally your success javascript function should be executed without problem with :
success:function(data){
console.log(data);//an object with average property (data.average)
}
It should work anyway this is not dificult, read the documentation
"data: avg" in the Ajax call is the data you want to send to the PHP (your page form values) that's why "avg" needs to be defined in the javascript before making the ajax call, that's why you get "avg is undefined".
You need to create the variable and somehow fill it with the form values.
For the PHP if it is on a server you need to work a little bit more like Carlos explained.
I give you some example code from a project I'm working on:
JS CLIENT SIDE
//jsonvar is an array
jsonvar["id"] = "the id";
jsonvar["name"] = "the name";
$.ajax({
url: url_webservice,
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(jsonvar), //turn jsonvar into json to send to the php server
})
.done(function(result) {
console.log("Show the result from the PHP in the console", result);
// Do all you want with the result
})
.fail(function(err) {
console.log(err.responseText);
// Do all you want in case of error
});
});
PHP SERVER SIDE
header('Content-Type: text/html; charset=utf-8');
//Get the data from the POST
$input_data = json_decode(file_get_contents("php://input"), FILE_USE_INCLUDE_PATH);
if(is_null($input_data))
{
trigger_error('Error empty input data in server.php', E_USER_WARNING);
}
//Do what you want with input data, sorry not familiar with mysql code.
echo json_encode($result); //Back to the client

Ajax to pull data from mySQL

I'm currently trying to set up an easy temperature monitoring system for our lab. It's controlled through a web interface which plots the temperature vs. time data in a Dygraph. The temperature data is written into a mySQL DB. I'm trying to add another input field which can be used to select a certain time range to plot.
I'm currently using a jQuery datebox to select the time window which seems to work fine. I'm sending an AJAX request to a PHP script which queries the DB. Instead of showing me the right data points, the PHP script just outputs an internal server error (500). The script works fine when the $_POST section of the PHP and the data part of the jQuery script is deleted.
My most recent JS code is:
$("#UpdateGraph").on("click", function(){
var startDate = $("#datestart").val();
var endDate = $("#datestop").val();
$.ajax({
url: "updateGraph.php",
data: {start : startDate,
stop : endDate},
datatype: "json",
type: "POST",
success: function(data) { DyGraph(data); }
});
});
The jQuery code is housed in a $(document).ready() environment.
The corresponding PHP script looks like this:
<?php
$conn = new PDO("mysql:host=localhost;dbname=temperature", "USERNAME", "PASSWORD");
$results = array();
$startDate = $_POST['start'];
$stopDate = $_POST['stop']:
$query = "SELECT atime,temperature FROM temp WHERE atime BETWEEN '" . $startDate . "' AND '" . $stopDate . "';" ;
$stmt = $conn->prepare($query);
$stmt->execute();
while($result = $stmt->fetch(PDO::FETCH_ASSOC)){
$results[] = $result['atime'].",".$result['temperature'];
}
print_r(json_encode(implode("\n+",$results)));
?>
Any advice what I'm doing wrong? Thanks a lot!
I guess, the source of your error is a syntax error in line $stopDate = $_POST['stop']:
There is a colon at the end of the line. You should change it to semicolon.
Syntax errors in php scripts at the server will show error 500 in http clients. I suggest you to use a linter to avoid this kind of errors. All the popular editors have plugins for this.

How to use AJAX and JSON to get data returned from a PHP file

For starters this website is being run on a Debian machine.
I have a SQLite3 database that has current news articles in it. I am trying to use PHP to query the database for these articles, and pass it as JSON to AJAX, so it can be displayed on my webpage. Right now nothing is being shown and I don't know where the error is.
Here is the PHP code to get the information from the database:
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('website.db');
}
}
$db = new MyDB();
$result = $db->query('SELECT * FROM news');
echo json_encode($result);
?>
Here is the JavaScript where the AJAX is located:
<script type="text/javascript">
function getNews()
{
console.log("firstStep");
$(document).ready(function()
{
console.log("secondStep");
$.getJSON("http://localhost/getNews.php",function(result){
console.log("thirdStep");
$('news').append(result); // display result
});
});
}
I think the error is occurring around $.getJSON("http://localhost/getNews.php",function(result), as in the console, thirdStep is never being outputted.
This is the HTML it should be appending to:
<div id = "newsEntry"> <news> test </news> </div>
Any help would be appreciated.
To find out what's going on, you might want to add an error handler:
$(document).ready(function() {
$.ajax({
url: "http://localhost/getNews.php",
dataType: "json",
success: function(result) {
console.log("thirdStep");
},
error: function(err) {
alert(err);
}
});
})
By default, the web server serves content as application/html. So when you simply echo a JSON string, it's treated like text on a html page. To really return JSON from your server, you need to specifically set it.
Include this line before your echo:
header('Content-Type: application/json; charset=utf-8');
Edit
On inspection of you PHP code, you are missing one line. Note that $db->query() returns you an SQLite3Result. You need to call:
$array = $result->fetchArray(SQLITE3_ASSOC); // get an associative array first
$json = json_encode($array);
header('Content-Type: application/json; charset=utf-8');
echo $json

Categories

Resources