I'm submitting a form through AJAX for the express purpose of displaying a pre-selected image. Selecting an image from the local drive will trigger the "onchange" event for the file-type input, and in turn call the AJAX routine. It works fine, and upon a successful "move_uploaded_file", the PHP handler returns the validated file name. The following illustrates how the AJAX submission was effected:
var xhr = new XMLHttpRequest();
var xForm = new FormData(document.forms.namedItem("form"));
xhr.open("POST", "handler.php", true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
document.getElementById("imgDiv").src = xhr.responseText;
}
}
xhr.send(xForm);
Instead of getting the handler to return the file name, is there any way to access the $_POST and $_FILES variables after returning from an AJAX submission? This is usually possible when returning from a normal form post, using:
<?php echo $_POST['stringInput'];?>
<?php echo $_FILES['imageInput']['fileName'];?>
but I'm not able to get anything in this case.
Thanking you,
Sofia
EDIT: in case it may be relevant, the handler is not in the same HTML script, but in a separate PHP file. Thanks again!
Because you made a mistake in code typing here:-
Old code
x.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
document.getElementById("imgDiv").src = xhr.responseText;
}
}
New code
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
document.getElementById("imgDiv").src = xhr.responseText;
}
}
Means replace x.onreadystatechange with xhr.onreadystatechange
Related
I am not able to select text which i retrieve from directoryScanner.php file into the div container. So what ever gets displayed in div container , i cannot select it by mouse.
<div id="file_link_panel">
</div>
Following javascript code
function dirRefresher(){
ajax = new XMLHttpRequest();
ajax.open("POST","directoryScanner.php");
ajax.onreadystatechange = function(){
if(ajax.readyState ==4 & ajax.status == 200){
msg = this.responseText;
document.getElementById("file_link_panel").innerHTML = msg;
}
}
ajax.send();
}
setInterval(dirRefresher,1000);
And this simple php script named directoryScanner.php
<?php
echo "kunal";
echo "pankaj";
echo "shekhar";
?>
The problem is you are making tons of Ajax calls and updating the element over and over again so as you try to make the selection, it is being replaced. You are better off increasing the timeout and only firing the next one after you get the call back from the server. Also there is no need to replace the html, if the content is the same.
function dirRefresher(){
var ajax = new XMLHttpRequest();
ajax.open("POST","directoryScanner.php");
ajax.onreadystatechange = function(){
if(ajax.readyState ==4 & ajax.status == 200){
var msg = this.responseText;
var elem = document.getElementById("file_link_panel");
if(elem.innerHTML !== msg) {
elem.innerHTML = msg;
}
setTimeout(dirRefresher, 5000);
}
}
ajax.send();
}
dirRefresher()
If you need quicker updates, you should be looking into webSockets, not Ajax.
Try using innerText besides innerHTML:
You return from php just text so you need to include innerText. Like so:
function dirRefresher(){
ajax = new XMLHttpRequest();
ajax.open("POST","directoryScanner.php");
ajax.onreadystatechange = function(){
if(ajax.readyState ==4 & ajax.status == 200){
msg = this.responseText;
document.getElementById("file_link_panel").innerText= msg;
}
}
ajax.send();
}
setInterval(dirRefresher,1000);
I have a js file, containing a folder myFunc(phone_number)
Now when this js function is called, I want to make a POST request to the URI https://pay.something.in:443/FetchPhone/ passing the json {'phone_number' : 10 digit phone no. } as input to the request
and show its output in a new window.
Can somebody tell me how do I do that?
Seems to me like you want to make a POST request with xhr.
var xhr = new XMLHttpRequest();
xhr.open('POST', "https://pay.something.in:443")
xhr.setRequestHeader("Content-type", "application/json");
xhr.send( '{"phone_number" : 4455566677 }' );
xhr.onreadystatechange = function(){
if (xhr.readyState != 4) return;
if (xhr.status != 200 && xhr.status != 304) {
alert('HTTP error ' + req.status);
return;
}
console.log(xhr.responseText);//this is your response
window.sessionStorage['response'] = xhr.responseText;
window.open('Your window');//The data is accessible through sessionStorage.
}
I need to use "POST" consisting of value and a variable structure using JavaScript. The plain text should be sent to a PHP page where it will be displayed. How should I get about this?
From what I understand according to my requirement. It needs to be something like a FROM submission, but run only using JavaScript.
document.body.innerHTML += '<form id="content" action="http://10.10.10.10/index.php" method="post"><input type="hidden" name="info" value="'+plainText+'"></form>';
document.getElementById("content").submit();
I tried this code as well.Do you have an Idea on how to display the text sent here on a PHP page?
var request = new XMLHttpRequest();
request.open("POST", "10.10.10.10/index.php", true);
request.onreadystatechange = function () {
if(request.readyState === 4){
if(request.status === 200 || request.status == 0){
request.setRequestHeader("Content-type","text/plain;charset=UTF-8");
request.setRequestHeader("Content-length", plainText.length);
request.send(plainText);
}
}
}
request.send(null);
You need to use ajax, if you need plain javascript then you should do something like this:
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
var DONE = this.DONE || 4;
if (this.readyState === DONE){
alert(xhr.responseText);
}
};
request.open('POST', 'script.php', true);
request.send("<YOUR TEXT>");
if you use jQuery then simple:
$.post('script.php', '<YOUR TEXT>', function(response) { });
and then you can read it in php using:
file_get_contents('php://input');
or (deprecated):
$GLOBALS['HTTP_RAW_POST_DATA'];
I am creating an AJAX+PHP submit form, for example purposes. For this, I will need Ajax, PHP and index.html file to write into the inputs. The problem is that, when I submit I have no way of redirecting a page, so I created this hack. (since page redirect get permission from the PHP script first) otherwise show error.
AJAX
function submit_form(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
if(xmlhttp.responseText.trim() == 'success'){
location.href = '/success';
}
//
var e = doc.querySelector('.form-error').innerHTML = xmlhttp.responseText;
}
}
And this is my PHP.
<?php
echo "/success";
if($_GET){
}else{
echo "error, no value found";
}
as you can see, this allows me to redirect the page, as the javascript will read the "/success" and redirect the document, but one problem with this is that, I don't like using echo, because the page actually shows "success" before redirect. I don't want it to show anything to the page.
Change your echo statement to return json_encode(), then in your JS code, you can parse it using JSON.parse();
In your PHP removes the slash of this line: echo "/success";
And in your java script code, add a else sentence before print error:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
if(xmlhttp.responseText.trim() == 'success') {
location.href = '/success';
}
else {
var e = doc.querySelector('.form-error').innerHTML = xmlhttp.responseText;
}
}
}
I'm trying to send parametres from a .php file to my Javascript but I can't even manage to send a String.
Javascript fragment:
var params = "action=getAlbums";
var request = new XMLHttpRequest();
request.open("POST", PHP CODE URL, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.send(params);
request.onreadystatechange = function() {
var phpmessage = request.responseText;
alert(phpmessage);
};
PHP fragment:
$deviceFunction = $_POST["action"];
if ($deviceFunction == "") $deviceFunction = $_GET["action"];
// Go to a function depending the action required
switch ($deviceFunction)
{
case "getAlbums":
getAlbumsFromDB();
break;
}
function getAlbumsFromDB()
{
echo "test message!";
}
The alert containing phpmessage pops up but it's empty (it actually appears twice). If I do this the alert won't even work:
request.onreadystatechange = function() {
if(request.status == 200) {
var phpmessage = request.responseText;
alert(phpmessage);
}
};
The readystatenchange event will be called each time the state changes. There are 5 states, see here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#readyState
Rewrite your JS:
request.onreadystatechange = function () {
if (request.readyState == 4) {
console.log('AJAX finished, got ' + request.status + ' status code');
console.log('Response text is: ' + request.responseText);
}
}
In your code, you only check for the returned status code. The code above will check for the ready state and then output the status code for debbuging.
I know that this answer is more a comment than an answer to the actual question, but I felt writing an answer in order to include nicely formatted code.
I faced a similar problem working with Django. What I did:
I used a template language to generate the javascript variables I needed.
I'm not a PHP programmer but I'm going to give you the idea, let me now if works. The following isn't php code, is just for ilustrate.
<?php
<script type="text/javascript" ... >
SOME_VARIABLE = "{0}".format(php_function()) // php_function resolve the value you need
</script>
?>
The I use SOME_VARIABLE in my scripts.
Please specify your onreadystatechange event handler before calling open and send methods.
You also should make your choice between GET and POST method for your request.
If you want to popup your message only when your request object status is OK (=200) and readyState is finished whith the response ready (=4), you can write :
request.onreadystatechange = function() {
if (request.readyState==4 && request.status==200) {
var phpMessage = request.responseText;
alert(phpMessage);
}
};