Update my php array in javascript function - javascript

I want to update or add new key=>value to my php array in javascript function.
The paging is in ajax, page is not reloaded again.
Actually I am receiving the data in a text file which is uploaded on my server. I parse that file and get a limited number of records, when I click on NEXT then one more file is uploaded on server and I parse it once again and show the data. So, I want that all data to be stored in php array on that page so when next time I go to PREVIOUS record, it doesn't parse the file once again, just show the data from the array.
//php array name is $call_data
var file_data = <?php $content = #file_get_contents("text file name");
$content = rawurldecode($content);
$new_call_data = json_decode( $content );
foreach ($new_call_data->CALLS as $key => $val) {
$call_data['CALLS'][] = $val; $file_rec_start++;
}
echo json_encode( $call_data ); ?>;

i don't see the part, where you split your "content" part into peaces so you have to reload the page, is it missing or is this part in JavaScript?
also you could minify you source:
<?php
$my_contents = file_get_contents('myfile.json');
$my_contents = rawurldecode($my_contents);
$my_array = json_decode($content);
$my_json = json_encode(array_values($my_array->CALLS));
?>
var file_data = <?=$my_json?>;
than you can itterate trough the array in javascript without the need of refreshing the page.
you could use
var results_per_page = 25
var page_available = Math.ceil(file_data.length / results_per_page);
var page = 0;
var page_array = file_data.slice((page * results_per_page), ((page+1)*results_per_page));

Related

AJAX call unable to fetch data from PHP, shows undefined data

I am new to web development and this is my first question here so please don't mind my vagueness, if any.
Now, I am facing facing problem with my javascript file which is supposed to draw a line chart.
Through an ajax call I am unable to fetch data from a php file which gets some variable from a html form. The problem is that I am not getting anything when I load my test.html (which includes the necessary file) not even in console.
Relevant part of my js file is here (graph.js):
$(document).ready(function(){
$.ajax({
url : "http://localhost/series/data.php",
type : "GET",
dataType: "json",
success : function(data){
console.log(data);
var time = [];
var sensor1 = [];
var sensor2 = [];
var sensor3 = [];
for(var i in data) {
time.push("time " + data[i].time);
sensor1.push(data[i].sensor1);
sensor2.push(data[i].sensor2);
sensor3.push(data[i].sensor3);
}...
And this is my PHP file(data.php):
<?php
header('Content-Type: application/json');
//connects to database
include '2connect.php';
//gets a date of which sensor data is to be displayed
if(isset($_GET['dateselector'])&&!empty($_GET['dateselector'])){
$date=$_GET['dateselector'];
//echo "$date";
$query1= "SELECT `time`,`sensor1`,`sensor2`,`sensor3` FROM `$date`";
if($result = mysqli_query($con,$query1)){
$data=array();
while ($row = mysqli_fetch_assoc($result)) {
$data[]=$row;
}
$result->close();
$con->close();
print json_encode($data);
}else {
echo"<br> failed <br>";
}
}else {
echo "You didn't select a date \n";
}
?>
Whenever I remove the isset check from my php code and give $date a value the code runs perfectly. Is it so that ajax doesn't fetches data from a php file which gets data (form data) from another file?
EDIT: The process is: User chooses a date from the calender (index.html) that date is sent to a php file (data.php) which displays the result in json format. Then in another browser I open a html file(test.html) which includes graph.js and graph.js should fetch data from data.php.

file_get_contents Not Work If Value is Gained from Javascript

I want to read other sites on my web with file_get_contents(). My value can be with javascript merging.
My site page is : http://example.com/page.html#2010/09/awesome.html
JAVASCRIPT
var hash = window.location.hash.substr(1);
// results: 2010/09/awesome.html
PHP
$hash = "<script>document.write(hash);</script>";
$resultLink = "http://www.external-site.com/" .$hash;
$content = file_get_contents($resultLink);
$first_step = explode("<div class='post-entry'>" , $content );
$second_step = explode("</div>" , $first_step[1] );
echo $second_step[0];
Here $resultLink is : http://www.external-site.com/2010/09/awesome.html
But file_get_contents($resultLink) can not open the page.
How can I fix this code?
The problem here is JS is executed client side, which is AFTER the PHP is executed and produces content to send to the browser.
For example, by doing what you're doing $resultLink contains http://www.external-site.com/<script>document.write(hash);</script>

Access Wordpress PHP Variables within Plugin JS

edit: I'm now wondering how I can access post ID from within plugin (outside of loop). If I try to get the post id, it returns 0.
How does one access a specific page's PHP variables within a plugin JS file?
I originally had the JS in the page template file but have moved it to a plugin. Now I am unsure how to access that page's PHP variables. Maybe move the PHP logic to a plugin function?
content-course.php (JS)
<?php
$user_id = get_current_user_id();
$course_id = $post->ID;
$vimeo_progress = 0;
$vimeo_seconds = 0;
if ( is_user_logged_in() ) {
// Run WP query to retrieve user progress
$row = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $table_name WHERE user_id = %d AND course_id = %d;", $user_id, $course_id) );
if ($row) {
$vimeo_seconds = $row->seconds_played;
$vimeo_progress = $row->progress_percent;
}
}
?>
<script>
jQuery(document).ready(function($) {
var progress = <?php echo $vimeo_progress; ?>;
var seconds = <?php echo $vimeo_seconds; ?>;
var userProgress = <?php echo $vimeo_seconds; ?>; //example user data retrieved
var lastUpdateProgress = <?php echo $vimeo_progress; ?>;
var videoUrl;
var courseID = <?php echo $course_id; ?>;
</script>
How would the JS script be able to access the PHP variables if moved to the plugin? Do I need to move the PHP above the script to a plugin function.. because then I am not sure how it would pass the data to the JS.
Wordpress have a classified function for the job
wp_localize_script()
Take a look. It's very easy to do.
http://codex.wordpress.org/Function_Reference/wp_localize_script

Struggling to create a php array to fetch photos from directory that can be used as an array in JavaScript

Basically I am trying to create a photo slideshow that will display specific photos depending on the userid. These photos will be stored in the directory of my web server space. Currently I have a html (not changed into php) file with basic html layout, css style sheet and an external js file that has my code that makes the photos fade in and out. I have added php at the bottom of my html. This is what I have:
$user_id = $_GET['userid'];
print "<h1> Hi, $user_id </h1>";
function returnimages($dirname = "Photos/1") { //will replace 1 with userid once something starts working
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
and in my javscript, the code I had before for the array of photos:
// List of images for user one
var userphoto = new Array();
userphoto[0] = "Photos/1/1.jpg";
userphoto[1] = "Photos/1/2.jpg";
userphoto[2] = "Photos/1/1.jpg";
userphoto[3] = "Photos/1/1.jpg";
userphoto[4] = "Photos/1/1.jpg";
which I have now commented out and replaced it with this:
var userphoto = <? echo json_encode($galleryarray); ?>;
I am hoping to be able to change the src of photodisplay with the new array:
photodisplay[x].attr("src", userphoto[x]);
Sorry if my problem is not clear at all. I am very confused myself. :( hopefully someone can help!
$user_id = (int) $_GET['userid'];
print "<h1> Hi, $user_id </h1>";
function returnimages($dirname = "Photos/1") {
$dirname = str_replace('..', '.', $dirname); //only remove this if you know why it's here
$pattern = "*{.jpg,.png,.jpeg,.gif}"; //valid image extensions
return glob($dirname . DIRECTORY_SEPARATOR . $pattern, GLOB_BRACE);
}
echo "var galleryarray = ".json_encode(returnimages()).";\n";
?>
Also, you should use <?= json_encode($ret) ?> because the PHP short tag (<?) is deprecated, but <?= is not, and is the equivalent of <?php echo.

php array to external page using jquery

I have a php page to creates a multi-dimentional array called $results.
I would like to:
catch submit of a form button
override default behavior of the submit using jQuery
copy and process $results on separate php using $.post
I have this which is not currently working and am not sure why?:
<form id='download_to_excel' method="post">
<input type="image" name="submit" value="submit" id='xls_download_button' src='images/common/buttons/download.png'>
</form>
<?php
$json_results = json_encode($results);
?>
<script type='text/javascript'>
$(document).ready(function(){
alert($json_results);
$("#xls_download_button").click(function(e){
alert('clicked');
e.preventDefault();
download_xls();
});
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results};
}
});
</script>
When selecting the xls_download_button, the alert() never fires nor does any data get passed to export_data_to_excel.php
The export_data_to_excel.php file has the following:
<?php
$results = json_decode($_POST['json_data']);
#include the export-xls.class.php file
require_once('export-xls.class.php');
$date = date('Y-m-d');
$filename = "contacts_search_$date.xls"; // The file name you want any resulting file to be called.
#create an instance of the class
$xls = new ExportXLS($filename, $results);
#lets set some headers for top of the spreadsheet
$header = "Searched Contact Results"; // single first col text
$xls->addHeader($header);
#add blank line
$header = null;
$xls->addHeader($header);
$header = null;
$row = null;
foreach($results as $outer){
// header row
foreach($outer as $key => $value){
$header[] = $key;
}
// Data Rows
foreach($outer as $key => $value){
$row[] = $value;
}
$xls->addRow($header);//add header to xls body
$header = null;
$xls->addRow($row); //add data to xls body
$row = null;
}
# You can return the xls as a variable to use with;
# $sheet = $xls->returnSheet();
#
# OR
#
# You can send the sheet directly to the browser as a file
#
$xls->sendFile();
?>
I do know that the $json_results does display proper JSON encoded values when echoed. But from there are not sure why the rest of the javascript does not run; the alerts never fire nor does the JSON data get passed?
Can you see why this isn't working?
Your PHP-supplied json is not stored as a javascript variable in your js.
$(document).ready(function(){
var json_results = <?php echo $json_results; ?>;
...
This code shouldn't run:
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results};
}
It is invalid (the ; doesn't belong there). Try this code:
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results});
}
Right now you are just setting a php variable called $results you need to transfear it to you javascript.
<script type="text/javascript">
// set javascript variable from php
var $results = "<?php echo json_decode($json_data); ?>";
</script>
For sure you have an error in your javascript code (you were not closing the parenthesis after $.post), should be:
$(document).ready(function() {
alert($json_results);
$("#xls_download_button").click(function(e) {
alert('clicked');
e.preventDefault();
download_xls();
});
function download_xls() {
$.post('./libs/common/export_data_to_excel.php', {
json_data: json_results
});
}
});
Then you should assign your JSON to a javascript variable inside document.ready
$(document).ready(function() {
var json_results = <?php echo($json_results);?>;
You can't pass a PHP variable to the JavaScript like that: there live in totally different worlds. Use Ajax to get the JSON data from JS.

Categories

Resources