Keep ajax POST formatting / live post feed - javascript

I'm just working on an openvz script to run some VM's at home.
Anyway, I have been working on some js and ajax functions to send post requests, all ending up in an innerHTML section.
However, when the command is run, the result of the command is merged into a one line result, I would like to keep the original formatting because some vzctl commands produce very long outputs.
I originally had this working with PHP and a live result of the command would be outputted into the web browser.
I would like to keep the result on the same line and if possible, have it like my old setup with a sort of live console feed.
This used to work because I was just using php, but now I have AJAX on front of the php, and it removes the formatting.
CTID NPROC STATUS IP_ADDR HOSTNAME 101 21 running - -
The above is a sample output of vzlist when run with ajax, and the bottom without, how can I fix this?
CTID NPROC STATUS IP_ADDR HOSTNAME
101 21 running - -
Also is it possible to put the ajax output into a buffer like I had with php?
<?php
$cmd = 'sudo '.$_POST["command"].' 2>&1';
while (# ob_end_flush()); // end all output buffers if any
$proc = popen($cmd, 'r');
while (!feof($proc))
{
echo fread($proc, 4096);
# flush();
}
?>
Current PHP file with live console.
function whoami () {
$.ajax({
url:"virt.php", //the page containing php script
type: "POST", //request type
data: "command=vzctl start 101",
success:function(result){
document.getElementById("test").innerHTML =(result);
}
});
}
function ls () {
$.ajax({
url:"virt.php", //the page containing php script
type: "POST", //request type
data: "command=vzlist",
success:function(result){
document.getElementById("test").innerHTML =(result);
}
});
}
Current html with ajax.
Sorry for the long read, thank you.

You can try adding html and filesystem line breaks when you create the data for result.
When generating it, I assume in php, you would place the following just after where you would like the break.
"<br>\r\n"
You may already be generating the newlines, if so you could wrap your output in nl2br(). This will create html <br> elements in place of newlines. See nl2br.

Related

PHP file called by javascript and another php file

I have a php file (I will call ORIGINAL) which do some calculations (through db mysql). I want to read this php from javascript. For that operation I have used ajax function and my php uses echo $result to print the data I need.
Everything is perfect here.
What happends now, I am creating another php file which need to call the ORIGINAL php file. If I want to call it, I must change the echo to return which is normal. This causes that my javascript call doesnt work.
Do you have a solution which work for both situations?
Thanks in advance.
Do you mean something like this?
original_php_file.php:
<?php
require_once "other_php_file.php"; // include all of the other files contents
// all code contained within original_php_file
?>
You were being pretty broad with your request (not including file names or code), so this is all I can assume you need.
Tell me if it helps :-)
Just send one more parameter into your ajax request to tell that ORIGINAL php file what type of output it should return.
Into your ORIGINAL file check for that output so you can understand from where that request come and what output you should return.
$.ajax({
url: 'ORIGINAL.php',
data: 'data=test&output=1',
success: function(r){
// here you have your output
}
});

NodeJS + JQuery php variable in JScript

No, this is not like the other questions:
I need to have a php variable in a client-side javascript file. I tried using ajax, but due to the application being Node.JS I cannot properly find the link to the php file on client side.
I'm making a draw my thing game and since its a small project I have the words in a phpfile. If I put them in javascript clients could use 'inspect element' to find all the answers, php doesn't allow them to.
Basically a word is given to one client that he has to draw, the other client guess that word. The 'server' should select a word that only the (drawing) client can see.
TL;DR: Get php variable in javascript within a node.js application. (Serverside or clientside doesn't matter)
Code so far
(Client) Word.js
$.ajax({
url: 'util.php',
type: 'POST',
dataType: 'json',
success: function(result){
console.log(result['word']);
},
error: function(){
console.log("Error retrieving word.");
}
});
Util.php
$words = array("", ""); shuffle($words);
$selectedWord = $words[0];
$rtn = array('word' => $selectedWord);
echo($rtn);
Where you have...
echo($rtn);
... you want ...
echo json_encode($rtn);
Otherwise what your script outputs is just the word "Array".

PHP $_GET and underlines

I have a very short piece of PHP that I use to make HTTP requests from JavaScript.
<?php echo file_get_contents($_GET['url']); ?>
I have used it successfully in a few projects, but am running into a problem with making requests in my current project. Based on my searching, I believe it may be caused by the underscore in the request, though through my searching and not knowing PHP, I have not been able to confirm that.
Below is an example of what I am doing from JavaScript:
$.get("grabber.php?url=" + "http://tidesandcurrents.noaa.gov/api/datagetter?station=8573364&begin_date=20160202&end_date=20160203&product=predictions&units=english&time_zone=gmt&format=json&application=poseidonweathercom+&datum=MLLW", function(forecast) {
console.log(forecast);
});
If I copy the url and put in it in a browser, I get back the JSON that I requested. When I use the code above, I end up getting an error message from NOAA:
Wrong Product : Product cannot be null or empty Wrong Time zone: Time zone cannot be null or empty Wrong Unit:Unit cannot be null or empty Wrong Format: Format cannot be null or empty Wrong Date: The beginDate cannot be null or empty
Do I need to use a regex for the underscore in PHP? Is there some other issue that I do not understand?
Thanks.
You need to send it encoded, which will convert all the underscores/spaces/ampersands etc. with their encoded equivalents:
var url = "http://tidesandcurrents.noaa.gov/api/datagetter?station=8573364&begin_date=20160202&end_date=20160203&product=predictions&units=english&time_zone=gmt&format=json&application=poseidonweathercom+&datum=MLLW";
$.get("grabber.php?url=" + encodeURIComponent(url), function(forecast){
console.log(forecast);
}
Using encodeURIComponent() on that URL shows:
http%3A%2F%2Ftidesandcurrents.noaa.gov%2Fapi%2Fdatagetter%3Fstation%3D8573364%26begin_date%3D20160202%26end_date%3D20160203%26product%3Dpredictions%26units%3Denglish%26time_zone%3Dgmt%26format%3Djson%26application%3Dposeidonweathercom%2B%26datum%3DMLLW
Alternatively, if you just want to access the JSON data and handle it within the JavaScript function, you can retrieve the data via the URL directly, without having to encode the URL:
$.get("http://tidesandcurrents.noaa.gov/api/datagetter?station=8573364&begin_date=20160202&end_date=20160203&product=predictions&units=english&time_zone=gmt&format=json&application=poseidonweathercom+&datum=MLLW", function(forecast) {
console.log(forecast);
});
Um why do you even need your php code ... the code below will work just fine and eliminate your server overhead.
$.get("http://tidesandcurrents.noaa.gov/api/datagetter?station=8573364&begin_date=20160202&end_date=20160203&product=predictions&units=english&time_zone=gmt&format=json&application=poseidonweathercom+&datum=MLLW", function(forecast) {
console.log(forecast);
});

Posting long text from scripted browser (phantomjs) to a php script wont go over 2kb /2400 char

im doing some data scraping using phantomjs (basically its a browser you can code in and run it from command line)
i'm collection information about football matches (teams / countries / leagues , .... ) each as an object , put them all in an array , encode array to jason format and post the result to a php script
result could be a very long text based on amount of games on each day and when that happens i wont get the full text on the php script
in the php script i've stored the posted data in a text file to see whats going on , each time its about 2.3kb max and 2397~ characters
while the original posted text which i can see on the terminal is about 40kb and 40000 chars
so something must be limiting the characters here is my php.ini info which is more than enough :
post_max_size -> 20M
max_input_vars -> 100000
memory_limit -> 256M
here the simplified version of my code :
var res = page.evaluate(function(sport) {
var matches = new Array();
$('div#table-matches').find('.table-main').find('tr').each(function(index, element) {
var obj = {
teams : $(this).find('td').text() ,
link : $(this).find('td').find('a:last').attr('href') ,
};
matches.push( obj );
});
return matches ;
});
var postBody = 'sport='+sport+'&data='+JSON.stringify(res);
console.log(postBody);
page.open('http://xxxxx/result/save', 'POST', postBody, function(status) {
phantom.exit();
});
here is what i got in the php script :
[{"country":"Japan","league":"Emperors Cup","link":"/soccer/japan/emperors-cup/kobe-urawa-65k5LIMh/","match_date":"2015/12/26 04:00","teams":"Kobe - Urawa"},
{"country":"England","league":"Ryman League","link":"/soccer/england/ryman-league/wingate-finchley-metropolitan-police-rwuqgSz9/","match_date":"2015/12/26 12:00","teams":"Wingate
the json code has been cut off in the middle , so its not a valid json
is there anything else i should do ?
Usually it's much simpler to look for the answer when HTML that your code operates on is provided in the question (a link to the site is as good).
Luckily you'fe left some clues in a portion of json file, namely the link to one of the pages from the scraped site: /soccer/england/ryman-league/wingate-finchley-metropolitan-police-rwuqgSz9/
If we find it with Google and look at the source it will be clear that data in php script is truncated right at the title of the team «Wingate & Finchley - Metropolitan», that contains an ampersand, which serves as a delimiter for variables and values sent via an URI request and breaks your data variable into several others.
So, to amend your script you just have to encode the data string properly:
var postBody = 'sport='+sport+'&data='+encodeURIComponent(JSON.stringify(res));
Other way to find the cause of this issue would be to check $_SERVER and $_POST arrays at the server side, just dumping it to a file and looking if the whole data was really present, since you've already done great job checking PHP config that it should be present.
A way to go around the issue, had it not been solved (if, for example, PhantomJS had a weird bug with POST equests), would be to create a temporary file with data and send to php the path to that file (presuming the parsing is done on one and the same server):
var fs = require('fs');
var filename = '/tmp/scraped_' + (new Date()).getTime() + ".json";
fs.write(filename, JSON.stringify(res), 'w');
page.open('http://xxxxx/result/save', {"filename" : filename}, function(status) {
phantom.exit();
});

Mysql query result is not giving me the right result

I'm updating my php page each 5 seconds
window.setInterval(function(){
console.log(<?=mysql_num_rows(mysql_query("select * from records"))?>)
}, 5000);
If I have 5 records in my table, the output will be 5,
but when I insert a new record, the output remains 5 unless I refreshed the whole page, then it will be 6..
What's wrong?
You have a fundamental misunderstanding of how PHP and Javascript work. Don't worry, it's very common when first learning web development!
When you use PHP to print things onto the page (for example the code inside <?= ?>), the code is executed on the server. Try viewing the source of your page, and you'll see that when the browser receives the page, the PHP code has already been replaced by its result.
This means that when your Javascript loop runs, it's simply writing out the same precomputed value repeatedly.
To accomplish what you're going for, you'll either need to accept simply refreshing the page every 5 seconds, or read up on AJAX. AJAX is how you can load new content from the server (so, anything from the database) without reloading the page. It's what StackOverflow uses to show "1 new answer to this question", for instance.
This is because you are mixing PHP with JS, PHP value is written on page load and it remains that for all the time you stay in the page.
You should use a Ajax request that request again the value.
Do a PHP page that only returns this value:
<?=mysql_num_rows(mysql_query("select * from records"))?>
Then extend you JS with something like this:
setInterval($.ajax({
url: 'your-url-with-php-result',
type: 'GET',
cache: false,
success: function(result){
console.log(result);
}
}), 5000);
You need also to include Jquery to do this
you can not use php in javascript codes
you soulde save php in example.php and you call example.php in javascript code
your example.php like this
<?php
echo mysql_num_rows(mysql_query("select * from records"));
?>
and you can now get data from example around 5 second time by this code (load is jquery function)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
setTimeout(function(){
$("#showRes").load("example.php");
}, 5000);
</script>
</head>
<body>
<div id="showRes"></div>
</body>
</html>
you are normally mix the concept of jaavscript and php .you can solve this very easily . by passing php value into ajax and that value u should catch in that javascript .Try viewing the source of your page, and you'll see that when the browser receives the page, the PHP code has already been replaced by its result.
write php code in php page like:-
<?=mysql_num_rows(mysql_query("select * from records"))?>
and use js as different page . call that value as your requirement.
like:--
setInterval($.ajax({
url: 'your-url-with-php-result',
type: 'GET',
cache: false,
success: function(result){
console.log(result);
}
}), 5000)
if u need some jquery then you also include that in your code .

Categories

Resources