Json_encoding a Php Variable in an Ajax Request - javascript

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."'";

Related

value not defined when access php with get method from javascript

I want to send value with get method to my php file.
if i set my url like this
http://example.com?id=13
it can run normally, but when my id is like this
http://example.com?id=a0013
a get error in my console log a0013 is not defined. This is my code
<?php
//set $id value
$id=a001;
?>
<script type='text/javascript'>
function init(){
ja = new google.maps.Data();
ja.loadGeoJson('example.php?id='+<?php echo $id; ?>+'');
}
</script>
my example.php
<?php
$id=$_GET['id'];
//another action
?>
You seem to be confusing PHP and JavaScript;
PHP is a server side scripting language
JavaScript is a client side scripting language
The console you mention, is through a browsers inspector tool, and runs off of JavaScript.
If you want to get a request param from this, you could do the following;
// Remove the "?" from the URL and split this down by the ampersand
var requestParams = window.location.search.replace("?", "").split("&");
for (var i in requestParams)
{
// For each of the request parts, split this by the = to het key and value
// the console log them to display
var _params = requestParams[i].split("=");
console.log("Request Param; " + _params[0] + " = " + _params[1])
}
This will output something such as;
Request Param; id = a0013
You can also use these in PHP;
foreach ($_REQUEST as $key => $value)
{
print "Request Param; {$key} = {$value}<br />";
}
Which will result in the same thing. If you wanted just the a0013 value; using;
print $_REQUEST['id'];
Will give you this.
Trying to target via the a0013 won't work as that is the value in the data, not the key
NB - I use $_REQUEST in this, there is also $_GET (what you see in the URL bar and what JavaScript has access to via window.location.search) and $_POST which is hidden from the user
FOLLOWING OP EDIT
Add quote marks around your $id=a001; to make it $id='a001';
The reason it works with 13 and not a0013 (or a001) is because 13 is an integer and does not need quotes, because the latter has a string (starts with "a") it MUST have quotes around it (single or double, doesn't matter)

PHP, Javascript, mysql, and selection lists

I'm working on a piece of some software that will grab information from a mysql database and throw it onto our form dynamically. I'm running into a couple problems, though. I'll give a quick rundown of some functionality.
When the form loads, we have a ton of selection lists. These are all populated through arrays with various keys/values in php. When I select an option from one list, we'll call it a "customers" list, on-click I need to check if that customer has a special flag (stored in the database), and update another selection list based on that data.
How I understand the core of my solution is I need to have a javascript trigger on-click, which I have. The function that is called references a php page that handles the database query through a class and it's function.
<script>
function setService()
{ // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.get('thePage.php?key=setService?customer='+customer);
}
</script>
This function then talks to my php. The CustomerProvider class works 100%. I have tested that thoroughly on other pages. The problem arises when I try to actually get my selection list to change.
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
if ($s != '')
{ ?> <script>var element = document.getElementById('ticket_service');
element.value = 'Contracted Hours';</script> <? }
else return;
}
?>
I'm coding in javascript literally for the first time ever and they kinda just threw me on this project. I know that my portion isn't being read as html or output as I intend. I know that every other part of the php and the first bit of javascript seems to be executing okay. Any help would be incredibly appreciated.
You seem to be on the right track but just for your own sanity here are a couple pointers. You shouldn't be returning Javascript from PHP for a situation like this. Instead you should be relying on Javascript promises to wait for a response containing just the data and continue the execution of your client code once you have your values returned. Take a look at this:
<script>
function setService() { // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.get('thePage.php?key=setService?customer=' + customer, function(data) {
console.log(data + ' was returned from your php script!');
if(data.hasContract=='1')
$('#ticket_service').val('Contracted Hours');
else
$('#ticket_service').val('No Contracted Hours');
});
}
</script>
And then your PHP script will just look like this:
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
if ($s != ''){
$hasContract = 1;
}
else
$hasContract = 0;
echo json_encode(array('hasContract' => $hasContract));
}
?>
Therefore returning only the data needed for the client app to continue... not application logic
Your code isn't doing anything with the output of the PHP script. If you want the output to be inserted somewhere in the DOM, you should use .load() rather than $.get.
$("#someelement").load('thePage.php?key=setService?customer='+customer);
This will put the output into <div id="someelement">. If the output contains <script>, the script will be executed.
If you know the result is just a script, you could use $.getScript() instead of $.get. Then the output should just be the Javascript, not enclosed in HTML tags like <script>.
The problem here is that you are not using the result from the server. Your JavaScript may indeed be correct, but the browser never sees or runs it. From the docs:
Request the test.php page, but ignore the return results.
$.get( "test.php" );
Try this code, which utilizes the $.getJSON() shortcut function. I've written two versions, which you can see commented in the code. One moves the logic for determining contract status into the JS. Either should work.
PHP
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
// Default output
$output = array('hasContract' => false);
// Customer has contract
if ($s != '')
$output['hasContract'] = true;
echo json_encode($output)
// Alternative: PHP just returns getHasContract, JS determines action
// (this would replace $ouput, conditional, and echo)
// echo json_encode(array("hasContract" => $s));
}
?>
JavaScript
function setService()
{ // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.getJSON('thePage.php?key=setService?customer='+customer, function(result) {
// Alternative
// if (result.hasContract != "")
if (result.hasContract)
{
var element = document.getElementById('ticket_service');
element.value = 'Contracted Hours';
}
});
}
As others wrote, your code doesn't do a thing with the GET variables.
the element "ticket_service" doesn't exists on page and even if it was, the code has no impact on the page that sent the request, you should print/echo the result you want to display/return and then manipulate it with JS/Jquery.
since I'm against GET and pro POST which is safer method, here's an example with POST:
JS:
function postSomthing(customerID){
$.post(
'thePage.php',
{key:'setService',customer:customerID},
function(data){
if(data!='x'){
$('#ticket_service').val(data)
}
else{alert('no ticket');/*whatever you want to do*/}
});
}
PHP(thePage.php) :
if(isset($_POST['key']) && $_POST['key'] == 'setService'){
$customer = intval($_POST['customer']);
$s = CustomerProvider::getHasContract($customer);
if ($s != ''){echo 'x';/* false, or whatever you want*/}
else{echo 'Contracted Hours';}
}
notes:
you should create an element with the id "ticket_service" in the viewed page and not in the backstage one.

Passing a Jquery array of objects into a php array

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

How to transfer a value on DB to JAVASCRIPT through PHP

<?php
// Connect to database server
mysql_connect("192.168.1.101/phpmyadmin/", "root", "praticas") or die (mysql_error ());
// Select database
mysql_select_db("logs_history") or die(mysql_error());
//---> at this point, I want yo pull a VALUE from a column called potencia_ativa and insert in
// the code JS below
mysql_query($strSQL);
// Close the database connection
mysql_close();
?>
//JS code-------------------------------------------------------------------------------------------
<div id="graphHolder" style="height:75%;width:100%"></div>
<script type="text/javascript">
setInterval(
function() {
var d1 = [];
for (var i = 0; i < parseInt(document.getElementById('number').value,10); i += 0.5) {
d1.push([ //----------> pull the value from the php/DB as a FLOAT
]);
}
$.plot("#graphHolder", [{
label: "Label",
data: d1,
lines: { show: true, fill: true }
}
]);
}, 1000);
</script>
Remember, PHP executes on the server and GENERATES the page that runs the Javascript on the client. Putting a value from PHP into the JS code is as simple as:
<script>
var foo = <?php echo json_encode('bar'); ?>;
</script>
If you need to send the PHP data over AFTER the page was generated and already send to the client, then you need to have the client execute an AJAX request to fetch that data from the server. Once PHP has shoved the page out the door, it's basically done and can't "reach out" to the client to do updates on its own.
Also: Note the use of json_encode(). You should NEVER dump output from PHP directly into a Javascript context without it. Anything else puts you at risk of generating JS syntax errors, which will kill the entire JS code block.
Why are you using Interval? Are you trying to update the displaying page data/value automatically after some time passed? That won't work, because if anything changes in database, It won't change in the displaying page, unless you use AJAX to call your php script and return some values, and then, change in the displaying page.
To get a value from PHP script to JAVASCRIPT, you just need to use the php clausule;
var test = <?php echo $variable; ?>
// echo for strings, ints, floats.
// print_r for arrays.
Of course, if your PHP script already injected the data into the page/the data is in the same page you're using JAVASCRIPT, assuming that you have already fetched the data, handled it and etc.

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