XMLHttpRequest doesn't work from .js - javascript

I have this code that I want to use to pass information to a php file:
<script>
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "page.php?sess=123123", true);
xhttp.overrideMimeType('text/xml; charset=UTF-8');
xhttp.send(null);
</script>
If i echo this code in my .php page, it works on page load ("page.php" recieves the sess variable and stores it). However, when I copy this code (without the script tag) into a .js file that I use in my main php page, it doesn't work.
The idea is that I want to pass sess parameter to page.php when a specific javascript based timer is triggered.
Your help is appreciated.

Related

Loading Images into Gallery using PHP and JavaScript takes very long sometimes

A callback function triggers when my XMLHttpRequest has finished. I use an asynchronous JavaScript Function to load the content of a file that has been created by the PHP file_put_contents() function.
My problem is, that sometimes loading the gallery elements takes a very long time. I should rather return the html code I want to load as a string instead of writing it into a file.. but I do not know how?
This is my Javascript:
function xhr(php, form, after) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
after();
}
}
xhr.open('POST', php, true);
xhr.send(new FormData($(form)));
}
How can I get the corresponding PHP script to export a String? I would need something that puts $myExportString as parameter inside after() then I could use it like this:
xhr("../session/searchquery.php", "searchfilterterms", function( myExportString ) {
document.getElementById("someDiv").innerHTML = myExportString;
});
How can this be done?
There's no need to save a file on the server. You can just return the generated HTML string in the response to your XmlHttpRequest, and then write some Javascript to put that HTML into your page.
Otherwise a) you've got the overhead of disk I/O, and b) you're having to make 2 requests to the server (one to generate the HTML, and another to retrieve the file it's been saved to). This is not efficient at all.
In the PHP, instead of saving the generated HTML string to the disk, you can echo it, e.g. something like
echo $finalVariableWithHTMLString;
(I don't know your exact code as it's not shown in the question). If you echo it, then it becomes the contents of the response to the AJAX call. That's how you return a response to a HTTP request in PHP - you echo stuff to the output.
You can then get it from the xhr.responseText variable in the JavaScript. So you'd be able to write
after(xhr.responseText);
in your example, to pass the HTML to your after() function.

Saving a file to server using PHP and JS?

I have been trying this for a few hours now, googling around and trying several approaches. The code is so simple I don't understand why it doesn't work. I am using 000webhost free hosting atm just to test this out.
I literally just wanna pass a variable to the php file for it to save in a text file, in this case "ayy".
Latest code (file does not even get created):
JS Code
function doSave(){
xhr.open("POST", "save.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send("ayy");
}
PHP code (save.php)
<?php
file_put_contents('data.txt', file_get_contents('php://input'));
?>
I did also have this code below earlier, however it only created a blank file and would not append any text to it:
index.htm
function doSave(){
var datastr = "ayy";
var xmlhttp = new XMLHttpRequest();
xmlhttp.setRequestHeader('Content-Type', 'application/json');
xmlhttp.open("GET", "save.php", true);
xmlhttp.send(datastr);
}
save.php
<?php
$post_data = $_POST['datastr'];
$f = fopen("data.txt", "w+");
fwrite($f, $post_data);
fclose($f);
?>
Any suggestions why this might not be working? All I can think of is the server not supporting it or something, however I can get it working fine if I specify the variable IN the php file and using a GET request to simply just post the variable. However the data is going to be dynamic so I need to pass it from client-side using js.
Thanks.

Writiing to a SERVER file using JS

Tried all solutions.. none of them seem to work for me.
Basically, I have this website UPLOADED on the server that has a button which when clicked does a simple task of loading a file from the server, displaying it and adding +1 to it and then saving it back.
The main question now arises, I tried all the ways which I could find on the net to save the file back but it doesn't seem to work for me. Any specific advice on how can I fix this issue using JS?
UPDATE - One way I am using is - (Doesn't work tho)
fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("TOTAL.TXT", true);
var text = test1;
s.WriteLine(text);
s.Close();
Where test1 is the name of the variable which i am trying to write.
assuming that you have php on server try this js
var data = new FormData();
data.append("data" , 1);
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', '/path/to/php', true );
xhr.send(data);
php script
<?php
if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = "filname.txt"
$file = fopen("upload_or_whatever_path/" .$fname, 'w') or die("Unable to open file!");// open file
fwrite($file, $data);
fclose($file);
}
?>
The code you've shared belongs to the Windows Scripting Host platform. That's an automation solution for Microsoft Windows that's by no means intended for public web sites.
File upload implementation requires a proper server-side programming language (PHP, JSP, Node...). Client side code can be as simple as a static HTML form.

Storing the names of all files with a certain extension in a folder in a string?

I have a folder on my webserver to which I, using a form and a PHP script allow people to upload files. I then need to use these files (xml-files) in another script. This means that I need the script to, everytime it is loaded, find all files of the extension .xml and store their names in an array.
Is this possible using Javascript (this is preferred since the script that needs all filenames is written in Javascript)? Otherwise, what is the best solution?
Thanks for any help!
Finally managed to solve it. Heres my PHP script:
<?php
$files = array();
foreach (glob("../pathtofolder/*.xml") as $file) {
$files[] = str_replace("../guide/", "", $file);
}
echo json_encode($files);
?>
This is "sent" to the javascript using an XMLHttpRequest:
var oReq = new XMLHttpRequest();
oReq.onload = function() {
var files = JSON.parse(this.responseText);
};
oReq.open("get", "phpscript.php", true);
oReq.send();
The variable files now contains all filenames!

Blank $_POST var in PHP using AJAX

All I'm trying to do is send a string, in html, to a script written in PHP. I've tried several solutions, including making an html element and putting it in a form and then passing the form (didn't work). I don't know the basics of AJAX or PHP, everything is just kind of being pieced together via what I can google. Here's one way I trying to remedy the situation: (The regexp replaces the first line of the file, which I works. I tried foreach loops with assigning a variable to $_POST[$key], I tried sending just the string with html hoping that would work. I believe the problem lies in the HTML, or in the AJAX call, because I can make the form submit() to the .php file and then it works, however, that would change the browser location to that file and obviously with AJAX, that's not what I want. Anyone have any ideas (other than JQuery syntax)?
HTML
<form>
<input type="hidden" name="test" id="test" value="testString">
</form>
JavaScript AJAX call
function sendString()
{
var data = document.getElementById("test");
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open('POST', 'testing.php', true);
xhr.send(data);
}
PHP File
<?php
$line = $_POST['data'];
$file = 'test.txt';
file_put_contents($file,preg_replace('/^.+/',$line,file_get_contents($file),1));
?>
EDIT: Thanks for the responses, but non have worked. I tried:
document.getElementById("test");
document.getElementById("test").value;
and
xhr.send(data.value);
None of these worked. Still Blank lines. I also tried the extended solution.
Your problem is here:
var data = document.getElementById("test");
You're creating a reference to your html element. You need to reference the value property of your element.
var data = document.getElementById("test").value;
Also, you are only sending the value and not a key value pair to the server. So xhr.send(data); will only send the value. Your PHP script won't know that $_POST['data'] is what you mean. You need to format var data as
var data = "data=" + document.getElementById("test").value;
EDIT
To send form data via POST, you may need to add some header information.
xhr.open('POST', 'testing.php', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(data);
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
// change your function
function sendString()
{
var data = "data="+document.getElementById("test").value;
var xhr= new XMLHttpRequest();
xhr.open('POST', 'testing.php', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(data);
}
In testing.php you can call them via $_POST:
echo $_POST['data'];
Example here: http://www.openjs.com/scripts/examples/ajax_using_post.php

Categories