I am trying to save json data to a file using AJAX and PHP but the resulting file is empty. Why is it not working?
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
var dataset = {"value1": 2, "value2": 1000};
$.ajax({
url: 'save.php',
type: 'POST',
data: dataset,
success: function() {
alert('Success');
}
});
</script>
</body>
</html>
save.php:
<?php
$map=json_decode($_POST['json_string']);
$file = "test.json";
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, $map);
fclose($fh);
?>
You're using wrong POST variable name. Firstly, send your AJAX request with:
data: {
json: dataset
},
And then use:
$map = $_POST['json'];
Don't decode it since you want to save JSON string, not an array. If you want PHP representation, better use var_export():
$map = var_export(json_decode($_POST['json'], true), true);
change this line $map=json_decode($_POST['json_string']); to $map=json_decode($_POST['dataset']);
Related
I Want to get a file name from recursive AJAX, but until now its doesnt work, in my code was like this
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>GET NAME</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="/assets/mediaelements/build/jquery.js"></script>
<script src="/assets/mediaelements/build/mediaelement-and-player.min.js"></script>
<link href="/assets/mediaelements/build/mediaelementplayer.min.css" rel="stylesheet" />
<script type="text/javascript" src="jquery.min.js"></script>
<script>
(function rekurse(){
setTimeout(function()
{
/* ---------------------------------- */
$.ajax({
type: "POST",
cache: false,
url: 'shift.php',
data: {offi: 'E:/DataText/OFFICE/BI/FAR1'},
success: function(data){
alert(data);
rekurse();
},
error: function(){
alert(data);
rekurse(); // recurse, if you'd like.
}
});
/* ---------------------------------- */
}, 1000);
})();
</script>
</head>
<body onload="rekurse();return false;">
</body>
<html><body
and on shift.php, its just like
<?PHP
//
CLEARSTATCACHE();
//
$grps = '_';
$offi = $_POST['offi'];
$temp = $offi.'/'.$grps.'*.*';
$arrs = GLOB( $temp );
$coun = COUNT( $arrs );
//
IF($coun<1):
ECHO json_encode("ok");
ENDIF;
//
$text = $offi."/call.htm";
$hand = FOPEN( $text, 'w' );
$text = FWRITE( $hand,"\r\n");
$hand = FCLOSE( $hand );
//
$file = $arrs[0];
$hand = FOPEN( $file, 'r' );
$temp = FREAD( $hand, FILESIZE( $file ) );
$hand = FCLOSE( $hand );
//
$arrs = EXPLODE(',',$temp);
IF( COUNT($arrs)>0 ):
ECHO json_encode($temp);
ELSE:
ECHO json_encode("ok");
ENDIF;
//
?>
What im missed this and sorry about my english
Thank You
Regard
Bambang
Recursive AJAX is a bed idea.
you just check code of your php file and make sure it work's properly then after you call ajax function to get a file name.
First call your php file manually and check the output.
just use code like below don't make it complex..
$.ajax({
type: "POST",
cache: false,
url: 'shift.php',
data: {offi: 'E:/DataText/OFFICE/BI/FAR1'},
success: function(data){
alert(data);
},
error: function(){
alert(data);
}
});
I have a folder with images in it and I am trying to load the images from this file onto the webpage. I know the images are in correct format and the dir are all correct. The images are just not appearing on the page. This is my html file.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
url: "loadImages.php",
dataType: "json",
alert("This is working");
success: function(data) {
$.each(data, function(i, filename) {
$('#imgs').prepend('<img src="' + filename + '"><br>');
});
}
});
});
</script>
<html>
<body>
<div id="imgs">
</div>
</body>
</html>
This is my php file.
<?php
$filenameArray = [".png"];
$handle = opendir(dirname(realpath(__FILE__)).'/images/');
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
array_push($filenameArray, "/images/$file");
}
}
echo json_encode($filenameArray);
?>
All I need is the images to be shown on the page.
You don't appear to be concatenating your variables correctly
array_push($filenameArray, "/images/$file");
Needs to be:
array_push($filenameArray, "/images/".$file.");
If you're still having issues, could you post your json?
Testing downloading data from remote Db using Phonegap Android and JSONP
Works perfectly in Browser (with php file on remote host and index both from localhost on my local machine and when on remote host) and in Ripple but zero data displaying when ported to Android via Phonegap..just the 'Details' text is displaying..no error..
My code :
**INDEX.html**
<!DOCTYPE html>
<html>
<head>
<title>json</title>
<script src="phonegap3.1.0.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/
1.6.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
var output = $('#output');
$.ajax({
url: 'http://mydomain.com.com/landmarks1.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var contact = '<p>'+item.name+'</p>'
+ '<p>'+item.address+'</p><hr>';
$("#mylbl").append(contact);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
</script>
</head>
<body>
<div>
Details
<span id="mylbl"></span>
</div>
</body>
</html>
**landmarks1.php**
<?php
header('Content-type: application/json');
mysql_connect("localhost","m560847_sean","1994martha");
mysql_select_db("m560847_contacts");
$result = mysql_query("SELECT * FROM contact");
$records = array();
echo mysql_error();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
I've given access to remote domain in my xml file
<access origin="http://127.0.0.1*" />
<access origin="http://mydomain.com.com*" />
<access origin=".*"/>
I've looked at many many similar issues on here and in general on web and am stumped..
The issue is that either the PHP file isn't sending the data back or the JS file isn't catching the data.
The exact issue is that the data isn't display on the index.php page inside the <div>.
I included code in the getDetails.php file to record what it was doing. It allows me to see that the query is running and data is being returned.
I have used similar code to this in the past without any problems. The only difference is that the previous code was working with MySQL. This code is dealing with an Access database. I don't know if I need to do anything special with the json_encode to deal with Access data.
I used an alert() at the beginning of java.js to make sure that the java code is being called. It is. An alert right after the details = result command never gets called.
INDEX.PHP:
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="java.js" type="text/javascript"></script>
</head>
<body>
<div id="reportDetails" class="reportDetails" align=center></div>
</body>
<html>
JAVA.JS:
jQuery(document).ready(function () {
var ra='7100913063';
$.ajax({
type: 'POST',
url: 'getDetails.php',
data: 'value=' + ra,
dataType: 'json',
cache: false,
success: function(result) {
details = result;
$("#reportDetails").text("");
for (var i = 0; i < details.length; i++) {
$("#reportDetails").append("<tr class='bottom'><td width=200 align=center class='bottom'>" + details[i][0] + "</td><td width=200 align=center class='bottom'>" + details[i][1] + "</td><td width=200 align=center class='bottom'> " + details[i][2] +"</td></td><td width=200 align=center class='bottom'> " + details[i][3] +"</td></td></tr>");
}
$("#reportDetails").append("</table>");
},
});
});
getDetails.php
<?php
include("../../scripts/adodb/adodb.inc.php");
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$ra = $_POST['value'];
set_time_limit(0);
date_default_timezone_set('America/Chicago');
$counter = 0;
$connect = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=//server/directory/database.mdb", '', '');
$query = "SELECT distinct ra, MIN(received) as startDate, MAX(completion) AS stopDate, MAX(status) as stat FROM cont WHERE ra = '" . $ra . "' GROUP BY ra";
$result = odbc_exec($connect,$query);
while(odbc_fetch_row($result)){
$radetails[0] = odbc_result($result,"ra");
fwrite($fh, $radetails[0]);
$radetails[1] = odbc_result($result,"startDate");
fwrite($fh, $radetails[1]);
$radetails[2] = odbc_result($result,"stopDate");
fwrite($fh, $radetails[2]);
$radetails[3] = odbc_result($result,"stat");
fwrite($fh, $radetails[3]);
}
fclose($fh);
echo json_encode($radetails);
?>
I had the line "echo <br/>" in my getDetails.php. Removed that line and it works now.
If I embed my XHR file into my HTML document directly, everything works fine. As soon as I src it via
<script type="text/javascript" src="js/ajax_gallery.js">ajax_json_gallery('gallery');</script>
Nothing works, and I get no errors. I'm assuming it's something to do with the XHR being created in a separate file to the HTML. I just don't like XHR script cluttering up my HTML, I just want to load as an external JS file.
I've moved my main 3 scripts, galleryHandle.php, XHR.js, ajax_gallery.html all to the same dir level to keep things simple. And the gallery images are in a folder called "gallery", also on the same level.
Here's my code:
HTML
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="css/gallery.css" />
</head>
<body>
<div id="pagetop"></div>
<div id="thumbnailbox"></div>
<div id="pictureframe"></div>
<script type="text/javascript" src="XHR.js">ajax_json_gallery('gallery');</script>
</body>
</html>
JavaScript
function ajax_json_gallery(folder) {
"use strict";
var httpRequest = new XMLHttpRequest();
document.getElementById("pagetop").innerHTML = "dynamic ajax json gallery";
var thumbnailbox = document.getElementById("thumbnailbox");
httpRequest.open("POST", "galleryHandle.php", true);
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4 && httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText);
var pictureframe;
pictureframe.innerHTML = "<img src='"+data.img1.src+"'>";
thumbnailbox.innerHTML = "";
for (var obj in data) {
if (data[obj].src){
thumbnailbox.innerHTML += '<div onclick="putinframe(\''+data[obj].src+'\')"><img src="'+data[obj].src+'"></div>';
}
}
}
};
httpRequest.send("folder="+folder);
thumbnailbox.innerHTML = "Loading...";
}
function putinframe(src) {
"use strict";
var pictureframe = document.getElementById("pictureframe");
pictureframe.innerHTML = '<img src = " '+src+' " >';
}
PHP
<?php
header("Content-Type: application/json");
//bring in folder name
$folder = $_POST["folder"];
//start componding json
$jsonData = '{';
//compound directory path
$dir = $folder."/";
//open directory
$dirHandle = opendir($dir);
//init while looop
$i = 0;
while ($file = readdir($dirHandle)) {
if(!is_dir($file) && strpos($file, '.jpg')){
$i++;
$src = "$dir$file";
$jsonData .= '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$file.'" },';
}
}
closedir($dirHandle);
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
?>
I understand there are some redundancies in my code but it's just a tutorial I'm going through to learn the basics of JSON building with POST, XHR.
Anyway, help appreciated as always.
Thanks
Explanation
FROM W3C:
<script type="text/javascript" src="myscript.js">
alert('I am pointless as I won\'t be executed');
</script>
Upon meeting this element in a page, browsers will then load the file myscript.js and execute it. Any content inside the script element itself will be skipped when you provide a src attribute. The [last] example will load the file myscript.js and execute the code in it but will not execute the alert inside the script element at all.
Solution
Try the following in your head tags:
HTML
<script type="text/javascript" src="XHR.js"></script>
<script type="text/javascript">
ajax_json_gallery('gallery');
</script>
<script type="text/javascript" src="XHR.js">
You can't have src attribute and javascript both in a single tag. Separate them out. Like this...
<script type="text/javascript" src="XHR.js"></script>
<script type="text/javascript">ajax_json_gallery('gallery');</script>