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
Related
So my goal is to use PHP to get data from a PostGreSQL database. I want to use this data in a separate javascript file so I can display it on the screen a certain way that I have my website configured. All the tutorials that I have seen online just puts a script tag inside the PHP file but I cannot do that because my website display javascript code is in the separate file. I just need the numbers to be in the javascript file that I got from the PHP file that got its data from the PostGreSQL database. How can I do this?
I just need help with the means to get to the ends because I have researched on my own but it is always not exactly what I want.
PHP:
<?php
$myPDO = new PDO('pgsql:host=myHost; dbname=myDBName', 'myUsername', 'myPassword');
?>
$result = $myPDO->query("SELECT * FROM table WHERE id = 'someID'");
Now I want to use this row's values in another javascript file. How can I do this?
You could use Ajax for this.
You could so something like this in your JS file:
$.ajax({
type: "GET",
url: 'FILENAME.php',
success: function(data){
alert(data);
}
});
and then in your FILENAME.PHP just return the values.
Your JS should then pull through whatever has been returned, in this case, your database query.
Your JS file needs to request the data from your PHP controller, via an AJAX request. You can then manipulate the returned data object whichever way you like.
We have mainly two methods to pass php value to javascript variable
Simple variable method at the time of first page load
<script>
var js_variable = <?php echo $data_php_variable; ?> ;
//this is working only at the first time of the page load
//you can also parse the data to any format
</script>
Use AJAX call to trigger a PHP request and manipulate return PHP value in JS
$.ajax({
type: "GET", //get or post method
url: 'FILENAME.php', //php request url
data :{}, //optional ,you can send data with request
success: function(res){
// this 'res' variable is the php return data in the form of js data
console.log(res);
}
});
ajax method is more dynamic ,it can use any time request handling
use the javascript ajax to call a php api
pass your data at php in your view file , use something like:
var phpData = JSON.parse("<?php echo json_encode($data)); ?>");
So I have three different separate files:
functions.php (all functions for the database)
main.html (my main program)
main.js (all javascript functions)
Now, I want to call a function in PHP through AJAX. To do that, I need to pass $conn.
$conn = sqlsrv_connect($serverName, $connectionInfo);
It's a resource, so I can't use json_encode.
The way I set the everything up now is that the php-file is required in the html so I can use the functions and when I change the
value of a dropdown, the js is called.
How can I pass the $conn variable to Javascript?
Regards
It doesn't work like that.
You should never be directly making calls to the database from the front-end.
Think of it as three separate levels. Your HTML/JS is the front-end, your PHP is your server, and your Database is on its own level.
So when the user does something on the front-end, say changes the value of a field and you want to update that in the database the following actions should happen:
Event triggers on JS
AJAX is called as a result of the event being triggered
PHP server receives the AJAX request and executes code to modify database
(optional) PHP server sends something back to the front-end to tell it that the request was successful
Read up on the concept of MVC: https://developer.mozilla.org/en-US/docs/Web/Apps/Fundamentals/Modern_web_app_architecture/MVC_architecture
Try this in php code as I assume functions.php
$conn = sqlsrv_connect($serverName, $connectionInfo);
echo $conn;//Don't try echo anything other
In Javascript
$.ajax({
type: "POST",
url: "functions.php",
success: function(data)
{
var conn = data; // here is your conn which comes from php file
}
});
First of all include jquery latest version from cdn
Create an API Url, and use POST method
site.com/api/insert.php // to insert into table
Use $.post() api of jquery to send data
var url = ""; // enter your URL HERE
var postData = {}; // object of post data with table name, cols and values
$.post(url, postData, function(data, status) {
// do what ever you want with data
})
ps: you can also create diff insertion / selection / update / delete api for different table. (recommended)
Read more about $.post() here
I am new to Javascript and PHP. Can anyone let me know how to take javascript variable in php variable and I want to use that php variable in MySQL query to fetch the data from MySQL database. Whether it is possible to take javascript variable directly in MySQL query?
I have tried but I am unable to get the result. I have attached code below
<script>
var baccount = document.getElementById('accountid');
var bacc = baccount.value;
</script>
<?php
$abcd = '"+bacc+"';
$quer=mysql_query("SELECT * from fpay_user where account_id='$abcd'");
$result=mysql_fetch_array($quer);
$rbal = $result['balance'];
echo $rbal;
?>
You need understand the difference of client language and server language.
In your code, JavaScript is executed in browser, while the PHP is executed in your server. To make the PHP knows what happened in the client, your client must send this information to the server, through query string, form post or raw data post.
For your case, you can send an Ajax request from the JavaScript to the server, (using native XMLHttpRequest, or jQuery)
$.ajax({
type: "POST",
url: url,
data: {bacc:value},
});
Then your PHP can access it via $_POST["bacc"]
Do understand that although you could write it in the same file (which is a bad practice), they are executed in different place (client or server)
It is not as simple as that. Javascript runs in the browser (the client) and php runs on the web server (the host). These are two different computers. To pass data from the client to the host, you can make an an http request from javascript to a specific url on the server. When the server sends its response you can process it in javascript again.
An example (using jQuery) would be:
<script>
// success will be called when the server sent a response.
function success(result) {
// result.responseJSON is a javascript object: { balance: 1234 }
let balance = result.responseJSON.balance
}
$.ajax({
url: '/path/to/script.php',
data: {
bacc: baccount.value
},
success: success,
dataType: 'json'
});
</script>
In php you can fetch the passed value, do your query and return the result:
<?php
// get the passed value
$abcd = $_GET['bacc'];
// do the query SAFELY. See explanation below.
$quer = mysql_query("SELECT * from fpay_user where account_id='" . mysql_escape_string($abcd) . "'");
$result=mysql_fetch_array($quer);
// Now return the result as json string
header('Content-Type: application/json');
// This will encode the result as: "{balance: 1234}"
echo json_encode($result);
One very important thing. You should always sanitize the received values with something like mysql_escape_string. If you do not do that, your software is susceptible to SQL injection. I have added this function call to your example.
I'm fairly new to web development and php.
I have a js file with all my functions. In one of the functions I make an ajax call to create a new database record that person A is making a challenge to person B.
JS
var challengeeId = document.getElementById('Challengee').value;
$.ajax({
type:"post",
url: baseUrl+"/site/challenge",
data:{"challengeeId":challengeeId},
cache:false,
success: function(html){
}
});
PHP
$model = new Challenge();
$model->challenger_id = Yii::app()->user->id;
$model->challengee_id = $_POST['challengeeId'];
$model->date_created = date("Y-d-m H:i:s");
$model->status ="pending";
$model->save();
This is fine and saves in table correctly. The table also creates an id for every challenge. I want to know how to return that id so that I can store it as a variable in my JS file for later use. I have an SQL query which returns the ID for me, I just don't know how to return it from the PHP to JS.
Use this sure you get the last id
If using postgresql
$lastID = Yii::app()->db->getLastInsertID('table_sequence');
return $lastID;
If using mysql
$lastID = Yii::app()->db->getLastInsertID();
return $lastID;
since getLastInsertID is accessor method you also call like this too
$lastID = Yii::app()->db->lastInsertID;
return $lastID;
You'll need to return that value back either as a string or maybe a json return and then that becomes the "html" var in your "success" case of the ajax call. You then handle the rest in javascript
You could echo the id in php. the variabele html will then contain the id.
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.