How to take javascript variable in php mysql query? - javascript

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.

Related

Passing JS variables to a PHP file (using ajax) in order to update SQL table [duplicate]

I have a problem sending data with an AJAX query to a php file, basically I use post request to send some data just for testing it out, the request is successful when I checked with developer tools in Chrome, as I can see the data that was sent , but the variable $_POST[] in php is always null, and don't understand why, because my data was sent to the php file.
Tried all kind of possibilities found on here, non of them will let me to go further, all of them will leave my $_POST[] empty. I modified the values inside the data attribute I added or removed content-type but nothing worked.
Here you have my jQuery code.
$.ajax({
method: "POST",
url: "2.php",
data: { name: 'JohnDoe', age: '19' }
}).done(function( msg ) {
alert(msg);
});
This is my PHP code.
<?php
$user=$_POST['name'];
var_dump($user);
?>
Errors
$user=$_POST['name'];
//ERROR - Notice: Undefined index: name in G:\xampp\htdocs\weather\2.php on line 6
//Expected result is 'JohnDoe'.
var_dump($user);
//this is Null
//Expected result is to contain some data
This are my two results I get in php.
The html and php files are in the same folder.
You are making two HTTP requests.
The first one using JavaScript, where you make a POST request and alert the response.
You can see the data from the response there.
You make the second request by typing the address into the address bar, where you make a GET request and have the response rendered as a webpage.
$_POST contains the POSTed data from the current request, not the data from any previous request.
The data you POSTed when you made the first request is not available when the PHP program runs again using the second request as input.
If you want to access that data then you need to explicitly do something to make it persist. This could be linked to the browser (so different users would not see each others data) — such as in a session or a cookie — or it could be independent of the browser — such as in a database — so every visitor to the site could see the data.

How do I transfer the PHP variables to another javascript file?

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)); ?>");

How to pass resource from php to javascript

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

Can I use AJAX 'POST' to post data to a JSON file on my server?

I just want the easiest/most simple way to get my data from an AJAX form using 'POST' the data the user entered on my server.
So if the user leaves their name in the input form on the page, then AJAX POST's the data to a JSON file on my server.
Is this possible? Is this the quickest way to get the data that is entered?
Thanks in advance!
*can someone tell me why this got downvoted? Am I violating any terms? I would just like to know in the future. Thanks. :/
Ajax file directly can not write to a file in your server. But you can achieve this by creating simple php script say savejson.php on your server.
Your form:
<form>
<input type="text" id="name" name="name">
<button type="submit" id="submit-btn">
</form>
<script>
$('#submit-btn').on('click', function(e) {
e.preventDefault();
if( $('#name').val() ){
$.ajax({
url : 'savejson.php',
method : 'post',
data : { 'name': $('#name').val() },
success : function( response ) {
alert( response );
}
});
}
});
</script>
Your savejson.php:
<?php
$fp = fopen('names.json', 'w');
fwrite($fp, json_encode($_POST['name']));
fclose($fp);
?>
Ajax is a term that more-or-less just means "Make an HTTP request from JavaScript".
You can use it to make a POST request. You can use it to make the body of that request a JSON text.
You can't POST to a file, only to a URL. You would need server side code that would be responsible for taking the data in the request and writing it to a file.
Yes. This is a rather common question and you'd do good to take a look at the following questions as well:
How can I use JQuery to post JSON data?
Jquery Ajax Posting json to webservice
Essentially, you use a client-side language (Javascript) to send a POST request to your backend. Naturally, you will then require a backend language (such as PHP or node.js).
I'll provide an example:
JS (jQuery):
$.post("http://yourURL.com/backend.php",{
data: {
"name" :"John Smith",
"vehicle":"TARDIS"
}
}).success(function(response){
console.log(response)
//do something with the response
});
PHP
<?php
$data = json_decode($_POST['data'], true);
$name = $data['name'];
$vehicle = $data['vehicle'];
echo "Welcome {$vehicle}-driving $name!";
?>
Your PHP especially should include error checking among other things, but this will suffice for a simple example.
In your console, upon executing the AJAX request you will then see the following:
Welcome TARDIS-driving Doctor!
Which is the output from your PHP file
Sorry to jump in late here.
var name = $('#name').val();
$.ajax({
url : 'somefile.php',
method : 'post',
data : { 'name': name },
success : function( response ) {
console.log( response );
}
});
This will do the trick.
You cannot write to any file using JavaScript alone. Just cookies or local (or session) storage.
AJAX POST sends data to server. The data is in JSON format. You understand this part already.
On server, there needs to be a API to consume this JSON and write it to a file, or better store it in a database.
More questions:
Can it directly write to a file? No
Can API write to the file? Yes, its technically possible but not advisable
How do others do it? They take JSON response and write it to a database in server side code.

How to pass a value from JavaScript in php?

Translate translator from Google. So that did not swear if something is not clear. Itself from Russia.
The question arose. How to pass the value of the alert in the javascript in the variable $ value in php, and write it in the case file. And another question: how to hide the alert? or use instead to visually it was not visible, but the value was passed?
//a lot of code
{
console.log(data);
alert(data['value']);
}
});
So. Also there is a PHP script that writes logs (current page and the previous one) to a file. According to this principle here:
//a lot of code
$home = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$referer = $_SERVER['HTTP_REFERER'];
$value = how the value of the java script to convey here?;
$lines = file($file);
while(count($lines) > $sum) array_shift($lines);
$lines[] = $home."|".$referer."|".$value."|\r\n";
file_put_contents($file, $lines);
It is necessary that the value of js is transferred to the php-script and write to the file. How to do it? Prompt please. I am a novice in all of this.
PHP scripts run before your javascript, which means that you can pass your php variables into javascript, but not the other way around. However, you can make an AJAX POST request from JavaScript to your PHP script, and grab the POST data in PHP through the global $_POST variable.
Assuming you use jQuery, your JavaScript would look something like:
// assign data object:
var data = { value: "test" };
// send it to your PHP script via AJAX POST request:
$.ajax({
type: "POST",
url: "http://your-site-url/script.php",
data: data
});
and your PHP script would look like:
// if the value was received, assign it:
if(isset($_POST['value']))
$value = $_POST['value'];
else
// do something else;

Categories

Resources