Access array posted with Javascript - javascript

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

Related

Is there a way to get create a php varialble from ajax data returned from another php script

I have a php script that creates a webpage with my select box options
Eg index.php has a html select box:
<select id="sel_option">
<option value="0">- Select Option -</option> ....
this is posted on sel_option change using ajax to a php processing script as below:
<script type="text/javascript">
$(document).ready(function(){
$("#sel_option").change(function(){
var optionid = $(this).val();
$.ajax({
url: 'procscript.php',
type: 'post',
data: {option:optionid},
dataType: 'json',
success:function(response){ ...
I would like to pull some of the returned array into Php variables again in order to change some of the tabulator group or format options
eg $("#table1").tabulator({
height:500 ,
VirtualDomHoz:true,
<? echo "groupBy:[\"group_option_from_response array\"]," ?>
So Php script1 sends option data by ajax -> php script2 which gathers data from a mysql db and returns to script1
I have tried creating session variables in php script 2 and it works on first selection , but after that it seems to cache the initial sessions in the browser , the response sessions from the second php script do not seem to copy over to the first script in subsequent calls. I think it might because the first page never reloads , all selections are done within the loaded first page using js??
If what I am trying to do is if not possible by php can I rewrite the php section in tabulator below using some js code?
$("#table1").tabulator({
height:500 ,
VirtualDomHoz:true,
<? echo "groupBy:[\"group_option_from_response array\"]," ?>
placeholder:"No Data Set",
columns:[
{title:"ID", field:"ID",width:30},
{title:"F_name", field:"f_name", sorter:"string"},
<? echo "{title:\"different var\", field:\"field2\", sorter:"string"},"; ?>
Thanks for looking !
Steve
Receive your data through ajax, then create the tabulator object. If there is data coming through ajax for that object, you can add it in, then instantiate it.
success:function(response){ ...
response = JSON.parse(response);
createTabulator(response,"table1")
});
function createTabulator(data, idToUse) {
var tabobject = {
height:500 ,
VirtualDomHoz:true,
placeholder:"No Data Set"
}
if (data.groupBy) {
tabobject.groupBy = [data.groupBy]
}
var cols = [
{title:"ID", field:"ID",width:30},
{title:"F_name", field:"f_name", sorter:"string"}
]
// if there is columns data coming in, bring it as an array...
data.columns.forEach(item => {
cols.push({title: item.title, field: item.field, sorter:"string"})
})
tabobject.columns = cols;
$("#"+idToUse).tabulator(tabobject);
}
There are so many ways to achieve what you want. I think the best way is just to push the variable to the ajax request.
$.ajax({
...
data: {
option:optionid,
groupoption: "groupoptionvalue"
}
...
});
The first time you just have to send it empty. PHP will always be able to handle the value since you will always capture it at the very beginning.
If your variable is an object or an array, just use JSON.parse/JSON.stringify in javascript and json_encode/json_decode in PHP for them to communicate.

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

JavaScript array to PHP via AJAX

I have written a simple JS script, that saves mouse positions in an array, which I then send to a php function via AJAX. It works, and saves the recieved data, but the problem is how it is saved, i.e. i would expect to have a normal output of the x and y position as is: [x1,y1],[x2,y2],[x3,y3],...
But what i get is something like this:
a:63:{i:0;a:2:{i:0;i:527;i:1;i:1010;}i:1;a:2:{i:0;i:490;i:1;i:1205;}i:2;a:2:{i:0;i:588;i:1;i:1311;}i:3;a:2:{i:0;i:615;i:1;i:1368;}i:4;a:2:{i:0;i:553;i:1;i:1474;}i:5;...
I thought if i encode it in JSON format that it would save as i thought, but i dont understand why the output is as it is. Any ideas?
The JS code is as follows:
window.onbeforeunload = function() {
var jsonString = JSON.stringify(tabela);
$.ajax({
type: 'POST',
url: 'process.php',
data: {
text1: jsonString
}
});
}
And the PHP side is this:
$text1 = json_decode(stripslashes($_POST['text1']));
$string_data = serialize($text1);
file_put_contents("your-file.txt", $string_data);
The content looks like this in the file, because you passed the array through serialize function. In order to "decode" file content, use unserialize.
If you want to have more human-readable file content, just store the JSON string in the file ($_POST['text1'] directly) or instead of serialize use json_encode again before calling file_put_contents.

Return JSON object from php script

I am making an AJAX GET request using jQuery to a PHP file. I want the PHP script to return a JSON object, however, currently it is returning a JSON string. I realise I can use JSON.parse in the jQuery code, however, any experience I have in making an AJAX call to an API a JSON object is returned. I am trying to do the same with the php script however, it is returning a string as opposed to an object.
Does anyone know what the best practice is here, and if the best practise is to return a JSON object how I would do this using PHP?
Please see the code below:
js
$.get('test.php', function(data){
console.log((data));
});
php
<?php
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
In your PHP file, change the content type to application/json.
JS
$.get('/process.php', function(data) {
console.log(data);
} );
PHP
<?php
header( "Content-type: application/json" );
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
Then your console should read Object {test: "true"} rather than just the JSON string.
Add json to the end of your get function to return json
$.get('test.php', function(data){
console.log((data));
},'json');//here
and/or add this header in php
header('Content-Type: application/json');
more info here
Without modifying PHP script you can do:
$.get( "test.php", function( data ) {
var arr = $.parseJSON(data);
console.log(arr);
alert(arr.test);
});

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