How can i select text in javascript Ajax - javascript

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);

Related

how to create radio buttons by JS.

i have some problrm creating the radio buttons dynamically. in my problem i am requesting data from server in json formate than i check if it contains options i have to create the radio buttons otherwise simply creates the txt area of field to submit the answer. than again i parse it in json formate and send to the server and if my question is write i get new url for next question and so on...
my question is how can i create the radio buttons and read the data from it and than parse that data like {"answer": "something"}.my code is bellow:
enter code herefunction loadDoc(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
var data = JSON.parse(this.responseText);
document.getElementById("my_test").innerHTML = data.question;
// Send the answer to next URL
if(data.alternatives !== null){
createRadioElement(div,);
}
var answerJSON = JSON.stringify({"answer":"2"});
sendAnswer(data.nextURL, answerJSON)
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function sendAnswer(url, data) {
xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(this.responseText);
console.log(this.responseText);
loadDoc(data.nextURL);
}
}
// var data = JSON.stringify({"email":"hey#mail.com","password":"101010"});
xhr.send(data);
}
function createRadioElement(name, checked) {
var radioHtml = '<input type = "radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
var radioFragment = document.createElement('div');
radioFragment.innerHTML = radioHtml;
return radioFragment.firstChild;
}
I'm only guessing since you have some things in your posted code that won't even run, but createRadioElement returns a detached node which you never actually inject into your document.
E.g.,
document.body.appendChild(createRadioElement());

How to get link specific php varaible to pass through ajax

I dont know much about ajax or jquery yet but i currently have an ajax script that does successfully send A variable through and does work properly.
--the way i have it set up is like this for my loop:
<?php
$tt= mysql_query("SELECT * FROM monsters");
while ($row= mysql_fetch_array($tt))
{
$namee= $row['name'];
echo "<a id='namee' onclick='post();'>$namee</a>", "</br>";
}
which echos:
horseman
dragon
---the results do make a list of all the names from the table as shown above and they are clickable which is working great
my ajax request is this:
<script type="text/javascript">
function post(){
var hr = new XMLHttpRequest();
var url = "mess.php";
var vars =document.getElementById("namee").innerHTML;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("new").innerHTML = return_data;
}
}
hr.send(vars); // Actually execute the request
alert(vars);
}
</script>
the alert when i click on horseman returns "horseman"
but when i click on dragon it still alerts "horseman"
i would like to get the specific variable ( when i click horseman it says horseman and when i click dragon it says dragon etc) so i can send it through ajax to update a database ( which i already know to to set up)
please help me and show me if you can full code so i can learn and see how it works and understand your response since im new like i said :)
thanks in advance:
if have any questions feel free to ask
Thats because ids should be unique, jquery will get only the first element with that id, my suggestion is to pass the value by parameter:
echo "<a class='namee' onclick='post($namee);'>$namee</a>", "</br>";
And then the js:
function post(vars) {
var hr = new XMLHttpRequest();
var url = "mess.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("new").innerHTML = return_data;
}
}
hr.send(vars); // Actually execute the request
alert(vars);
}

Posting plain text on php using JavaScript

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'];

JavaScript: reading $_POST & $_FILES variables after AJAX submission

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

Append HTML doc to element using ajax

I've written this code using various online sources but I cannot seem to figure out the last part.
function loadajax (event) {
event.preventDefault();
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200)
document.ajax.dyn="Received:" + xhr.responseText;
else
document.ajax.dyn="Error code " + xhr.status;
}
};
xhr.open('GET', this.href, true);
var content = document.getElementsByTagName('article')[0];
content.innerHTML = xhr.responseText;
}
It seems to work until I need to add content to my page. Indeed content.innerHTML = xhr.responseText; returns nothing. I am getting a simple HTML file, how can I post it in my page? what am I doing wrong?
Thanks for your help!
ajax calls are asynchronous. it will work if you'll move the content.innerHTML = xhr.responseText; line into the onreadystatechange function like this:
function loadajax (event) {
event.preventDefault();
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
document.ajax.dyn="Received:" + xhr.responseText;
content.innerHTML = xhr.responseText;
else
document.ajax.dyn="Error code " + xhr.status;
}
};
xhr.open('GET', this.href, true);
var content = document.getElementsByTagName('article')[0];
}
Put your contet.innerHTML inside status 200 condition.
You are just assigning the value to content before it really exists. Before the ajax got it from server.

Categories

Resources