How to get data from PHP in JSON and AJAX? - javascript

Hey guys I am fetching some data with PHP with is listing the folders and Inside the folders I have some images. But I am willing to know how can I get that data in JSON with AJAX to get the name of folders in a DropDown.
This is the code that I am using
JS
<html>
<head>
<script type="text/javascript">
function getXmlHttp(){
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function readDir(dirName) {
var req = getXmlHttp();
var list = document.getElementById('subDir');
req.onreadystatechange = function() {
if (req.readyState == 4) {
if(req.status == 200) {
list.innerHTML = req.responseText;
}
}
}
req.open('GET', 'getList.php?data=' + dirName, true);
req.send(null);
list.innerHTML = 'loading...';
}
</script>
</head>
<body onload="readDir('');">
<div id="subDir">
</div>
</body>
</html>
PHP
<?php
$dir = "./data/";
if (strlen($_GET['data']) > 0){$dir = $_GET['data'];}
getList($dir);
function getList($name) {
$path = realpath($name);
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CATCH_GET_CHILD);
foreach($objects as $name => $object){
if (filetype($name) == "dir") {
print "<br/><a href='javascript:void' onClick='readDir(\"" . $path . "/" . basename($name) . "\")'><b>" . basename($name) . "</b></a>";
} else {
print "<br/><a><b>" . basename($name) . "</b></a>";
}
}
}
?>
Here you can see the code how is working: http://tdhdemo.com/phpfetch/

I'm not sure I get your question right but you can add your list to an array in PHP and display it using json_encode.
When receiving data from the ajax call, use JSON.parse to make it easily readable.
You can also separate files and folders if you want to use them in the future.
<?php
$dir = "./data/";
if (strlen($_GET['data']) > 0){$dir = $_GET['data'];}
echo json_encode(getList($dir));
function getList($name) {
$path = realpath($name);
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CATCH_GET_CHILD);
$folderContent = array("directories" => array(), "files" => array());
foreach($objects as $name => $object){
if (filetype($name) == "dir") {
array_push($folderContent["directories"], basename($name));
} else {
array_push($folderContent["files"], basename($name));
}
}
return $folderContent;
}
?>
Javascript :
function readDir(dirName) {
var req = getXmlHttp();
var list = document.getElementById('subDir');
req.onreadystatechange = function() {
if (req.readyState == 4) {
if(req.status == 200) {
contentList = JSON.parse(req.responseText);
for(i in contentList["directories"]){
list.innerHTML = list.innerHTML + contentList["directories"][i];
}
}
}
}
req.open('GET', 'getList.php?data=' + dirName, true);
req.send(null);
list.innerHTML = 'loading...';
}

Related

Json decode from Javascript to php to Javascript

I am trying to get the value from json.stringfy sent to PHP file, for some reason php file is not receiving the key. If I manually add the key it is working fine. What could be wrong here:
My php file:
$request = json_decode(file_get_contents('php://input'), true);
$getID = $request['docid'];
$query = mysqli_query($con, "SELECT * FROM user_details WHERE id = $getID'");
if(mysqli_num_rows($query) > 0)
{
$response["details"] = array();
while ($row = mysqli_fetch_array ($query))
{
// temp user array
$detail = array();
$detail["docname"] = $row["docname"];
$detail["textresults"] = $row["textresults"];
array_push($response["details"], $detail);
}
echo json_encode($response);
$response["success"] = 1;
}
else
{
$response["success"] = 0;
echo json_encode($response);
}
This is my javascript file:
function loadData() {
var docid = window.localStorage.getItem('myKey');
console.log("Docid " + docid);
var xhr = new XMLHttpRequest();
var url = "./api/getData.php";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json);
}
};
var data = JSON.stringify({'docid': docid});
xhr.send(data);
}

How can Variable and that value move freely in the cycle of PHP->HTML->JS->PHP

I am adding the comments input box of every XML-RSS article.
When I select a RSS url, that results are commonly as below
PHP code
for ($i=0; $i<=19; $i++) {
$item_title=$x->item($i)->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$item_link=$x->item($i)->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$item_desc=$x->item($i)->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
$item_date=$x->item($i)->getElementsByTagName('pubDate')
->item(0)->childNodes->item(0)->nodeValue;
echo ("<p><a href='" . $item_link
. "' target=\'_blank\'>" . $item_title . "</a>");
echo ("<br>");
echo ($item_desc . "<br>".$item_date."</p>");
$item_link1 = str_replace('http://','',$item_link);
$item_link2 = str_replace('https://','',$item_link1);
$item_link3 = str_replace('/','-',$item_link2);
$item_link4 = str_replace('?','-',$item_link3);
$content = $item_title."--". $item_link."--".$item_desc."--".$item_date;
file_put_contents("./comments/".$item_link4.".txt",$content);
//Next line is something wrong or not??
echo "<option id=".$item_link4." onclick=\"showComment(this.value)\" value=".$item_link4."> Show Comments </option> <div id=\"".$item_link."\"></div>";
Next, I can see the results as a below picture.
And I am coding JS which has the showComment function as below.
function showComment(str) {
if (str.length == 0) {
document.getElementById(""+item_link4+"").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(""+item_link4+"").innerHTML = this.responseText;
}
};
var q = document.getElementById(""+item_link4+"").value;
xmlhttp.open("GET", "showComment.php?q=" + q, true);
xmlhttp.send();
}
}
And Next, I am coding the showComment.php as below to see the 'q' value.
But,
Notice: Undefined index: q in E:\xampp\htdocs\code\v1\showComment.php on line 5.
The first part is like next.
// line 5 is $q = html...
$q = htmlspecialchars($_GET['q']);
global $result;
echo $q;
Eventually, I got something wrong in JS code which received item_link4
How do I change the JS variable originated from php-HTML code?
Please your Kindness.
I have tried so many times. At last I got the good result for going to the better.
PHP code is
echo " <option id=".$i." onclick=\"showComment".$i."(this.value)\" value=".$item_link4."> Show Comments </option>";
And I changed JS code as below.
<script>
function showComment0(str) {
if (str.length == 0) {
document.getElementById("0").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("0").innerHTML = this.responseText;
}
};
var q = document.getElementById("0").value;
xmlhttp.open("GET", "showComment.php?q=" +q, true);
xmlhttp.send();
}
}
</script>
....
<script>
function showComment22(str) {
if (str.length == 0) {
document.getElementById("22").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("22").innerHTML = this.responseText;
}
};
var q = document.getElementById("22").value;
xmlhttp.open("GET", "showComment.php?q=" +q, true);
xmlhttp.send();
}
}
</script>
<script>
function showComment23(str) {
if (str.length == 0) {
document.getElementById("23").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("23").innerHTML = this.responseText;
}
};
var q = document.getElementById("23").value;
xmlhttp.open("GET", "showComment.php?q=" +q, true);
xmlhttp.send();
}
}
</script>
So I made Id 0 to 18 script. That is, 19 scripts are necessary.
I am waiting for better answer.

Can't upload large files using XHR and FormData

I have created simple script using XMLHttpRequest. It sends text and (optionally) file. It works but problem is that large files (above 50MB) are not accepted. I thought that problem was with PHP's upload_max_filesize or post_max_size but it doesn't (I set it up 512MB). I don't know what to do now... Any ideas?
function publishPost() {
if (!event) { event = window.event; }
event.preventDefault();
var data = new FormData();
data.append('SelectedFile', document.querySelector('#post input').files[0]);
var x = new XMLHttpRequest();
x.open('POST', 'upload.php', true);
x.setRequestHeader('TEXT', post.innerHTML);
x.onload = function() {
if (x.readyState == XMLHttpRequest.DONE) {
if (x.responseText == '1') {
location.reload();
} else {
alert('Error: ' + x.responseText);
}
}
}
x.send(data);
}
And PHP:
$text = strip_tags($_SERVER['HTTP_TEXT']);
$file = $_FILES['SelectedFile']['name'];
$info = pathinfo($file);
$uniqid = uniqid();
if (!empty($file)) {
$newfile = '../files/'.$uniqid.'.'.$info['extension'];
if (move_uploaded_file($_FILES['SelectedFile']['tmp_name'], $newfile)) {
$file = $uniqid.'.'.$info['extension'];
}
}
// Adding to Database
My error is Undefined index: SelectedFile

How can I properly make AJAX POST request

I need some help. I can't make POST request with javascript.. I don't want to use jQuery in a first place. I don't know why my $_POST is empty..
This is my scores.php file.
<?php
$method = $_SERVER['REQUEST_METHOD'];
$file = __DIR__ . '/scores.json';
$scores = file_get_contents($file);
if ($method === 'GET') {
echo $scores;
} else if ($method === 'POST') {
$scores = json_decode($scores, TRUE);
$scores[] = [
'name' => $_POST['name'],
'scores' => (int) $_POST['scores'],
];
usort($scores, function($a, $b) {
$scoresA = $a['scores'];
$scoresB = $b['scores'];
if ($scoresA === $scoresB) {
return 0;
}
return $scoresA < $scoresB ? 1 : -1;
});
$scores = json_encode($scores);
file_put_contents($file, $scores);
echo $scores;
} else {
echo 'Method not allowed.';
}
And this is some of my code in frogGame.js file:
function setScores(){
let xhttp = new XMLHttpRequest();
xhttp.open("POST", "scores.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("name=Henry&scores=2542");
}
setScores();
You should use this:
function setScores(){
let xhttp = new XMLHttpRequest();
xhttp.open("POST", "scores.php?name=Henry&scores=2542", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
}
setScores();

Unable to pass value to php POST via javascript

I am trying to update the text from textbox to database using the onclick event and calling a javascript function.
This is the javascript code
function send_post()
{
var hr = new XMLHttpRequest();
var url ="send_post.php";
var fn = document.getElementById("post").value;
var vars = "post="+fn;
hr.open("POST",url,true);
hr.setRequestHeader("Content-type","application/x-www-form-urlencode");
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status ==200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("status").innerHTML = fn;
}
This is the php file code
<?php include 'inc/connect.inc.php';
$post =#$_POST['post'];
if ($post != "") {
$date_added = date("Y-m-d");
$added_by = "test123";
$user_posted_to = "test123";
$sqlCommand = "INSERT INTO posts VALUES('','$post','$date_added','$added_by','$user_posted_to')";
$query = mysql_query($sqlCommand) or die (mysql_error());
}
else{
echo "Write something to post.";
}
?>
But I get this error from the php :
Undefined index: post on line 3
The MIME type you are trying to use is application/x-www-form-urlencoded (with a d on the end).
PHP doesn't know how to parse data encoded as application/x-www-form-urlencode (without the d) so it doesn't populate $_POST for your code.
Javascript part:
<script>
function getXMLObject(){
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e2) {
xmlHttp = false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}
var xmlhttp = new getXMLObject();
function send_post() {
if(xmlhttp) {
var post = document.getElementById("post").value;
xmlhttp.open("POST","send_post.php",true);
xmlhttp.onreadystatechange = resultPost;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("post=" + post);
}
}
function resultPost() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
}
</script>
PHP part:
<?php
include 'inc/connect.inc.php';
if(isset($_POST['post']) && trim($_POST['post']) != '') $post = mysql_real_escape_string(trim($_POST['post']));
else $post = '';
if ($post != '') {
$date_added = date("Y-m-d");
$added_by = "test123";
$user_posted_to = "test123";
$sqlCommand = "INSERT INTO posts VALUES('','$post','$date_added','$added_by','$user_posted_to')";
$query = mysql_query($sqlCommand);
if(mysql_affected_rows($link) == 1){
echo 'Operation successfully executed';
exit;
}
}
echo 'Write something to post.';
?>

Categories

Resources