I need to pass a huge set of data with jquery ajax - image data. In which I can't use the usual way of uploading. Because the image data is from a canvas - literalycanvas. I've tried sent it but it's not get through. The data sample as follow: (pink is image data which is a lot longer than this and yellow is a truncate warning)
Well, I need to pass this data along the jquery ajax. So
Is there any possibility to do?
Can I write it to a cookie instead?
Can I pass it through the session?
Here's my code :
$.ajax({
url: 'print.php',
type: 'POST',
data: {
// convert the image data to base64
filename:'<?=$_GET[file]?>',//photo/2015-03-09/img_00215.jpg
image: lc.canvasForExport().toDataURL().split(',')[1],
type: 'base64'
},
success: function(data) {
$('.export_btn').html("<div class=\"alert alert-success\"><i class=\"fa fa-check\"></i> Printed</div>");
},
error: function() {
$('.export_btn').html("<div class=\"alert alert-danger\"><i class=\"fa fa-warning\"></i> Print error!</div>");
}
});
return false;
});
As you can see, the image: is sending a long line of data. Which is needs to send along the data. Any idea I can send this?
Related
I have this code which makes a binary image from a normal image and displays it into an .img
$host=$_POST['hostname'];
$type=$_POST['type_char'];
include('rrdtools.inc.php');
include('graphs/'.$type.'.inc.php');
function graph_error($string,$rrd_options)
{
$graphfile ='/tmp/'. strgen().'.png';
$rrd_options .= ' HRULE:0#555555';
$rrd_options .= " --title='".$string."'";
rrdtool_graph($graphfile, $rrd_options);
header('Content-type: image/png');
$fd = fopen($graphfile, 'r');
fpassthru($fd);
fclose($fd);
unlink($graphfile);
}
graph_error($type,$rrd_options);
I send the hostname,type_char to the file using ajax and this is the code
$('.print_graph').click(function(e) {
e.preventDefault();
var type_char='fortigate_sessions';//$('#graph').val();
var hostname='10.10.0.144';//$(this).attr('id');
//$('#device_host').val(id);
$.ajax({
type: 'POST',
url: 'SNMP/graph.php',
data: {'hostname':hostname,'type_char':type_char },
success: function(data) {
alert(data);
// show the response
$("#grph").attr("src", 'SNMP/graph.php');
console.log(data);
}
});
as you can see in the javascript code I used this code to display image
$("#grph").attr("src", 'SNMP/graph.php');
and this code will call graph.php again without parameters and the result is wrong
how can I pass parameters to graphs.php .
I wish I explained my problem clearly
You can solve this by making graph.php look for GET parameters instead of POST and then setting the image source directly without using AJAX:
Change
$host=$_POST['hostname'];
$type=$_POST['type_char'];
to
$host=$_GET['hostname'];
$type=$_Get['type_char'];
and also change
$.ajax({
type: 'POST',
url: 'SNMP/graph.php',
data: {'hostname':hostname,'type_char':type_char },
success: function(data) {
alert(data);
// show the response
$("#grph").attr("src", 'SNMP/graph.php');
console.log(data);
}
});
to simply
$("#grph").attr("src", 'SNMP/graph.php?hostname='+hostname+'&type_char='+type_char);
This will mean that the image data returned by graph.php is used directly in the img tag instead of ending up in a JavaScript variable.
P.S. I note you are using the $type variable to directly create an include() statement in PHP. This is potentially very insecure, as you're letting the client have very direct control over what code is executed and this could be abused to execute code which shouldn't be executed at this time. You should make sure the value submitted contains a value you are expecting and is allowed before using it in your include() statement.
In my project, there is a URL that normally responses an image with Content-Type:image/png that drawn by Java dynamically with user's data.
But sometime causes some reason, the user should not see the image or the image cannot be drawn with user's data. In this case, server will response JSON result that contains error info with
Content-Type:application/json; charset=utf-8
Is this possible to show the image while server response Content-Type:image/png otherwise to alert error info while Server response Content-Type:application/json; charset=utf-8?
I can handle either of the response content type, but struggling with handling both of two content type in one request. is this possible?
EDIT
I tried using AJAX like
<img id="preview-img"/>
$.ajax({
url: "/preview",
type: "GET",
dataType: "JSON",
success: function(data) {
if (!data.success) {
alert(data.msg);
}
},
error: function() {
alert("occur error");
}
});
With above code, alert(data.msg) is available when Server response a JSON result with error message, but alert("occur error") will triggered when Server response correct Image.
And I retried with remove dataType:
$.ajax({
url: "/preview",
type: "GET",
success: function(data) {
if (!data.success) {
alert(data.msg);
}
},
error: function() {
alert("occur error");
}
});
Glad to see the success function is triggered whether Server response Image or JSON
But I don't know how to display Image with response data that looks like
ÿØÿàJFIFÿÛC
$.' ",#(7),01444'9=82<.342ÿÛC
2!!22222222222222222222222222222222222222222222222222ÿÀ%a"ÿÄ
ÿĵ}!1AQa"q2¡#B±ÁRÑð$3br
%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚáâãäåæçèéêñòóôõö÷øùúÿÄ
ÿĵw!1AQaq"2B¡±Á #3RðbrÑ
$4á%ñ&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚâãäåæçèéêòóôõö÷øùúÿÚ?÷ú(¢
......
A bunch of garbage.
And now I temporarily not to handle JSON result
<img id="preview-img"/>
var image = new Image();
image.onload = function () {
$("#preview-img").attr("src", "/preview");
};
image.onerror = function() {
alert("could not load image");
};
image.src = "/preview";
The request fails with "dataType" set because JQuery tries to parse the response as JSON, but fails to do so if the server responded with an image. Therefore the error-callback is called.
The preferred solution, in my opinion, would be to set an HTTP code != 200 (e.g. 404 for not found) in case the image couldn't be served by the server. The error-callback would be called in that case and you can show an error-dialog the user. Otherwise you can proceed with displaying the image in the success-callback.
Regarding "I don't know how to display Image with response data that looks like" look here: Using jQuery's ajax method to retrieve images as a blob
I am developing a theme in wordpress and i am not being able to set a background-image in spite of getting a successful ajax response.
I am requesting an image url that is being successfully given in the json response except that i am not being able to set the image as a background image.
I am using the following ajax function:
function Pat_Req(pat_val){
$.ajax({
type: 'POST',
dataType: 'json',
url: BAC_PAT_OBN.ajaxurl,
data: {
'action' : 'BAC_PAT_Ajax',
'nonce' : BAC_PAT_OBN.nonce,
'rpat' : parseInt(pat_val)
},
complete: function( object ) {
$('#pat_bac').css('background-image',object.responseJSON.response_pat)
}
});
}
"pat_val" is an integer that i am getting from an input of type number.
I tested to see if "pat_val" is actually storing an integer from the input and it does store an integer.
When the input values changes to say, 5, "pat_val" stores 5.
The Pat_Req function is triggered every time there is a change in the input value. the following jquery code is doing it:
$('#The_pats input').on('change',function(){
Pat_Req($(this).val())
})
"BAC_PAT_OBN" is the javascript object i am using.
"object.responseJSON.res_pat" is also giving me a valid image url. The only problem is that Pat_Req complete function is not setting the background.
Thank you for your time and answer,
MMK.
If you showed the Ajax response, it would be easier to answer. My guess is you are not returning url() surrounding the image path.
$('#pat_bac').css('background-image', "url(" + object.responseJSON.response_pat + ")");
I have a situation,I need to add lot of text to server (via ajax & php).Each is happeening by clicking on a add button.In order to reduce round trip.I am planning to give a save all button so once I store everything in client side and I can save all together to database via ajax so only one round trip.
I have 6 input fields and needs to save this info everytime
My planning
Store everything in a JavaScript hidden variable and itreate this in php side and save it.
I will have to store lot of text in hiden field.Is my approach correct ? any better way ?
You dont need to store it on hidden fields, just make a JSON object containing the data you want and then send it to the server throught ajax.
You can create the JSON object this way:
var jsonObject = {'name': $('#name').val(), 'city': $('#city').val()};
And then you send it to PHP throught AJAX:
$.ajax({
type: 'POST',
url: 'some.php',
data: jsonObject,
dataType: 'json'
}).done(function() {
alert('success');
}).fail(function() {
alert('error');
}).always(function() {
alert('complete');
});
I need to send image data (data:image/png;base64) from the clientside using AJAX to my PHP server. My AJAX call looks like this:(form_data contains the image)
$.ajax({
url: global_siteurl+'/save_image',
data: form_data,
dataType: 'json',
type: 'post',
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (retval) {
process_save_image(retval);
}
});
Then I store the encoded image data as a blob in the database (yes - long story behind that!). When I retrieve the image data it seems to be corrupted and does not display correctly. Almost as if there are line breaks and spaces introduced into the image data. Am I missing any parameters in my ajax call? Any ideas as to what may be going wrong? Is there a size limit for the image data I can send across?
It's been a long 4 days of chasing this one.
Mmiz
The problem turned out to be the same described (and solved) in this posting:
Blob data replace '+' with space
Turns out I needed to make the blob data safe for URLs when I GET/POST it. On the PHP server side I used the function described in the above posting. On the Javascript side, I used the functions from:
http://notepad2.blogspot.com/2012/08/javascript-make-base64-encoded-string.html
Took a lot of staring at the encoded image data to notice that the +/= were replaced.
Try this when showing image.
echo '<img src="data:image/png;base64,' . base64_encode($blob_data) . '"/>