I'm currently developing a intranet application for my company. Within my application i would like to fetch some variables with javascript and send them to a MySql database through php.
I know that javascript is a client-side and php is server-side so I'm not sure if it's even possible to transfer the variables through.
Goal is to get the current users computer name and store it in a SQL database whenever they are opening the intranet site.
<?php
<script type="javascript">
var network = new ActiveXObject('WScript.network');
<?php $pcName = "<script>document.write(network.computername)</script>";
</script>
?>
This part works perfectly. The computername is stored in the php variable $pcName and it shows fine on the intranet site when I try to echo the variable.
$sql = "INSERT INTO t1 (pcName) VALUES ('".$pcName."')";
But when I insert it into my sql table the value is "<script>document.write(network.computername)</script>".
Am I missing something? Or is it as I assumed that the variable is available on the clint, and the client only.
You will probably have to create and call an "API" of some sort. For example, you could have something like this on the client:
<script type="javascript">
var network = new ActiveXObject('WScript.network');
var pcName = network.computername;
fetch('storeComputer.php', {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
pcName: pcName
})
});
</script>
And then on PHP side:
// storeComputer.php
$json = json_decode(file_get_contents('php://input'));
$pcName = $json['pcName'];
// do what you want with $pcName..
There are many ways, but i use jquery inside javascript to send the parameter to php. Its works for me very well
try this
$('.add_item').click(function(){
var responsecontainer=$('#responsecontainer').val();
var ProductName=$('#ProductTable').val();
$.ajax({
url:"sample.php"
, method:"POST"
, data: {
ProductName: ProductName,
}
, success: function(result){
// do some thing here
}
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
}
use can use some other method too.
Yes, it's possible.
Javascript can launch any URL with parameters, notably including JSON encoded parameters; the URL can launch a CGI script; the CGI script can catch the JSON and interact with the MySQl; and then return the result to javascript, either asynchronously or synchronously. Here's an asynch URL launch:
// this is asynchronous - result comes back to callback later, while this returns immediately
// -----------------------------------------------------------------------=======------------
function callAjax(url, callback)
{
var xmlhttp;
// compatible with IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
.
Here's a callback:
function cb_myCallback(theStuff)
{
// process theStuff here. If it's JSON data, you can unpack it trivially in Javascript,
// as I will describe later. For this example, it's just text. You're going to get
// back "hello, Ben"
console.log(theStuff);
}
.
So here's how I might use that to call a script that can access the database:
function pyRequest(upd_data,upd_callback)
{
var cd_url;
cd_url = '/cgi-bin/myPython.py?myData=' + encodeURIComponent(upd_data);
callAjax(cd_url,upd_callback);
}
pyRequest("Ben",cb_myCallback);
.
So here’s what happens. pyRequest() builds a URL that can call the Python (or whatever you like to use) script. callAjax() actually does the calling. This all returns immediately to the calling code. Later, when the script has completed whatever its task is, the callback, in the example cb_myCallback(), is sent whatever the script emitted.
Synchronous Approach
There may be times when you won’t want to use an asynchronous callback, because you can’t proceed until you have the data you asked for. In such cases, you need to use a synchronous request, which will not return (with the actual response) until the response has been received from the script. Note that in this function, I embed the URL to demonstrate a little variety in possible structuring of these types of usages:
// this is synchronous - result returns only when called script provides it
// ------------------------------------------------------------------------
function syncCallAjax(spdq_myData)
{
var remote = '__Unset__';
var request = new XMLHttpRequest();
var remote_url;
remote_url = '/cgi-bin/myPython.py?myData=' + encodeURIComponent(spdq_myData);
request.open('GET', remote_url, false); // false makes the request synchronous
request.send(null);
if (request.status === 200)
{
remote = request.responseText;
}
return(remote);
}
Related
I'm currently building a site that should be able to function as a ftp sort of browser. Basically what I have is a ftp server with some images on it.
What I can't figure out is: if I browse to this ftp site I can view the source of the ftp site (as seen in some browser), what I need is to save that source in a way to a string (using javascript).
The reason is, that I will make som kind of 'image' browser. I plan on accomplishing that by reading the source into a string, then copy all the image sources and use innerHTML to create a new layout.
In short: I want to read information from a url and display it in a different way.
Well, can't seem to get it working. The problem might be that I cannot use serverside scripting. Would it be possible however to put a file on the ftp server that I can load that can dynamically load the data in the same folder? (when I say FTP I actually mean a NAS server with FTP access).
Your answer is Ajax. It can POST and GET data from an URL, just like browsing a website, and it will return the HTML as a string.
If you plan on using jQuery (real handy), it is easy to use Ajax. Like this example (does not work without the library):
$.ajax({
url : "/mysite/file.html",
success : function(result){
alert(result);
}
});
If you want to use default Javascript, take a look at http://www.w3schools.com/ajax/default.asp
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajax_info.txt", true);
xmlhttp.send();
IN Javascript to get data without using alert() :
$.ajax({
url : "/mysite/file.html",
async:false, //this is the trick
success : function(result){
//does any action
}
});
Modern Promise-based Fetch API solution (no more XMLHttpRequest or jQuery.ajax()):
fetch('data.txt')
.then(response => response.text())
.then(data => console.log(data));
Example using async/await:
async function myFetch() {
let response = await fetch('data.txt');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
let text = await response.text(); // await ensures variable has fulfilled Promise
console.log(text);
}
There's not much to add to what Niels and rich.okelly have said. AJAX is your way to go.
Keep in mind though, that cross-domain restrictions will prohibit you to access data that is not in the same domain. You'll find a possible workaround here.
I developed a small Javascript/jQuery program to access a collection of pdf files for internal use. And I wanted to have the information div of a pdf file highlighted if the file actually exist.
Is there a way to programmatically determine if a link to a file is broken? If so, How?
Any guide or suggestion is appropriated.
If the files are on the same domain, then you can use AJAX to test for their existence as Alex Sexton said; however, you should not use the GET method, just HEAD and then check the HTTP status for the expect value (200, or just less than 400).
Here's a simple method provided from a related question:
function urlExists(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.status < 400);
}
};
xhr.open('HEAD', url);
xhr.send();
}
urlExists(someUrl, function(exists) {
console.log('"%s" exists?', someUrl, exists);
});
Issue is that JavaScript has the same origin policy so you can not grab content from another domain. This won't change by upvoting it (wondering about the 17 votes).
I think you need it for external links, so it is impossible just with .js ...
If the files are not on an external website, you could try making an ajax request for each file. If it comes back as a failure, then you know it doesn't exist, otherwise, if it completes and/or takes longer than a given threshold to return, you can guess that it exists. It's not always perfect, but generally 'filenotfound' requests are quick.
var threshold = 500,
successFunc = function(){ console.log('It exists!'); };
var myXHR = $.ajax({
url: $('#checkme').attr('href'),
type: 'text',
method: 'get',
error: function() {
console.log('file does not exist');
},
success: successFunc
});
setTimeout(function(){
myXHR.abort();
successFunc();
}, threshold);
You can $.ajax to it. If file does not exist you will get 404 error and then you can do whatever you need (UI-wise) in the error callback. It's up to you how to trigger the request (timer?) Of course if you also have ability to do some server-side coding you can do a single AJAX request - scan the directory and then return results as say JSON.
Like Sebastian says it is not possible due to the same origin policy. If the site can be published (temporarily) on a public domain you could use one of the link checker services out there. I am behind checkerr.org
As others have mentioned, because of JavaScript's same origin policy, simply using the function from the accepted answer does not work. A workaround to this is to use a proxy server. You don't have to use your own proxy for this, you can use this service for example: https://cors-escape.herokuapp.com (code here).
The code looks like this:
var proxyUrl = "https://cors-anywhere.herokuapp.com/";
function urlExists(url, callback) {
var sameOriginURL = proxyUrl + url;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.status < 400);
}
};
xhr.open('HEAD', sameOriginURL);
xhr.send();
}
urlExists(someUrl, function(exists) {
console.log('"%s" exists?', someUrl, exists);
});
I have created a mobile application that scans the surrounding Bluetooth devices and I am able to put the devices into an array list.
Now, using the http POST method, I have to send a JSONObject having this array list to a url and even for this I have written an expected code on the android app(I am sure this code will work because I have already worked on this using POST method to URL's and displaying the response on the activity).
But, how to listen the JSONObject, sent by any android app to the URL, parse it and show it on that particular URL's webpage ?
(In short I am looking for a Javascript code which can handle this and show the list.)
if you already have the URL where the JSON is being posted to you can do:
plain js:
var request = new XMLHttpRequest();
request.open('GET', 'URL', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
with jquery:
var getData = $.getJSON('URL');
getData.done(function(data){
// you have access to data here
});
I'm sending a POST from a chrome extension content script to a server I control. I setup the permissions in the manifest ok. Here is my XHR code. (I want to avoid jQuery for this). Its sending an empty responseText
var xhr = new XMLHttpRequest();
xhr.open("POST",'http://mysite.com/make',true);
xhr.onreadystatechange=function() {
if (xhr.readyState == 4) {
var res = JSON.parse(xhr.responseText);
console.log(res);
}
}
xhr.send({'textbox':data[0].user,'from':'extension'});
data[0].user is an object I got directly from the Twitter API
in my CI controller I have
$user = $this->input->get_post('textbox', TRUE);
$from = $this->input->get_post('from', TRUE);
$fullURL = 'http://www.google.com'; //example of a URL from code.
$json = $this->output->set_content_type('application/json');
$json->set_output(json_encode(array('URL' => $fullURL)));
The response text is empty
a jquery call on the other hand works fine
$.post("http://mysite.com/make", { 'textbox': data[0].user, 'from':'jquery' },
function(data) {
console.log(data);
});
Reason is simple, JQuery post method can accept JSON and then convert it to string and send to the server.
What you are trying to do is to directly send JSON here :
xhr.send({'textbox':data[0].user,'from':'extension'}) // Incorrect way
send method should either accept NULL or a string which is generally made up of QueryString Parameters like.
xhr.send("textbox="+ data[0].user + "&from=extension"); // Correct way
This will ensure that your data goes to the appropriate URL with textbox and from as post request parameters.
and queryString will be generated like textbox=username1234&from=extension in the packet's body unlike one goes in Get with the headers along side the URL.
jQuery's post method makes it simpler for you to format data you send using JSON and then internally it converts that to a queryString to send parameters.
You can't directly send Javascript object like that with an XHR object!
Also checkout this example:
http://beradrian.wordpress.com/2007/07/19/passing-post-parameters-with-ajax/
I'm new in JS, and having quite hard time reading the following JS code.
The first parameter of the function is a url to a PHP script, the second is a string.
What confuses me is how to read code after the line:
self.xmlHttpReq.open('POST', strURL, true);
What happens after this? Which code should i look after this line? The script?
What happens after open?
function check_detail(strURL, pids)
{
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function()
{
if (self.xmlHttpReq.readyState == 4)
updatepage(self.xmlHttpReq.responseText, pids);
}
self.xmlHttpReq.send(getquery(pids));
}
The key is the call to "send()", which actually launches the HTTP request. That happens, but the code then proceeds immediately without waiting for the result.
When the server responds, the browser will invoke the anonymous function set up as the "readystatechange" handler. Exactly when that happens is unpredictable; it's asynchronous, in other words.
Thus, the "updatepage()" call will happen long after the "check_detail()" function has returned.
When you make an Ajax request (which is what you are doing here) it is asynchronous, which means that you don't know exactly when it will return so you can't just wait for the return.
Instead, you set up your function so that, when the request returns, a function is kicked off to handle the response. This is the onreadystatechange piece.
So the chronology will be: first the send() will occur, which will send the result of the getquery() method up to the PHP page. When that returns, the function defined within onreadystatechange will fire, which will call updatepage() and pass it both the text that was sent back from the Ajax call, and also the pids parameter.
If you're new to JavaScript, then I'd say it's a waste of time trying to figure out what's going on here - you're learning how to use the XHR object, how to make that cross-browser, and you're learning JavaScript at the same time.
I'd recommend doing the Ajax with a JavaScript library such as jQuery - don't try to learn it all now while you're learning JavaScript as well.
Most of that could be replaced with something along the lines of:
$.post(strURL, function (data) {
updatePage(data);
});
this is simple Ajax function
function check_detail(strURL, pids)
{
// definning new variable
var xmlHttpReq = false;
// creating variable self which will function as this
var self = this;
// creating HTTP request maker for Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// creating HTTP request maker in IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
// so this is the confusing part right ?
// xmlHttpReq.open opens connection tu the strURL and infomation sending method
// will be POST method ( other passible values can be GET method or even else )
self.xmlHttpReq.open('POST', strURL, true);
// this defines HTTP request header (small information about what we are sending)
// in fact this is sending Content-type of information
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// when HTTP request maker state will be changed for example:
// the data will be sent or data will be received this function will be fired
self.xmlHttpReq.onreadystatechange = function()
{
// readyState 4 means data has been received
if (self.xmlHttpReq.readyState == 4)
updatepage(self.xmlHttpReq.responseText, pids); // updatepage is user defined function
}
// this actually sends the HTTP request which is made above
// but don't be confused because of this code ordering
// I mean the function defining what to do when content will be received is implemented
// before sending HTTP request right ?
// thats because if the data is too small and internet is really fast HTTP query can be
// executed faster then defining new function which will cause javascript error
self.xmlHttpReq.send(getquery(pids));
}
hope this helps
if not
more about ajax: http://en.wikipedia.org/wiki/Ajax_(programming)