Passing a Jquery array of objects into a php array - javascript

I have an array in jQuery that I am trying to convert to a PHP array by using Post:
$.post("http://www.samepage.com", {final_slip: JSON.stringify(final_slip)});
When I pass this dynamically created array "final_slip" into it :
[final_bet_game { final_user_id="1", final_game_id="1", final_game_type="spread_2",final_price="10", final_odds="1.8"}, final_bet_game { final_user_id="2", final_game_id="3", final_game_type="spread_2",final_price="1", final_odds="2.8"}, final_bet_game { final_user_id="3", final_game_id="14", final_game_type="spread_32",final_price="140", final_odds="1.8"}, final_bet_game { final_user_id="4", final_game_id="1", final_game_type="spread_2",final_price="10", final_odds="2.8"}, ]
I get this php outputted :
$data = $_POST['final_slip'];
print_r ( $data);
[{\"final_user_id\":\"1\",\"final_game_id\":\"1\",\"final_game_type\":\"spread_2\",\"final_price\":\"211\",\"final_odds\":\"1.8\"},{\"final_user_id\":\"1\",\"final_game_id\":\"2\",\"final_game_type\":\"spread_2\",\"final_price\":\"212\",\"final_odds\":\"1.8\"},{\"final_user_id\":\"1\",\"final_game_id\":\"parlay\",\"final_game_type\":\"\",\"final_price\":\"021\",\"final_odds\":\"\"}]
I tried to use the json_decod, but Im not getting any results. How can I get this to a usable php array? Would I be better off using ajax?

$.post("http://www.samepage.com", {myJsonString: JSON.stringify(myJsonString)});
But when I then try to access it in PHP I am not seeing any results.
And that tells you that you have another problem - PHP is not reporting errors. You want to turn error_reporting on.
In this case the likely cause is that your data is arriving into the $_POST array, and $myJsonString is not defined (automatic definition of parameters has been deprecated since PHP 5.3.0, and no longer available since PHP 5.4.0).
You should either do
if (array_key_exists('myJsonString', $_POST)) {
$myJsonString = $_POST['myJsonString'];
} else {
die("myJsonString not in _POST");
}
or try straight
$result = json_decode($_POST['myJsonString'], true);

The problem was the backslashes in the outout needed to be stripped out:
$result = $_POST['json_string'];
$test = urldecode(str_replace("\\","",$result));
$test2 = (json_decode($test,true));
print_r($test2);

Related

Get Data from Mysql using (PHP) and send it to typescript/javascript using JSON

I have got data from mysql in php, and i want to send it to typescript using JSON. but when load the php page. nothing showed in the screen. It always shows a blank page.
$select ="SELECT * from `filiere`";
$run = mysqli_query($connect, $select);
$temp = array();
while($row=mysqli_fetch_row($run)) {
$temp[] = $row;
}
echo json_encode($temp);
from the code, it should show the data in json format.
what it is the problem?
I think i've understood where is my error.
You are all right. i have some data with frensh letters like ('é', 'ù'..). I think that was the problem.
Thank you all
In PHP, an unexpeted blank page usually means some kind of error + error reporting turned off.
Try to turn error reporting on
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(E_ALL);
EDIT #1:
Based on the comments, it seems that json_encode() fails, so returns false (echoing false will result in a blank page).
The json_last_error() and/or json_last_error_msg() functions should be used to find the error.
EDIT #2:
The first argument of json_encode() must hold only UTF-8 encoded strings.
did you set endpoint content-type on php ?
header('Content-Type: application/json');

Finding all PHP functions in a file

I want to find all functions in a file - thats no problem:
preg_match_all("/function[\s\n]+(\S+)[\s\n]*\(/", $data, $outputData);
The problem is that if there are Javascript functions, they will get in the scheme, too.
Is it even possible to get only PHP-functions.
One indicator would be the <script>-Tag, but I have no Idea how to only track functions, which are not surounded by the script-Tag!
Thank you!
I had THE idea 2 seconds after writing the question.
$data = file_get_contents($file);
$data = preg_replace("/<script[^>]*>[\s\S]*?<\/script>/", "", $data);
preg_match_all("/function[\s\n]+(\S+)[\s\n]*\(/", $data, $outputData);
Just delete all the <script>-Tags!
If you would need them later, you also could save them (instead of replacing them) and add them later!
Just if someone else will have the same problem!
One option would be to remove all <script>...</script> tags before processing, but this assumes that you will only have JavaScript in these tags directly in the file. If you have a function or a library that generates HTML for you, it is possible for you to output JavaScript code without explicitly having the <script>...</script> tags in your PHP document. The issue is that you are using pattern matching, which can lead to an array of false positives.
To remove these false positives all together, you could use the PHP ReflectionFunction class to determine which functions are defined in PHP and which are not. Once you have an array of possible function names, use the following:
$data = file_get_contents($file);
$outputData;
$validMatches=array();
preg_match_all("/function[\s\n]+(\S+)[\s\n]*\(/", $data, $outputData);
foreach($outputData[1] as $match) {
$isValid=true;
try {
$reflection = new \ReflectionFunction($match);
} catch (\ReflectionException $e) {
$isValid=false;
}
if($isValid == true) {
$validMatches[]=$match;
}
}
This is more verbose but it will guarantee that you will get a list of only PHP function names.

Json_encoding a Php Variable in an Ajax Request

Currently I am using a jQuery Ajax asynchronous function to request a PHP page multiple times until a large number of spreadsheet rows are processed. Right now I am using the following code to set the variables to be passed to the requested page, I am not sure if this is the proper way to do it or not. PHP:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$new_spreadsheet = nl2br($_POST['spreadsheet']);
$new_spreadsheet = explode('<br />', $new_spreadsheet);
array_shift($new_spreadsheet);
$new_spreadsheet = array_values($new_spreadsheet);
$new_spreadsheet = json_encode($new_spreadsheet);
echo var_dump($new_spreadsheet);
}
JavaScript/PHP:
var done = false,
offset = 0,
limit = 20,
rankings_abv_twenty = 0,
sum = 0,
num_count = 0,
websites = 1
<?php if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo ', spreadsheet = '.$new_spreadsheet;
}?>;
On the requested PHP page (which happens to be Object-Oriented PHP), I have the following code to slice off 20 rows to process on the given request. Please not the PHP is a full working class, I just did not include all the PHP for the sake of post length. Also note, I have another page which calls the class, which passes the spreadsheet variable to the constructor of the PHP by reference as $_POST['spreadsheet'], so I know I have the right value as the spreadsheet. PHP:
$this->offset = $offset;
$this->limit = $limit;
$this->spreadsheet = json_decode($spreadsheet);
Here is the PHP line which slices off the rows:
$this->rows = array_slice($this->spreadsheet, $this->offset, $this->limit);
For some reason my code is not working properly and is giving me the following errors relating to the above code:
PHP Warning: json_decode() expects parameter 1 to be string, array given
PHP Warning: array_slice() expects parameter 1 to be array, null given
I think it might have something to do with how my string is getting passed the requested PHP. Also, just as a further note, when I use var_dump() on my spreadsheet variable before it is passed to the requested PHP, I get it outputted as a string like so:
string(7560) "String content goes here"
On the first look, instead of echoing the json_encode, you used var_dump.
And when manually modifying the json encoded string make sure to use " around the vars.
And this:
websites = 1
<?php if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo ', spreadsheet = '.$new_spreadsheet;
}?>;
Will result in:
websites = 1, spreadsheet = "{"1":"foo","2":"bar","3":"baz","4":"blong"}";
Wrap the line in ' if that's what you expect it..
like this:
echo ", spreadsheet = '".$new_spreadsheet."'";

How to receive data in php sent from javascript [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
I am sending some data from my pain page to app.php using javascript
$(document).on('click', '.app' , function(){
var data=$(this).attr("id");
window.location="application/app.php?data="+data; //data send in this statement
});
my php code is this :
<?php
if($_GET['data'])
{
echo $app_id=$_GET["data"]; receiving data
}
?>
It works sometime but now it is giving Notice in an alert box: Undefined index data in app.php. But it is showing the echo.
I want to know how I can receive the data I need using $_POST or $_GET. like we receive by making an Ajax call. But I haven't specified something like this in Javascript. is there any way to this?
I want to clarify that the data exists and it is non empty because echo is successfully printing that on the page
Try this:
<?php
if(!empty($_GET['data']))
{
$app_id = $_GET['data']; // receiving data
}
?>
Please be aware that passing data without validation is not secure. Reccomended reading: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
use isset() to first check if the key exists. data won't exist in $_GET when it's not passed via a parameter in the url
you probably want some logic that looks like this:
if (isset($_GET['data'])) {
if (!empty($_GET['data'])) {
$appId = $_GET['data'];
}
else {
// data exists, but it's empty
}
}
else {
// data does not exist
}
and maybe you even want to check if it's a valid id, like being numeric or something

What is the most efficient and correct way of handling PHP array variables within JavaScript and being able it obtain those values using indexing

THE QUESTION
What is the most efficient and correct way of handling PHP array variables within JavaScript and being able it obtain those values using indexing.
I have a MYSQL database and have a PHP script that creates an indexed row array of the database information.
Now that this information is within the array i am comfortable about echoing this data on screen from within PHP.
i.e.
echo $lastplayed[1]['artist'];
My next step is to take the array into JavaScript so that i can use the variable information to display data on screen, make calculations and create an Ajax timer that looks for a value from a variable and refreshes the page..
Its basically a internet radio station that will display what is and has been played and when a counter reaches zero will refresh the page. (the counter being time left of a song)
I could echo each variable into a separate PHP script and then use JavaScript to call each of those PHP scripts that contain the different variables (This seems long-winded) AND puts unnecessary request strain on the MYSQL server
**I really feel that there must be a better way of transferring and handling the data, surely there must be some type of bridge between PHP and JavaScript, should i be looking into JSON ?
So my end result is to be able to take an indexed array from PHP, transfer this array into JavaScript and be able to call on different variables from within the array using indexing (i.e call the variable that resides in result 3 column 3)
And while this is happening i will be using separate PHP and JavaScript files...
Here is my code for the PHP part.
<?php
date_default_timezone_set('Europe/London');
require_once("DbConnect.php");
$sql = "SELECT `artist`, `title`, `label`, `albumyear`, `date_played`, `duration`,
`picture` FROM historylist ORDER BY `date_played` DESC LIMIT 5 ";
$result = $db->query($sql);
$lastplayed = array();
$i = 1;
while ($row=$result->fetch_object()) {
$lastplayed[$i]['artist'] = $row->artist;
$lastplayed[$i]['title'] = $row->title;
$lastplayed[$i]['label'] = $row->label;
$lastplayed[$i]['albumyear'] = $row->albumyear;
$lastplayed[$i]['date_played'] = $row->date_played;
$lastplayed[$i]['duration'] = $row->duration;
$lastplayed[$i]['picture'] = $row->picture;
$i++;
}
$starttime = strtotime($lastplayed[1]['date_played']);
$curtime = time();
$timeleft = $starttime+round($lastplayed[1]['duration']/1000)-$curtime;
$secsremain = (round($lastplayed[1]['duration'] / 1000)-($curtime-$starttime))
?>
Any thoughts on this would be greatly appreciated and thanks so much for your time.
Justin.
PROGRESS:
Thanks for the comments, i really need to take a JavaScript course at this point...
Now i have created a new output.PHP file that does the following
<?php
require_once("dblastplayedarray.php");
echo json_encode($lastplayed);
?>
So this file now echo's out the data i need in a JSON format from my array $lastplayed.
#VCNinc you say that i now can use the following code to take the data into JavaScript
<script>
var array = <?=json_encode($lastplayed)?>;
</script>
Please could you detail where i put the path information in this code so that the program knows where to look for the .PHP file output.php
Am i doing this right.. should i be printing the data into another .PHP file and then use your code to take the array into JavaScript..
Thanks
Justin.
JSON is the bridge!
You can "export" the variable to a json string and print on the output:
echo json_encode($lastplayed);
TIP: if the php file is used to show a html GUI AND you still want output a JSON too, you can create a GET variable like "&json=1" and, before output your HTML GUI, you do a IF. This way tou can use the same php file to output a GUI and the JSON. WHen you do the request via ajax, you call using the "&json=1".
if(isset($_GET['json']) && $_GET['json']==1){
echo json_encode($lastplayed);
exit;
}
Then, use AJAX to download this JSON string by calling your php script.
$.getJSON(url, function (json) {
//here the 'json' variable will be the array
//so you can interact on it if you want
$.each( json, function( key, value ) {
alert( key + ": " + value ); //here you can do anything you want
});
});
If you have a PHP array $array, you can easily export it into JavaScript like this:
<script>
var array = <?=json_encode($array)?>;
</script>
(and from that point you can manipulate it as JSON...)

Categories

Resources