Passing data from Javascript to php with Laravel 5.1 - javascript

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

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 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

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.

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.

Store Javascript object in $_SESSION by Ajax. Array vs JSON string

I'm sending an Ajax request which sends an object objectVariable to a PHP file:
$.post(url, {action : 'function' , object : objectVariable });
Then, the PHP file will store objectVariable in $_SESSION['objectVariable'] (I'm omitting validation to make it clear):
function function_callback() {
if(!session_id())
session_start();
$_SESSION['objectVariable'] = $_POST['objectVariable'];
}
When the user goes to other page of the site, the $_SESSION['objectVariable'] will be sent from PHP to the user by Ajax again.
Here, I should encode the array stored in $_SESSION['objectVariable'] to a JSON string:
//inside other Axax callback function
echo json_encode($_SESSION['objectVariable']);
That's working right, but I also could store a JSON string into $_SESSION['objectVariable']:
function function_callback() {
if(!session_id())
session_start();
$_SESSION['objectVariable'] = json_encode($_POST['objectVariable']);
}
And after, just echo $_SESSION['objectVariable'] to send it to the Javascript file.
I wonder what would be a better way: store an array in $_SESSION['objectVariable'], or store a JSON string.
Any suggestion about it?
When sending data between Javascript/PHP I always keep it encoded as a JSON string. It makes things simpler. In fact, I would just JSON.stringify() it right away when you send it to the server the 1st time.
This way you also will always know what type the data will be.

Categories

Resources