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.
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)); ?>");
I'm using the following code to send a form to a php processor:
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
},'json');
return false;
});
});
I presume that this sends the form to my php script with all the form values in json format but I then don't know how to then access this json and turn it back into the array i need to process in my PHP script.
Does anyone know how I access this variable in my processor script so I can process the data?
Also, what is the best way for me to view the data being posted so I can work out what to do with it, when I send the data the processor is obviously not displayed, is there a way to echo out/write the information received by the script to I can view it?
You can easily access to the json as an array called "$_POST" in your php.
for example, if you send the form as a json structured like this:
{
"name":"userID",
"psw":"password123"
}
in your php script there will be the variable $_POST with this structure:
$_POST = Array (
"name" => "userID",
"psw" => "password123"
)
EDIT
In a comment you asked me how to display the data received from the server,
that's quite simple,
in your php script just write this:
echo json_encode($_POST);
so that you output the $_POST array in the json format,
then in your script write this:
$.post($(this).attr('action'), $(this).serialize(),
function(data){ //"data" argument will contain the output from the server (that is the encoded $_POST array printed as json with the php code as showed above)
console.log(data); //log data
}
); //as you can see, I've deleted "json", becouse it's unuseful
I was trying to make a Json Object of some variables Which I am using as Session variables, But I am not geting the proper Response To make it as Json Object ..
Some Code which I tried (for Reference) Sharing Below..
//Passing the Variable To another PHP File
session_start();
$_SESSION['EmailIds']=$strEmailIds;
$_SESSION['SCHOOL_NAME']=$SCHOOL_NAME;
//sending data to another php page ..
header('Location: ../SecondPage.php');
In second file SecondPage.php Where i was Using This Session..
session_start();
$SCHOOL_NAME = $_SESSION['SCHOOL_NAME'];//1
$EmailIds= $_SESSION['EmailIds'];//1 <br>
Now trying to make this Session Variable in Json OBject...????
var OBJ = jsonObj.(SCHOOL_NAME+EmailIds);// Confuse with THis Line<br>
Actuaaly Not Getting What is the Good Approach To make this variables as Json Objects..
AS I Made this Json Object I can Use This AS another Purpose Like to send as Ajax Data and etc..
You can use json_encode method like this :
$someArray; //can be array of your values or $_SESSION
$jsonObj = json_encode($someArray);
get session data in an array like :
$data['SCHOOL_NAME'] = $_SESSION['SCHOOL_NAME'];
$data['EmailIds']= $_SESSION['EmailIds'];
then encode it like
$json_obj = json_encode($data);
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
I'm learning PHP OOP, and getting used to all of these objects.
When I create an object in a PHP file called via an $.ajax function, I want to deliver the answer back. But how am I supposed to send back the object to my ajax call ? Before OOP, I was putting everything into an array, then json_encode() the array, and everything worked perfectly. How to adapt this using OOP?
Thanks a lot for your answers
Romain
Example:
On the client side
$.ajax(
{
url:"test.php",
type:"POST",
dataType:"json",
success:function(json)
{
// json into template
}
});
On the server side: test.php
require_once("bdd.php");
function loadClass($class)
{
require $class.".class.php";
}
spl_autoload_register('loadClass');
$PersonneM = new PersonneManager($db);
$perso = $PersonneM->get("123456");
$perso = serialize($perso); // ????????????
header('Content-type: application/json');
echo json_encode(array("result",$perso));
either use serialize or __toString to create a JSON-representation of your data that you can send down the tube. You will not be needing an extra array around your object.
However, there is an error in some JSON parsers/interpreters that can mess with your data when not wrapped in an array. But I haven't heared anything of this issue since a couple of years so you should be safe