How to call element.onload inside AJAX sucess function? - javascript

I am uploading a image using AJAX in php codeignitor and on upload return a JSON response containing path of uploaded image, then i insert that path into a img tag for preview
Now what i want to do is get the height and width of rendered img tag after updating its path, but the problem is i am getting a 0 always so please somebody help me out here
here is my JS
function uploadAd(){
// console.log($('#uploadedPDF').prop('files'));
var file_data = $('#uploadedAdFile').prop('files')[0];
var form_data = new FormData();
form_data.append('uploadedAdFile', file_data);
// alert(form_data);
$.ajax({
url: BASE_URL+'home/uploadAdFile', // point to server-side PHP script
dataType: 'json', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
async: false,
success: function(data){
console.log(data);
if(data.status == -1){
// If file extension Validation failed
$('#uploadedAdFileMsg').html(data.msg);
$('#uploadedAdFileMsg').removeClass('hidden');
$('#uploadedAdFilePreview').addClass('hidden');
}
else{
// If file extension Validation passed
$('#uploadedAdFilePreview').attr('src', data.path); // Render file in img tag
$('#uploadedAdFileMsg').addClass('hidden');
$('#uploadedAdFilePreview').removeClass('hidden');
console.log(document.getElementById('uploadedAdFilePreview').naturalWidth);
// console.log()
}
},
complete: function(){
console.log('Complte '+document.getElementById('uploadedAdFilePreview').naturalWidth);
}
}).done(function(){
console.log('Done '+document.getElementById('uploadedAdFilePreview').naturalWidth);
});
}
$(document).ajaxComplete(function(){
console.log('AJAX '+document.getElementById('uploadedAdFilePreview').naturalWidth);
})
as you can see I inserted get height code in various places but no luck
PS: I used clientHeight, height, naturalHeight as well but still got 0
so what I concluded is the height function is called before the img tag rendered its content hence it shows a 0
so can I include a onload type of function inside a AJAX success function ??
thanks

I Solved it :D ,
actually i was using onload on a Jquery returned object which is wrong , it should be used on document.getElement , so then i put a
element.onload = function(){ getHeight(); }
inside my success function os AJAX, and it worked :)

Related

How to read dynamic url from JSON file?

I have a .json file (see below) with image URL containing variables like the path and the project name.
{"imgs":[
{
"gatewayImg": "resrcPath+_global_PROJECT_NAME+'/images/gateway-'+_global_PROJECT_NAME+'.png'"
}
]}
I also have my ajax request loading the file and on my request success I assign the attribute src and the source path to the image.
$.ajax({
async: false,
type: "GET",
global: false,
dataType: "json",
url: resrcPath+"imgRes.json",
success: function (data) {
var src = data.imgs[0].gatewayImg;
$('.gatewayImg').attr('src', src);
}
});
The problem is that when the I do this, the image isn't found on the local server and I get this localhost:8080/order/resrcPath+_global_PROJECT_NAME+'/images/gateway-'+_global_PROJECT_NAME+'.png' as the src.
But when I attribute the src as followed: $('.gatewayImg').attr('src', resrcPath+_global_PROJECT_NAME+'/images/gateway-'+_global_PROJECT_NAME+'.png'); the image shows up and the variables are well replaced by their correct value.
I don't know if my JSON is valid or not that way, and I need to know how to assign the src with the json value instead of writing the URL in the attribute function.
Your JSON is valid, but you have a string that needs to be executed (evaluated). If you have 100% control over the JSON file, you can eval the string, that assumes you have resrcPath,_global_PROJECT_NAME as globals.
var resrcPath = "/";
var _global_PROJECT_NAME = "global"
eval("resrcPath+_global_PROJECT_NAME+'/images/gateway-'+_global_PROJECT_NAME+'.png'")
=== "/global/images/gateway-global.png"
$.ajax({
async: false,
type: "GET",
global: false,
dataType: "json",
url: resrcPath+"imgRes.json",
success: function (data) {
var src = data.imgs[0].gatewayImg;
$('.gatewayImg').attr('src', eval(src));
}
});
The best solution would be to process the string on the server so you don't need to evaluate it again on the client and open holes in your program.

Sending blob data via ajax

So I'm trying to send an image via ajax as a blob. The blob has the correct type and is about 4.5 kb in size. I try to send it like this:
document.getElementById("canvas").toBlob(function (blob) {
var data = new FormData();
data.append('name', name);
data.append('program', YouTomaton.Main.get_CurrentProgram());
data.append('image', blob);
$.ajax({
type: "Post",
url: "save.php",
data: data,
processData: false,
contentType: false,
success: function (result) {
if(result != undefined && result.length > 0)
alert(result);
}
});
});
The recieving page looks like this:
<?php
include("session.php");
writeProgram($_POST['name'], $_POST['program'], $_POST['image']);
?>
It tells me that the index 'image' could not be found. So not only does the data not get sent, but even the index is omitted. What am I doing wrong ?
EDIT: neither toBlob nor toDataURL produce anything but an empty PNG. Is there a way to convert the data from a framebuffer into a base64 encoded jpg or png ?
Read this. Then think of what you would like to do.
If you could use a plugin for jQuery. I would recommend using FileUpload
For an HTML file input, minimal syntax would be like this:
<input type="file" name="fs" id="fileupload" />
And JS script:
$('#fileupload').fileupload({
url: "fileupload?additional=data",
done: function (e, data) {
console.log(data.result);
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
I'm working on a similar problem right now - I'm using PDF's - here's my working ajax call:
$.ajax({
dataType: "native",
url: ("handle.php?filename=" + event.target.dataset.name),
xhrFields: { responseType: "blob" },
data: "secure=<?php echo $pass ?>",
success: function(result){
console.log(result.size)
download(result, event.target.dataset.name, "application/pdf")
}
})
The download() part is a call to the FileSaver tool - which is how the Blob gets saved on the client side in my case...
I'm using data-name attr in the markup to store JUST the filename (not full path) - hope that helps!
EDIT:: Sorry for the PHP mixed in! - that statement just passes a hashed nonce token to the script to make sure no requests have been duplicated/gotton out of order - etc...

Show downloaded html inside of string

Im trying to create kind of a user interface with a downloaded html-string and an iframe. What my 'Submitta' ActionResult does is returning a html-page as a JSON string. And then I try to append it to an iframe so I can record and save clicks. See code below:
$.ajax({
url: '/Home/Submitta/',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(paket),
success: function (data) {
var iframe = document.getElementById('frame');
var html = data.Url;
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
renderat = true;
$('#frame').on('load', function () {
console.log("load");
var iframeDoc = document.getElementById('frame').contentWindow;
$(iframeDoc).mouseover(function (event) {
}).click(function (event) {
console.log($(event.target.valueOf()));
});
});
},
error: function (data) {
}
})
Which I am having problem with rendering due to a browser error:
Uncaught SecurityError: Blocked a frame with origin "http://localhost:xxxx" from accessing a frame with origin "null". The frame requesting access has a protocol of "http", the frame being accessed has a protocol of "data". Protocols must match.
Am I going at this project the wrong way? Is it not possible to work with iframes in this way?
For the record does this JQuery click function work when the iframe is directly rendered from a local .html file. But not when it has html appended to it.
Think of an iFrame like a window into another tab on your browser... opening a page within a page. What you're doing, is trying to transmit the data via json, generate the page on the client-side, and then put that page in the iframe... if that's the case, then you could just eliminate the iframte all together and put your generated HTML into a div or something using jQuery.
$.ajax({
url: '/Home/Submitta/',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(paket),
success: function (data) {
// take "data" and do what you gotta do to
// get it into HTML...
var resulthtml = "";
// put that HTML generated above into
// your results div like this:
$("#resultsdiv").html(resulthtml);
},
error: function (err) {
$("#resultsdiv").html("Something went wrong.");
}
});

Javascript get current page html (after editing)

I have a page that I have edited after load and what I want to do is get the pages current HTML and pass that off to a PHP script.
I first passed document.documentElement.innerHTML but that ended up including a bunch of computed style garbage at the top which I did not want. After googling around I found I could use ajax to get a copy of the current file on the server and then replace the edited part afterwards.
I can get the copy of the file using this:
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
$.ajax({
url: filename,
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
origPage = data; // can be a global variable too...
// process the content...
}
});
Which works fine and gets me the html I expected and see when viewing the page in notepad.
The next step is what I cannot figure out. All I want to do is swap out the innerHTML of a div with an id of 'editor' with what the current value is, so I have tried this:
origPage.getElementById('editor').innerHTML = e.html;
But I get the error "TypeError: undefined is not a function". I must be doing something simple wrong I feel but I don't know the proper formatting to do this. I have tried the following variations:
alert($(origPage).getElementById('editor').innerHTML);
//Different attempt
var newHtml = $.parseHTML( origPage );
alert($(newHtml).getElementById('editor').innerHTML);
//Different attempt
alert($(origPage).html().getElementById('editor').innerHTML);
But I always get "TypeError: undefined is not a function" or "TypeError: Cannot read property 'getElementById' of undefined". How can I do this properly?
EDIT:
Complete page html below:
<!DOCTYPE html>
<html>
<body>
<div id="editor">
<h1>This is editable.</h1>
<p>Click me to start editing.</p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="snapeditor.js"></script>
<script type="text/javascript">
var editor = new SnapEditor.InPlace("editor", {onSave: function (e) {
var isSuccess = true;
//var origPage = e.html;
var origPage;
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
// Actually perform the save and update isSuccess.
// Javascript:
$.ajax({
url: filename,
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
origPage = data; // can be a global variable too...
// process the content...
}
});
//origPage shows expected html as this point
//alert($(origPage).getElementById('editor').innerHTML);
//alert($(origPage).html().getElementById('editor').innerHTML);
$(origPage).getElementById('editor').innerHTML = e.html;//fails here
alert(origPage);
//alert(newHtml.getElementById('editor').innerHTML);
$.ajax({
data: {html: origPage, docName: 'example1.html'},
url: 'savePage.php',
method: 'POST', // or GET
success: function(msg) {
alert(msg);
isSuccess = true;
}
});
return isSuccess || "Error";
},
onUnsavedChanges: function (e) {
if(confirm("Save changes?")) {
if(e.api.execAction("save")){
//location.reload();
}
} else {
e.api.execAction("discard");
}
}});
</script>
</body>
</html>
It seems that you get the user's changes in a variable - you called the var e.html. That is not a good variable name, BTW. If you can, change it to something like htmlEdited
Question: If you add the command alert(e.html); what do you get? Do you see the HTML after user edits?
If yes, then what you need to do is send that variable to a PHP file, which will receive the data and stick it into the database.
Code to send the data:
javascript/jQuery:
alert(e.html); //you should see the user-edited HTML
$.ajax({
type: 'post',
url: 'another_php_file.php',
data: 'userStuff=' + e.html, //var_name = var_contents
success: function(d){
window.location.href = ''; //redisplay this page
}
});
another_php_file.php:
<?php
$user_edits = $_POST['userStuff']; //note exact same name as data statement above
mysql_query("UPDATE `your_table_name` SET `your_col_name` = '$user_edits' ") or die(mysql_error());
echo 'All donarino';
The AJAX javascript code will send the var contents to a PHP file called another_php_file.php.
The data is received as $user_edits, and then inserted into your MySQL db
Finally, I presume that if you redisplay that page it will once again grab the contents of the #editor div from the database?
This is where you haven't provided enough information, and why I wanted to see all your code.
ARE you populating that div from the database? If not, then how do you expect the page to be updated after refreshing the page?
You would benefit from doing some tutorials at phpacademy.org or a thenewboston.com. Do these two (free) courses and you'll be an expert:
https://phpacademy.org/videos/php-and-mysql-with-mysqli
https://phpacademy.org/videos/oop-loginregister-system
If all you need to do is insert the contents of e.html to replace the #editor div, then try this:
$('#editor').html(e.html);
HOWEVER, you need an event to trigger that code. Are you able to do this?
alert(e.html);
If so, then put the first bit of code at that same spot. If not, we need more information about when your code receives that variable -- that is where you put the $('#editor').html(e.html); statement.

load view using ajax symfony2

I'm very new to symfony2 and I'm getting some problems to load a view using ajax when the user clicks on a div. Using firebug I can see the data is returned but I can not append the result in the page.
My Code:
//Default Controller
public function indexAction($num, Request $request)
{
$request = $this->getRequest();
if($request->isXmlHttpRequest()){
$content = $this->forward('PaginationBundle:Default:ajax');
$res = new Response($content);
return $res;
}
return $this->render('PaginationBundle:Default:index.html.twig', array('num' => $num));
}
public function ajaxAction()
{
return $this->render('PaginationBundle:Default:page.html.twig');
}
}
My Js:
When clicking on #target, I'd like to load page.html.twig in my div
$("div#target").click(function(event){
t = t +1;
$.ajax({
type: "POST",
cache: "false",
dataType: "html",
success: function(){
$("div#box").append(data);
}
});
});
I'm using isXmlHttpRequest() in my controller to detect if it's an ajax request to load ajaxAction. I get that view on firebug but it's not appended in my div#box. div#box exists in index.html.twig
Thanks everybody in advance
In your
$("div#target").click(function(event) event you didn't specify the url parameter in ajax call, and another thing is you must specify an argument inside the 'success'
parameter of ajax call.
$("div#target").click(function(event){
t = t +1;
$.ajax({
type: "POST",
url: "{{path('yourpath-means header name in routing.yml')}}",
cache: "false",
dataType: "html",
success: function(result){
$("div#box").append(result);
}
});
});
Hope this helps...
Happy coding
This has nothing to do with symfony but with your ajax options. Pece is right though: You can use the return from §this->forward directly as it is a Response object.
The problem lies within your ajax options. You must pass the data object within your inner function or data is simply null. Try this:
success: function(data){
$("div#box").append(data);
}
I don't get your forward to treat AJAX call. Try this :
if($request->isXmlHttpRequest()){
return $this->forward('PaginationBundle:Default:ajax');
}
Controller::forward() already returns a Response object ;)

Categories

Resources