How to pass resource from php to javascript - 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

Related

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 take javascript variable in php mysql query?

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.

Passing data from Javascript to php with Laravel 5.1

I need to pass data from Javascript to php using Laravel 5.1
So right now I have a blank page with input(name='q'). When I start typing it sends the query via Ajax data:{q: query} to php so in php I am taking the value from q $query = e(Input::get('q', '')); (Laravel syntaxis) and I am processing the data and I have a respond from the php
return response()->json(array(
'data' => $data
));
So after Ajax is succeeded. The ajax is taking the respond :
function(item, escape) {
console.log(item); }
And the output data is object:
Object {url: "http://localhost:8000/well/3", name: "Welly", iso3_code: "NOR", class: "product"}
So by clicking a button I want to send this data via POST to some method.
After this all I need to take the "item" from js and save it to php variable so via POST I can send this data to differened procces. So after the POST I will have the data for the other process.
I would have access to the object via the respond from the php 'data' => $data
or from the js "item" .... But whatever I try I can not manage to do it.
Thank for helping me.
EDIT
So at all I have JS object that I need to send as a POST request to the server so after that with php I will do stuffs with the object taken from the JS. Is that clear enough.
You can probably do return response via json_encode from php to javascript then in the javascript you can do {{$phpVariable}} = var javascriptVariable

making a loop with jquery, Ajax and PHP

i want to make a loop in jquery, Ajax and PHP.
my pages are:
shop.php
do_ajax.php
in the shop.php are variable $p_productid is 1 and $j_productid is $p_productid
var j_productid = <?= $p_productid ?>;
now i do j_productid++ so the output from $j_productid is 2
now i'm posting this with ajax to do_ajax.php
in the do_ajax.php are variable $pa_productid is $_POST['$j_productid'];
now i can place this on html, but i want to set this value in too the variable on $p_productid on shop.php
how i need to do this?
there is working a swipe system in this case so only with php it isnt working i need to work with jquery that's why am i doing this on this way. i got an another solution without AJAX but i want that you cant see on the client side the webpage is refreshing.
JQUERY
wipeLeft: function() {
var j_ProductId = <?= $g_ProductId ?>;
var j_Swiped = 1;
if (j_ProductId < <?= $l_LastProduct ?>){
j_ProductId++
//document.swiping.productid.value = j_ProductId;
//document.swiping.submit();
$.ajax({
url: 'do_ajax.php',
type: 'POST',
data: { swipe : j_Swiped,
productid : j_ProductId},
success: function (data) {
$('.product').html(data);
}
});
}
}
do_ajax.php
if(!empty($_POST['swipe'])){
$l_ProductId = $_POST['productid'];
echo $l_ProductId;
}
You need to understand that the JavaScript (even if generated dynamically by PHP) is not running the same time that PHP is running. Your workflow will be something like this:
PHP script (shop.php) is invoked
PHP script generates output, HTML and JS mixed.
These are all in server side until the web server sends the output to client (browser)
In browser HTML displays and JS runs with starting values that you generated previously by PHP. But in this time, PHP has been finished, not running anymore. PHP variables are not alive anymore.
JS interacts with the user in browser, we can say it's running continuously.
Triggered by an action (swipe) JS sends an (ajax) request from client side to server side. This request transfers the new value to server side, and invokes another PHP script (do_ajax.php). You do whatever you want with the new value (process it and or store it) in server side. You need to understand that you are in a completely disjunct scope in PHP than in your first PHP script. (distinct in time too)
If you want to be sure that, in case of a page reload, the (product ID) value will be the updated value, you need to store it somewhere (user session, key-value store, database, or any persistent) when you get it in server side (so in do_ajax.php) and later load this value in the beginning of your shop.php script ...which will pass it to the JS, and so on. The workflow starts again.

Capture onClick event in serverside php file using Ajax

I am very new to Ajax. My application uses ajax (and a server side php page called Req.php) to fetch records from a database, create table using those fetched records and display it. Now I want a column to be added having Delete option to it. May be something like this:
echo '<td>Delete</td>';
This deleteIt() method lies inside Req.php (server side) file like this:
<script type = "text/javascript">
function deleteIt(rowID)
{
//Some Code
}
</script>
Now considering the fact that it is a server side file, and delete event happens at client side, what should be the procedure to capture this delete event so that it takes $rowID from the table made by server side php file and deletes the correponding record.
Any help would be highly appreciated. And please let me know if there's insufficient information so that I can give more details.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
jQuery.ajax({
url:'YOUR PHP url which contains DELETE code',
type:'POST',
data:'SEND YOUR DATA',
success:function(results){
jQuery("#oresponsecontainer").html(results);
}
});
In your PHP
$id = $_POST["id"];
An Ajax request would be then be sent from your javascript with the id and action (deleting) of the column your accepping php file would then search for the row and delete it.
please specify what has been done in php for deleting.
You should create another php script that handles POST request (or GET, i've used post ajax)
so function should execute something like this
$.post("/trackDeletion.php",{rowID:rowID},function(successResponse){
//client handler
})
and PHP will be
rowID = $POST['rowID']
//do you code on backend

Categories

Resources