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);
}
});
Related
This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 5 months ago.
so, this is really hard to phrase, but I'm trying to use jQuery to move the file of an input element to a php file to put it into a message.
here's the code
HTML:
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg"/>
<input name="userimg" type="file" id="userimg" accept="image/*"/>
<input name="submitmsg" type="submit" id="submitmsg" value="Send"/>
</form>
jQuery:
$(document).ready(function () {
$("#submitmsg").click(function () {
var clientmsg = $("#usermsg").val();
var clientimg = $("#userimg").val();
$.post("post.php", { text: clientmsg, img: clientimg });
$("#usermsg").val("");
return false;
});
//other stuff here
});
PHP:
$text = $_POST['text'];
$img = $_POST['img'];
$text_message = "<div class='msgln'><span class='chat-time'>".date("m-d, g:i A")."</span> <b class='user-name'>".$_SESSION['name']."</b> ".stripslashes(htmlspecialchars(preg_replace('/\pM/u', '', $text)))."<br><br>".$img."</div><!--". $_SESSION['ipAddr'] ."-->
";
file_put_contents('log.html', $text_message, FILE_APPEND | LOCK_EX);
If I add no file, it posts the message as usual (username and text), but if I add a file it says C:\fakepath\[file name and extension] note: fakepath is not a filler -- that's actually what it returns.
Please replace your js code and check again.
$(document).ready(function () {
$("#submitmsg").click(function (e) {
e.preventDefault();
var myFormData = new FormData();
myFormData.append('text',$('#usermsg').val());
myFormData.append('img',$('#userimg').get(0).files[0]); // Here's the important bit
$.ajax({
url: 'post.php',
type: 'POST',
data: myFormData,
dataType: 'json',
mimeType: 'multipart/form-data', // this too
contentType: false,
cache: false,
processData: false,
success: function(data){
$("#usermsg").val("");
return false;
},
error: function(error){
console.log(error);
}
});
});
});
php code:
$text = isset($_POST['text']) ? $_POST['text'] : '';
$img = $_FILES['img']['name'];
$target_file = basename($_FILES["img"]["name"]);
$name = isset($_SESSION['name']) ? $_SESSION['name'] : '';
// upload image in your root folder
if(move_uploaded_file($_FILES["img"]["tmp_name"], $target_file)) {
}
$text_message = "<div class='msgln'><span class='chat-time'>".date("m-d, g:i A")."</span> <p><b class='user-name'>".$name."</b></p> ".stripslashes(htmlspecialchars(preg_replace('/\pM/u', '', $text)))."<br><br><img src='".$img."' alt=''></div>";
// if you want to previous file delete.
if(file_exists('log.html')){
unlink('log.html');
}
file_put_contents('log.html', $text_message, FILE_APPEND | LOCK_EX);
echo $img;
I have a following HTML and Javascript code:
<script type="text/javascript">
$(function() {
$('#form_1 input').on('change', function() {
val = $('input:radio[name=graf]:checked').val();
$.ajax({
type: 'POST',
data: ({graf_id: val}),
url: 'rrd_image.php',
success: function(data) {
$('#div_1 img').attr('src', data);
}
});
});
});
</script>
<div id="div_1">
<form id="form_1">
<input type="radio" name="graf" value="1">Daily
<input type="radio" name="graf" value="2">Weekly
<input type="radio" name="graf" value="3">Monthly
</form>
<img src="default.png">
</div>
And the rrd_image.php:
$graf_id = $_REQUEST['graf_id'];
$tmpfile = "/tmp/rrd.png";
// rrd_graph options...
rrd_graph($tmpfile, $options);
header( "Content-Type: image/png" );
header( "Content-Length: " . filesize( $tmpfile ) );
$fp = fopen( $tmpfile, 'rb' );
if( $fp ) { fpassthru( $fp ); }
fclose( $fp );
exit();
The rrd_graph.php itself is working, but when i click one radio-button, the HTML page
do not reload the right PHP generated rrd image.
The problem is your PHP file is returning an image, not a URL. What I would do is pass your graf value, along with a time string, in the query string and then tell JS to load that image instead
$(function() {
$('#form_1 input').on('change', function() {
var val = $('input:radio[name=graf]:checked').val();
var time = new Date().getTime();
$('#div_1 img').attr('src', 'rrd_image.php?graf_id=' + val + '&time=' + time);
});
});
You don't need AJAX anymore because the time parameter will always be different and thus your browser won't cache it.
I have problem with showing current inserted rows into mysql with query.
Now I have this code in index.php:
$('#nacitatATC').click(function() {
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener("progress", function(e){
var p = (e.loaded / e.total)*100;
var prave = $("#progress").html();
$("#progress").html(prave+"<br>"+p);
});
return xhr;
}
, type: 'post'
, cache: false
, url: "/sql.php"});
});
});
and in sql.php I have the php code with inserting data into mysql with for().
$i is the current inserting line and $pocet is total lines.
The problem is with show current inserting line with ajax.
The code above shows in div #progress "100" when ajax finish loading.
I need show 1% 2% 3% 4%... 99% 100% Completed.
Thanks for help!
I think php -> flush() is what you are looking for.
This Example works perfect on my php-apache on debian
see ajax-request-progress-percentage-log
PHP side:
header( 'Content-type: text/html; charset=utf-8' );
echo 'Begin ...<br />';
for( $i = 0 ; $i < 10 ; $i++ )
{
echo $i . '<br />';
flush();
ob_flush();
sleep(1);
}
echo 'End ...<br />';
site:& javascript:
<!doctype html>
<html>
<head>
<title>Test Flush</title>
<meta charset="utf-8">
<script src="./js/jquery-2.0.3.min.js" type="text/javascript"></script>
<body>
<h1>Hello</h1>
<div id="progress">0%</div>
<p>
</p>
<script type="text/javascript">
$('h1').click(function() {
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener("progress", function(e){
console.log(e.currentTarget.response);
$("#progress").html(e.currentTarget.response);
});
return xhr;
}
, type: 'post'
, cache: false
, url: "testFlush.php"
});
});
</script>
</body>
Also have a look at Rogers Answer in
how-to-flush-output-after-each-echo-call
He found issues in the apache setup
I have problem with logging visit duration.
I wrote test html file like this:
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript" type="text/javascript">
function enter() {
this.chrono = new Date().getMilliseconds();
alert("test");
}
function leave() {
this.chrono = new Date().getMilliseconds() - this.chrono;
var myAjax = new Ajax.Request('visitor_log/ajax_store_visit_duration.php?visit_duration=' + this.chrono.toString(),{
method: 'get',
onComplete:handlerFunction
});
return null;
}
window.onload = enter;
window.onbeforeunload = leave;
</script>
</body>
</html>
PHP file (visitor_log/ajax_store_visit_duration.php):
<?php
if(isset($_GET["visit_duration"]))
{
$text = $_GET["visit_duration"];
log($text);
}
else die("error");
function log($text)
{
$myFile = "test.txt";
$fh = fopen($myFile, 'wb');
fwrite($fh, $text);
fclose($fh);
}
?>
When I type in browser:
http://localhost/visitor_log/ajax_store_visit_duration.php?visit_duration=123
it creates text file as I want, but it seems that AJAX call in onbeforeunload event is not working.
Whats wrong with my code?
Edit:
I created test function to find problem with AJAX call.
function testajax(){
this.chrono = new Date().getMilliseconds() - this.chrono;
var blockingRequest = new XMLHttpRequest();
blockingRequest.open("GET", "visitor_log/ajax_store_visit_duration.php?visit_duration=" + 123, false); // async = false
blockingRequest.send();
return null;
}
window.onload = testajax;
</script>
</body>
This is not working too.
Ok, so purposefully NOT using jQuery:
here's the PHP:
<?php
function loggit($text) {
$myFile = "/tmp/test.txt";
$fh = fopen($myFile, 'wb');
fwrite($fh, $text);
fclose($fh);
}
if(isset($_GET["visit_duration"])) {
$text = $_GET["visit_duration"];
loggit($text);
}
else die("error");
?>
here's the HTML:
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript" type="text/javascript">
function enter() {
this.chrono = new Date().getMilliseconds();
}
function leave() {
this.chrono = new Date().getMilliseconds() - this.chrono;
alert("test" + this.chrono);
var blockingRequest = new XMLHttpRequest();
blockingRequest.open("GET", "http://localhost/_TempFiles/temp.php?visit_duration=" + this.chrono.toString(), false); // async = false
blockingRequest.send();
return null;
}
window.onload = enter;
window.onbeforeunload = leave;
</script>
</body>
</html>
you want to use an async request (see the false sent to blockingrequest.open) - but beware this is a BLOCKING request (hence the name).
Also I changed the name of the php function from "log" to "loggit" log is the php natural logarithm function...
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']);