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.
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 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'm going off of Dropzone.js resources provided by: http://www.dropzonejs.com/
What I'm trying to do - After uploading the image(s) and filling out all inputs, to get the link for each image that was uploaded in this session, to be passed into an AJAX request URL as a POST type.
My HTML:
<div id="myForm">
<input type="text" id="form-name" placeholder="Name">
<input type="text" id="form-email" placeholder="Email">
<form action="/upload-target" class="dropzone" id="myDropZone"></form>
<button id="submit-info">submit</button>
</div>
My JS:
<script>
$("div#myDropzone").dropzone({ url: "/upload.php" },
function() {
console.log("Hello");
});
</script>
The images are uploaded to a directory mentioned in the PHP code below, but I have a problem with the above script, where the output in the console doesn't even print. Hello doesn't show in the console when anything is uploaded.
My upload.php:
<?php
$ds = DIRECTORY_SEPARATOR;
$storeFolder = 'img/uploads';
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
}
?>
Just to explain the above code, once an image(s) is
selected/drag-and-dorpped, upload.php uploads the images to
http://example.com/img/uploads/ folder.
Here's where I need help:
I am trying for when clicking the button with id submit-info, passing each image I've just uploaded as a string to the AJAX request:
<script>
$('#submit-info').click(function() {
var str = "name=" + $('#form-name').val()
+ "&email=" + $('#form-email').val()
+ "&images=" + /* what to put here */;
console.log(str);
$.ajax({
type: "post",
url: "sendEmail.php",
data: str,
dataType: "json",
success: function (confirmation) {
// some code here dealing with after the email is sent like hiding the form
}
});
});
</script>
Here's one way to do it:
var files = '';
if (Dropzone.forElement("#my-dropzone").files.length > 0) {
for (var i = 0; i<Dropzone.forElement("#my-dropzone").files.length; i++) {
if (i === (Dropzone.forElement("#my-dropzone").files.length - 1) ) {
files += Dropzone.forElement("#my-dropzone").files[i].name;
}
else {
files += Dropzone.forElement("#my-dropzone").files[i].name + '~';
}
}
}
The above code should be placed inside of the $('#submit-info').click(function() { ... so that once the submit button is clicked, we set an empty string, check if there are any files that were uploaded, and concatenate them if they exist.
For this example, the files are being separated by ~ characters. So once the string is passed through, you can declare your str variable like so:
$('#submit-info').click(function() {
var str = "name=" + $('#form-name').val()
+ "&email=" + $('#form-email').val()
+ "&images=" + files;
My jQuery Ajax code is:
<div class="page_rank">
<form name="searchForm" id="searchForm" method="post">
<span class="my_up_text">ENTER THE WEBSITE TO CHECK GOOGLE PAGE RANK:</span>
<br /><br />
<input type="text" name="my_site"/></div><div class="p_ity"><input type="submit" class="btn" value="PAGE RANK" /> </form></div><div id="my_pass"></div>
<script>
function sub_form()
{
document.forms["searchForm"].submit();
}
$(function () {
$('form#searchForm').on('submit', function(e) {
$( ".p_ity" ).hide();
$.ajax({
type: 'post',
url: 'check-google-page-rank.php',
data: $('form').serialize(),
success: function (data) {
$('#my_pass').html(data);
}
});
e.preventDefault();
});
});
</script>
My php code is:
<?php
header('Content-type: image/jpeg');
require('./get_page_rank.php');
$url=$_POST['my_site'];
//echo $url;
$pr = new PR();
//$rank= $pr->get_google_pagerank($url);
$rank=$pr->get_google_pagerank($url);
// Create Image From Existing File
$jpg_image = imagecreatefromjpeg('./images/page-rank/G.jpg');
if($jpg_image)
{
// Allocate A Color For The Text
$white = imagecolorallocate($jpg_image, 0, 0, 0);
// Set Path to Font File
$font_path = './images/page-rank/Helvetica.TTF';
// Set Text to Be Printed On Image
$text = $rank;
// Print Text On Image
imagettftext($jpg_image, 85, 0, 305, 100, $white, $font_path, $text);
// Send Image to Browser
imagejpeg($jpg_image,NULL,100);
// Clear Memory
imagedestroy($jpg_image);
}
?>
It works perfectly if I execute the PHP separately with manual input so I think the problem is with jQuery html() function. I am sure the image is not corrupted and I am using utf-8 encoding and I also tried base64_encode(imagejpeg()) but got the same output.
OUTPUT:
��*����D\�#��梸�����[[h� ��0 s��('�y\�ӎ+��_�P 7��){�i�i��ĽOH�
_��:�� VV���y�x���o~�Eh��R��U�1�C����|�~,�ѿ
��7c��|S�����W�:�g��� ����K�z��A��D .͓�<�n��F� d�Qƹ̸{%�*֣�2�q7c�9UJ�0s��w�ߞ>ҥX��UaQG��w�bq8��
imagejpeg() outputs the image to browser directly, so the response is not the html content you could use with .html(), you don't have to use ajax in this case, the url should be used as the src of an image tag.
You could do like below:
$(function () {
$('form#searchForm').on('submit', function(e) {
$( ".p_ity" ).hide();
$('<img />').attr('src', 'check-google-page-rank.php?my_site='+ encodeURIComponent($('[name= "my_site"]').val())).load(function() {
$(this).appendTo('#my_pass');
});
e.preventDefault();
});
});
And change $url=$_POST['my_site']; to $url=$_GET['my_site'];.
In your php handler, write your image in a file;
$imgFolderPAth = "/path/to/img/";
imagejpeg($jpg_image,$imgFolderPAth . "image.jpg",100);
echo $imgFolderPAth . "image.jpg";
and in your js;
$.ajax({
type: 'post',
url: 'check-google-page-rank.php',
data: $('form').serialize(),
success: function (data) {
$('#my_pass').html('<img src="' + data + '"/>');
}
});
Or alternatively you can use;
imagejpeg($jpg_image,NULL,100);
$rawImageBytes = ob_get_clean();
echo "<img src='data:image/jpeg;base64," . base64_encode( $rawImageBytes ) . "' />";
and in your js, you can use as it is
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