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.
Related
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
I'm trying to dynamically collect some free images from Google using the Web Speech API.
Here's the logic:
I capture the search keyword with the Web Speech API in JS.
I send it to the server (PHP) using an ajax call
Then I process the keyword and send back the results to JS.
Everything works fine if the keyword is just a single word like: Barack, but if I use Barack Obama there is a 500 Server Error and the ajax call fails.
JavaScript
$keyword = 'Barack Obama'; //the $Keyword is created from the result of the Web Speech API, but to make this clearer I just created it manually bc the problem still there anyway.
$.ajax({
type:'POST',
url: '../php/myfunctions.php',
data: {$keyword:$keyword},
dataType:"json",
}).done(function(response) {
console.log('yeah');
})
.fail(function(responseText) {
console.warn('error: ',responseText);
});
PHP
include_once($_SERVER['DOCUMENT_ROOT'].'/php/library/simple_html_dom.php');
$keyword = $_POST['$keyword'];
$keyword = 'Barack Obama'; //IF I manually create the $keyword all is fine but It's not the idea so this line is just to debug this issue.
$keyword = strtolower($keyword); //I tried with lowercases (barack obama).
$keyword = rawurlencode($keyword); //Then I tried a encoding workaround (barack%20obama).
$keyword = str_replace(' ','',$keyword); //Then I tried without white spaces(barackobama).
$url = 'https://www.google.com/search?q=' . $keyword . '&tbm=isch&source=lnt&tbs=sur:fc&sa=X&ved=0ahUKEwjQgMn87ajaAhUOtlkKHdgZB_8QpwUIHg&biw=1745&bih=872&dpr=1.1';
$html = file_get_html($url);
//From here I handle this data and I send it back in a json to JS
echo $url //if I echo the $url these are the outputs:
https://www.google.com/search?q=barack obama&tbm=isch&source=lnt&tbs=sur:fc&sa=X&ved=0ahUKEwjQgMn87ajaAhUOtlkKHdgZB_8QpwUIHg&biw=1745&bih=872&dpr=1.1
https://www.google.com/search?q=barack%20obama&tbm=isch&source=lnt&tbs=sur:fc&sa=X&ved=0ahUKEwjQgMn87ajaAhUOtlkKHdgZB_8QpwUIHg&biw=1745&bih=872&dpr=1.1
https://www.google.com/search?q=barackobama&tbm=isch&source=lnt&tbs=sur:fc&sa=X&ved=0ahUKEwjQgMn87ajaAhUOtlkKHdgZB_8QpwUIHg&biw=1745&bih=872&dpr=1.1
If I copy&paste these 3 URLs in the browser manually there is no problem and all the images appear, but if the $keyword created in JS has 2 words like New York there is a 500 error.
What could be the problem? Greetings.
Instead of
data: {$keyword: $keyword}
use
data: {keyword: encodeURIComponent($keyword)}
And drop the dataType: 'json' since you are definitely not echoing json there.
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
I've searched the internet and found something about using ajax for setting information in my database. I found this page, but it shows how to GET info from your database.
Is it also possible to SET information in the database?
I use this for a schedule.
in my DB I have a table that contains the following columns:
Startdate
Enddate
Productdescription
Expected production
actual Production
Difference
When they create the schedule they only know the first four. The other two need to be filled in automatically. I do this when the production is finished:
I've made a small start about checking if the production is done:
setInterval(function()
{
var currentTime = new Date();
var endProductionTimeMachine1 = <?php echo json_encode($TempomaticRow1[0]['Einddatum']) ?>; // get the enddate from the database via php
var ActualProductionToday = 2100; //just an example value
//Convert mysql date to javascript date
var t = endProductionTimeMachine1.split(/[- :]/);
var endProdTimeMachine1 = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
if(currentTime == endProdTimeMachine1)
{
//set information in the DB
}
},1000);
So I would like to know if I can call a php page that inserts information into my database with a parameter from this page.
Yes, you can.
You can do it with jquery using a post method through ajax.
So, now that you have your vars you have to add a code like this:
$.ajax({
method: "POST",
url: "some.php", //the endpoint in php where your save method is
data: { currentTime: currentTime, endProductionTimeMachine: endProductionTimeMachine1 ...and so on}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
and at your php just do this...
if(isset($_POST['currentTime']){
$currentTime =$_POST['currentTime'];
}
... and so on
After you get all your vars be sure you use (if you are not using a framework) a mysql injection cleanup.
I suggest using mysqli_real_escape_string , after having all your variables and all at your PHP side, you can create your query to set/update info at your db.
More info of Ajax here
Use that page and modify the AJAX call so that it triggers a PHP script which will then update your database. Send all information necessary to the server. In order to change the database, make use of "prepared statements" either via MySQLi or PDO.
Never send a SQL query from a client to a server! Always only send the values and have the server build the query!
For a complete example, you can also take a look at this: http://www.plus2net.com/php_tutorial/display-record-edit.php
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