Looking for your advice!
Im looking at a new method to update multiple with data.
Currently, I have say 3 divs.
I then have three scripts that get called every x seconds. Each script calls an external php file and in turn then updates the div that the script is designed for.
Im wondering,
Is it possible to have a single .php server file that can get called once.
But update multiple divs with the html data?
Maybe have the .php file output something like
div1html='HTMLCODE';
div2html='HTMLCODE';
div3html='HTMLCODE';
( Above clearly wont work because the html may contain ' or ; or whatever anyway.. )
And then have a single script that is called once to update all 3 divs with the data from a single call? ( Rather than 3 scripts calling 3 different files for each div )
I'm just looking for your advice on the best ( and easiest ) way to achieve this?
Thanks guys. Hopefully you will come up with something for me.
-Graham
Send the data json encoded. see json_encode
$data = new stdClass();
$data->div1html = 'bla';
$data->div2html = 'more bla';
$data->div3html = 'even more bla';
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data);
Json can easely read by javascript and will handle all escaping for you.
Related
I've been trying this for hours and finally give up.
As you can tell I've a huge noob and have little to no idea what I'm doing...
I have some JS being called from a button onclick= which POSTs to a PHP file. I'd like to take this POST data and just write it to a file, nothing fancy, just dumping it raw.
I've tried various methods, but none seem to work - either not writing the data at all, or writing "()", "[]" (if trying to encode the POST data as JSON), or just the word "array" and so on.
Methods I've tried;
file_put_contents('test.txt', file_get_contents('php://input')); //this I thought *should* definitely work...
var_dump / var_export / print_r
I've tried storing the above as $data and writing that as well. Just nothing I do seems to work at all.
I'm mostly trying to use fopen/write/close to do the deed (because that's all I really "know"). File is writable.
(part of the) JS I'm using to POST:
(from button onclick="send('breakfast'))
function send(food){
if(food == 'breakfast'){
$.post("recorder.php?Aeggs=" + $("textarea[name=eggs]").val());
I'm not looking to extract(?) values from the POST data, just write it "as-is" to a file, and I'm not bothered on the formatting etc.
Would someone please assist in putting me out of my misery?
You could use fopen() and fwrite() to write text to a new file. print_r() could be used to get the structure of the data or you could write the post var itself to the file. But since your client side code is not sending any POST data, use $_GET on the php side instead of $_POST. Here's an example:
$f = fopen("post_log.txt", 'w'); // use 'w' to create the file if not exists or truncate anew if it does exist. See php.net for fopen() on other flags.
fwrite($f, print_r($_GET, true)); // the true on print_r() tells it to return a string
// to write just the Aeggs value to the file, use this code instead of the above fwrite:
fwrite($f, $_GET["Aeggs"]);
fclose($f);
NOTE: The 2nd param to $.post() would contain the "post" data. Since you dont have that in your code, the $_POST on the PHP side will be an empty array.
Looking at this document; I am trying to make a file upload using XMLHttpRequest.
Here is how I start: I take the code in the A little vanilla framework section of the document. Then I first make it work on my own site. Then to implement the upload functionality I want to modify the end of the register.php file. Indeed a file transfer to the server is already happening there. To call it an upload I only have to save the file on the server.
I do that after these lines:
echo "\n\n:: Files received ::\n\n";
print_r($_FILES);
There, I want to write the contents of $_FILES[0] on the server. For that I use this code:
$myfile = fopen("MyData.jpg", "w");
fwrite($myfile, $_FILES[0]);
// The three lines below that I have tried instead of the one above do not work either.
//fwrite($myfile, json_encode($_FILES['photos']);
//fwrite($myfile, json_encode($_FILES[photos[0]]);
//fwrite($myfile, json_encode($_FILES['photos'][0]);
fclose($myfile);
As a result, there is a file named MyData.jpg written on the server as expected, but its length is zero.
I think there is a mistake in the three lines above but, what did I do wrong?
Right method is to use
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "MyData.jpg");
where "fileToUpload" is the field name you gave for the file button
I think you'll get data here: $_FILES['photos']['tmp_name'][0].
Try it please.
Or
You could rewrite your code like below:
foreach($_FILES['photos']['tmp_name'] as $i=>$file){
if($_FILES['photos']['error'][$i] == 0){
move_uploaded_file($file, "MyData_".$i.".jpg");
}
}
First: I KNOW this is a duplicate. I am creating this because none of the answers to all the other questions satisfy me. I have a very particular situation where I'm using yii and tryi I can't send it through ajax because the php and javascript are on the same page on the same page.
Basically what I'm asking is if you have a page that uses yii and chart js, and you need to render a page that requires two arguments from the clicked bar, which is represented by activeBars[0]:
<script>
canvas.onclick = function(event) {
var activeBars = getBarsAtEvent(event);
<?php $controller->functionThatRendersView($arg1 /**(activeBars[0].value*/,$arg2 /**(activeBars[0].label*/); ?>
}
I don't care if it will render automatically, that is another problem. I just need to get those arguments to the php.
Thanks.
Also, if it helps, I am passing those two values to javascript through php for loops:
labels: [<?php for ($i=1;$i<=$numberIssues;$i++) {
echo $i . ",";
}?>],
The problem with grabbing $i and putting it into the label argument is that I don't know which bar label is the clicked one, I need javascript to pass the clicked bar values back to php.
Explain to us again why you can't use ajax. You say "because the php and javascript are on the same page". That's not what ajax is - you need a different URL for the ajax request, and a separate PHP file or something to handle it.
Without ajax it's impossible for javascript to send information to PHP, because the PHP runs on the server before the javascript runs on the client. Unless of course you want to do a complete page refresh, which is slower and generally worse from the user perspective.
I found an answer to my question! I'm just doing this for anyone else who is stumbling:
To pass javasctipt variable var jsInteger = 5; to php you type (in javascript):
window.location.href = "yourPhpFile.php?phpInteger="+jsInteger;
You access the variable in php like so:
$phpInteger = $_GET['phpInteger'];
This will require a page refresh, and will redirect you to the php file.
I have been reading how to pass variables from a php webpage to a separate javascript file, but am not having any luck.
Please don't mark this as duplicate, as I know there are a ton of things out there telling the ways to do this. I recognize those posts and am more just checking my syntax or seeing if there is anything unique about my specific situation that is causing those methods not to work.
So I have a PHP webpage where I POSTed some variables to:
DOCTYPE HTML
...
<?php
$id = $_POST["id"];
$name = $_POST["name"];
?>
...
HTML code with some usage of PHP variables
javascriptFunction()
end page
Then in a separate javascript file I have:
var markerlocation = '<?php echo $point; ?>';
function javascriptFunction () {
alert("markerlocation");
});
This seems really straight forward, but for whatever reason I can't get it. I also have tried with json encode.
I can delete this when done.
Sincere thanks for any help.
My way:
Declare a Array to store variable for passing variable to JavaScript
Encode the Array to JSON in php
Decode the JSON String from php and store as a JavaScript variable
PHP
<?php
//You may declare array for javascript
$jsVal = array(
'user_name' => 'Peter',
'email' => 'peter#gmail.com',
'marker_location' => '102,300'
);
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>var phpConfig = jQuery.parseJSON(<?=json_encode($jsVal)?>);</script>
Separated javascript file
alert(phpConfig.marker_location);
You can try it
You can point the script tag source to a .php file instead of a .js file, I think that's what you want. Works with image tags too ;)
Edit: some browsers may require the text/javascript mime header in order for it to work properly, but it's not hard with PHP I'll assume you already know how to do that.
On a side note: This option should probably only be used if you're planning on allowing the client to cache the javascript output. If you don't want the client to cache it, you need to set additional headers.
I'm trying to import a local CSV file with headings into a local HTML file, which will then display as a table in a browser.
I haven't been learning HTMLand JavaScript for long, so I don't know a lot about importing and converting. What I need is some advice or possibly a basic script describing the sort of function I need. Explanations and advice are all welcomed!
This is an example of the csv file:
heading1,heading2,heading3,heading4,heading5
value1_1,value1_2,value1_3,value1_4,value1_5
value2_1,value2_2,value2_3,value2_4,value2_5
value3_1,value3_2,value3_3,value3_4,value3_5
value4_1,value4_2,value4_3,value4_4,value4_5
value5_1,value5_2,value5_3,value5_4,value5_5
This is how I'd want to display it:
http://jsfiddle.net/yekdkdLm
<div id="CSVTable"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//jquerycsvtotable.googlecode.com/files/jquery.csvToTable.js"></script>
<script>
$(function() {
$('#CSVTable').CSVToTable('your_csv.csv');
});
</script>
you can use jquery.csvToTable.js to display csv file in html
Fetch an external file.
You have to use xmlHttpRequest for this. Simplified using jQuery (include jQuery library) as.
You will need to run the HTML file in a local server like Apache,
browsers like Chrome doesnt allow xmlHttp for file:// urls.
$.ajax({
type: "GET",
url: "words.txt",
dataType: "text",
success: parseTxt
});
Use a success callback to process the data
parseTxt is the function to which the content of the file is read and passed. You can then write the code in parseTxt to process the text as string.
function parseTxt(text){
var rows=text.split('\n');
//for each row
//cols=rows[i].split(',');
}
This should be enough to get you started I guess.
How to read a text file from server using JavaScript?
You can even try the answer to above question by Shadow Wizard using iframes.
A RAW XMLHttpRequest can be made without jQuery as shown here
I don't think there is a trivial solution to this. An insistence on using client-side JavaScript makes this a more difficult task than doing the processing on the server-side and simply serving up the HTML.
You first need to use JavaScript to fetch the file from the server, the easiest way to do this is with the jQuery library. Next you need to take the data and construct the HTML in the existing document, again, jQuery will simplify this for you.
If you are still learning, I'd recommend skipping the first bit, and simply create a JavaScript variable with the data already in it. This way you can write the code to build the table, get this working, then go back to worrying about how you would actually fetch that from the server using AJAX.
Alternative, look at using a server-side language such as PHP which will incorporate the data into the page before delivering it to the browser. Without knowing more details, this would seem like the more logical solution.
You need to use javascript(jquery) or php
This is the code to open with php and get the values in a table
<table>
<tr>
<td>Header 1</td>
<td>Header 2</td>
</tr>
<?php
$fp = fopen ( "file.csv" , "r" );
while (( $data = fgetcsv ( $fp , 1000 , "," )) !== FALSE ) {
$i = 0;
echo "<tr>";
foreach($data as $row) {
echo "<td>" . $row . "</td>";
$i++ ;
}
echo "/<tr>";
}
fclose ( $fp );
?>
</table>
I used PHP to parse the CSV file on the server side, then format that output as HTML. Along the way, it turns the unique values in the CSV columns into unique filter values to refine the result set.