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".
Related
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.
So I made a website that displays FPS information stored in a mysql database. For each second of gameplay I have a pair of number(fps)-image(screenshot).
I display the numbers in a line chart made with JavaScript. The behaviour desired is when I click on a bullet in the chart, the screenshot for that particular second is displayed in a div on the page.
I have to mention that the screenshots are stored in the database and they are very low in size. I display then using PHP like this:
$query = "SELECT `image` FROM `logs` WHERE `session_id`=".$_GET['session']." AND `second`=".$second;
$sth = $mysqli->query($query);
$result=mysqli_fetch_array($sth);
if (!empty($result))
echo ' <img id="screen" src="data:image/jpg;base64,'.base64_encode($result['image']).'"/>';
The method I'm using now is when I click on a bullet in the chart (action recorded in JS), I send it as a GET parameter and read it with PHP afterwards, like this:
window.location.href = url + "?second=" + second;
This method obviously will refresh my page. The problem is, the chart I made also has a zoom/scroll option and that resets whenever the page is refreshed, making the experience very bad for the user.
Is there any method to display the screenshots without refreshing the page, for this particular case (where I have to query the database for each click/picture)? Maybe there is a better way of approaching this problem?
Thanks.
I think you've got 2 solutions which are Ajax or Websocket depending your needs.
AJAX
Ajax permit to asynchronously, only when you need, call the server and get datas from an URL which could be a webservice or PHP page... Perhaps, it's the better solution in your case.
To make it easy, you can use JQuery library by donwloading the script and insert it in your HTML :
<script src="jquery-3.0.0.min.js"></script>
To call the server, using JQuery :
$.ajax({
url: url + "/yourphppage.php",
data: "parameter=" + yourOptionelParameter,
async: false,
success: function(data) {
refreshYourChart(data);
},
error: function() {
alert("Your error");
},
contentType: 'charset=utf-8'
});
Or if your prefer pure javascript.
Now, you just have to work on the presentation of your data, on the server side. It could be what you want HTML, TXT, JSON, XML...
Websocket
Websocket is like a permanent tunnel opened between your server and the client. Each side can ask or send datas in real time.
It seems to be a library server side :
http://socketo.me/
And client side, it's very easy :
Nice documentation on mozilla website
Hope it helps. Good luck.
To change a picture source, as I see the easiest way is using an ajax call, so you can send any kind of parameters to your server, and in return your will get your new picture source.
$.get('urlToYourServer.com?parameter=1', function(data){
$('#img').attr('src', data.imgSrc);
})
I have a problem. I have a JavaScript function which should update an XML file (btw please check if its correct):
function changename(node2){
var nodenumber = node2;
var newname = "tescik";
$.ajax({
type: "GET",
url: "config2.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('device').each(function () {
var node = $(this).find('node');
if (node.text() == nodenumber) {
var name = $(this).find('name').text(newname);
alert(name.text());
$.post(
"config2.xml",
{
name: "Bravo"
},
function(dane){
alert("Dane otrzymane: " + dane);
}
);
}
});
}
});
}
The problem now is: How to update that file on the web server? I can not install PHP server on this. There can be only a web server. Nothing else.
Please send my any instruction or materials which can help me.
You can't save anything to a server without any server side technology. Either you use PHP, ASP.NET or any similar server side technology or leave it.
There must be a service on the other side dictating what to do with the file it receives. You can't just copy the file over there (if you want to, use FTP or something like that)
Just realize what it will mean if this is possible:
What if I could just change a file on your webserver. Would you like that? No, of course not! At least there must be some authorization, authentication, and some software that tells where to place the file.
That is not possible. If the server does not provide some server-side way to update a file, then you can’t do it.
Imagine if a simple JavaScript file that is executed on the client’s machine could modify files on the server. That would be highly insecure. Instead, you will need at least something that processes this change on the server itself. And it’s really recommended to add some validation there too, so that one cannot just store anything (for example malicious code).
I have problems when saving html5 data from a page into mysql through an ajax request and trying to retrieve it back with ajax. HTML attributes that trigger some javascript such as
<onload> or <iframe> will be stored as <on<x>load> and <if<x>rame> in the database and thus screw up the page when loading it.
Here's a short description of what I am trying to accomplish: I want registered users to have the ability to highlight text on my site and get the highlighted text back after refreshing the page, relogging etc.
What I have done so far: I implemented a javascript highlight library on my server that allows users to highlight text. That works well.
By clicking a button, those data are then saved into mysql through jquery ajax post. See specific code here:
Javascript
$(document).ready(function() {
//saves highlighted data in var "highlighted"
$('#savehighlights').click(function() {
var highlighted = $('.tabcontent.content1').html();
//send data to server
$.ajax({
url: 'highlight.php',
type: 'POST',
data: {highlighted: highlighted},
dataType: 'html',
success: function(result) {
console.log(result);
}
});
});
Saving the data to mysql works generally, but it looks as if certain commands are disabled through the process (e.g. onload becomes on<x>load5). The data are stored in the database as longtext and utf8_bin. I also tried blob, but problem remains. I also tried different dataTypes with Ajax such as 'text' and 'script'. 'Text' causes the same problem and 'script doesn't work at all. I also tried the ajax .serialize function, but no luck either.
I really don't know what to do about it and I am not sure what is causing the problem, Ajax or mysql? I was searching the web for an answer, including many articles in stackoverflow (which normally always give me the answer), but this time I am stuck. Either I don't know enough about it to look for the right question, or I just don't have any luck this time. So, any help would be greatly appreciated.
I was requested to add some more information. Here it is:
I am actually doing this on my local server (localhost) with XAMP, so security issues should not be a problem, right? If it is of any help, I am doing this in a Tiki Wiki CMS. The php script that is called through ajax (highlight.php) is the following:
require_once ('tiki-setup.php');
include_once ('lib/highlights/highlightslib.php');
$highlighted = $_POST['highlighted'];
$highlightslib->save_highlights($user, $highlighted);
The highlightslib library is here:
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
header("location: index.php");
exit;
}
class HighlightsLib extends TikiLib
{
function save_highlights($user, $highlighted) {
$saveHighlights = $this->table('tiki_user_highlights');
$saveHighlights->insert
(array(
'user' =>$user,
'highlightId' =>'',
'data' =>$highlighted,
'created' =>$this->now,
)
);
return true;
}
};
$highlightslib = new HighlightsLib;
I am using the following click function for a purpose. What can I add so it will add 1 in a txt file when it is clicked? Like a counter on how many times it was clicked.
Thank you
$("#clearme").click(function(e) {
e.preventDefault();
// i have some stuff here
});
You can't access or edit files from the front-end. You'll need PHP or something. You can save it in a variable and pass it and process it with ajax. Something like this, untested:
var num = 0;
$button.click(function(){
$.ajax({
url: 'bla.php',
type: 'POST',
data: { num: ++num }
//...
});
});
And in PHP:
$num = $_POST['num'];
// Add to file stuff
you will have to modify the text file on the server. Send a ajax request every time the click event happens.
$("#clearme").click(function(e) {
$.post("url")
e.preventDefault();
// i have some stuff here
});
Text file where? On the server or the client machine?
If you're aiming for the client machine, javascript and jquery alone aren't going to work. There are security measures to prevent this so that would be hackers don't drop trojans on our machines every time we visit a website.
That leaves the server.
Accomplishing this depends entirely on the server side language/framework you are using (i.e. PHP, JSP, .NET).
You didn't post the reason behind needing to do this, so I'll offer the option of writing the value to a cookie instead of a file, but since you haven't told us more about what you're up to, this might not be a viable solution.