How to parse string html from submitted iframe - javascript

I'm uploading a file in an iframe (with name and id=upload_target) to some server. As a response it creates a callback json style :
'result':'true'
So I'm trying the following. On onload action of my IFrame I've added an event listener, which should run function grabbing data :
function fileUploadFunction(){
(...)
$("#upload_target").onload = uploadDone;
(...)
};
function uploadDone() {
alert("uploadDone");
var ret = frames['upload_target'].document.getElementsByTagName("body")[0].innerHTML;
var data = eval("("+ret+")");
if(data.result == 'true') {
alert("GREAT SUCCESS !!");
}
else {
alert("GREAT FAILURE :(");
}
}
But as a result I'm not getting anything at all. Should I return callback status in different form, or can it be solved differently ? Because even the first alert from uploadDone is not shown problem probably lies somewhere else.

Probably the reason nothing is happening is because of the funky way you have to detect an iFrame is loaded. Check the post jQuery .ready in a dynamically inserted iframe. I am assuming you are using jQuery.

Related

how to adjust margin session flash in php?

I am trying to flash a success message when data store successfully. My database code and every other thing working fine but when I give $_SESSION success message it always come under navigation.
1) I want to know is there any way in php to set margin of $_SESSION['success_flash'] message
2) is there any way like /n/n type so that my flash message will show two line below
3)
My real code is:
$_SESSION['success_flash'] = '\n\n<span style="color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>';
I tried /n/n but not working:
$_SESSION['success_flash'] = '\n\n<span style="color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>';
I tried style="margin-top:200px;" but not working:
$_SESSION['success_flash'] = '<span style="margin-top:200px;color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>';
Kindly check the image below only green background is showing under the navigation bar and the text message "Data saved successfully!" not showing because it is hidden under the navigation.
One more thing I am using below code after the flash message and my code end.
echo "<script type='text/javascript'> document.location = 'index.php'; </script>";
Any idea or suggestion would be helpful.
Thanks you.
I am getting data and passing the data to database successfully. I just want to reload my page after php call and show sucess flash to the user.
My Ajax Call: top my php page.
<script>
function createD () {
var data = {
'name' : jQuery('#name').val(),
'phone' : jQuery('#phone').val(),
};
//Ajax call Start Here
jQuery.ajax({
url : '/mycodpage/includes/codfile/product.php',
method : 'POST',
data : data,
success : function(data){
if (data != 'passed') {
// This will show error
jQuery('#modal_errors_1').html(data);
}
if (data == 'passed') {
//clear the errors if any
jQuery('#modal_errors_1').html("");
location.reload();
}
},
error : function (){alert("Something went wrong.");},
}); //Ajax call End Here
}
} // Function End
</script>
PHP once loaded it does not change on the page, it is not dynamic. The way you do this is rather weird, but can be acomplished if you will set $_SESSION['success_flash'] just right after saving the data in the database, and reaload the page.
In my opinion the best way is to use ajax here, and the ajax response can change the container under the menu to "success".
But I don't know how do you send your data, is it by POST form or something?
Add display:inline-block; or display:block; in the styles of the span.
As long as dom elements behaviour can depend on outer dom objects (and you do not specify them): if it still does not work try using padding instead of margin, if it still does not work place two span tags one inside other both with inline-block.
All that stuff using $_SESSION is kinda weird, however XD... but from your description I assume that it shows already the span, but without the margin... but you should not use $_SESSION in that way.
OK, now we are getting somewhere. But now location.reload is unnecessary, because if you will receive 'passed' answer, you can set the communicate without reloading (and without using any code in session variable, get rid of $_SESSION['success_flash']), like below.
Please note that I do not know what is the CSS class or ID of your green DIV (if any), so for this specific example I will assume, that it has a class ".msg-response"
<script>
function createD () {
var data = {
'name' : jQuery('#name').val(),
'phone' : jQuery('#phone').val(),
};
//Ajax call Start Here
jQuery.ajax({
url : '/mycodpage/includes/codfile/product.php',
method : 'POST',
data : data,
success : function(data){
if (data != 'passed') {
// This will show error
jQuery('#modal_errors_1').html(data);
}
if (data == 'passed') {
//clear the errors if any
jQuery('#modal_errors_1').html("");
// this new line will change the content of your message div
$('div.msg-response').html('<span style="margin-top:200px;color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>');
}
},
error : function (){alert("Something went wrong.");},
}); //Ajax call End Here
}
} // Function End
</script>
there is also a security risk here: "if (data != 'passed')" - you will echo PHP errors (path, filename, variables, class, code row etc.) when something unpredictionary will happen, unless you will turn display_errors off on your server (display errors should be enabled only in development mode, that's a good practice).
To avoid it you can use JSON response here, handle the "error" status, "success" status, and do nothing if JSON response is different from "success" or "error".

"Function Expected" error in JsProvider.ashx after setting a lookup field

I have an HTML page that gets opened when clicking a ribbon button of a custom entity page. The JS code running in this page is does some business logic, and eventually needs to update a lookup field back on the custom entity page.
Currently, for setting the lookup value, I'm doing something like the following*:
window.opener.Xrm.Page.getAttribute("ik_reportid").setValue([{
id: "d67aa9d8-c528-e711-80f2-005056b74923",
name: "test record",
entityType: "ik_report"
}]);
*Note: The above is written hard-coded for simplifying this question. I assure you the problem is not in these values, but somewhere else.
After doing so, the HTML page continues with its existing code, and eventually calls window.opener.Page.data.refresh(true), and then closes itself with window.close().
The problem is that when the opener page is refreshing, I get an error "function expected", and opening the debugger get me to the following line in JsProvider.ashx:
Mscrm.FormInputControl.LookupUIBehavior.$2I=function($p0,$p1){if(!parseInt($p0.type)&&!parseInt($p1.type)||parseInt($p0.category)===LookupItemCategories.UNKNOWN_EMAIL&&parseInt($p1.category)===LookupItemCategories.UNKNOWN_EMAIL)
I watched the values of p0 and p1, and I noticed they don't have a category property. However, when I tried using the same code for setting the value of the same lookup field when I'm on the page itself (i.e., omitting the window.opener', and even calling arefresh`), I get no error.
In addition, I commented-out the refresh call inside the HTML page code. That didn't help, too: when I clicked the save button on the entity page, I again got the "function expected" error, now in Global.ashx (b was expected to be a function, apparently) :
Sys._isInstanceOfType=function(c,b){if(typeof b==="undefined"||b===null)return false; if(b instanceof c) return true;
No idea what's the cause for it. Any help is welcomed.
Posting messages between windows should meet your requirements here. You can find more information here
Basically in your parent window do something like this:
window.onmessage = function (e) {
//e.data will contain some payload
Xrm.Page.getAttributes("xxx").setValue(e.data);
};
Or to be compatible with all browsers:
if (window.addEventListener) {
window.addEventListener('message', function (e) {
//e.data will contain some payload
Xrm.Page.getAttributes("xxx").setValue(e.data);
});
}
else { // IE8 or earlier
window.attachEvent('onmessage', function (e) {
//e.data will contain some payload
Xrm.Page.getAttributes("xxx").setValue(e.data);
});
}
Now in your child window only send the result using postMessage
window.opener.postMessage("I'm the result", '*');
I usually handle the scenarios that you described this way. The other solution would be to create a callback on parent window
window.callback = function() {
//do your stuff here
}
and from child window calling this callback:
childWindow.opener.callback();
But personally I prefer the postMessage approach, I had some problems with the callbacks sometimes.

Call a dynamic python function after the webpage is loaded in Django

I have a function in python which will return one of many Image URLs. I would like to implement a button on a webpage made with django which will change the image's source to the returned value. The issue I've run into is that django template tags are only accessible when the page is rendered, as explained here. Since the real code cannot be recreated in javascript, is there a workaround to get access to the python function's return data every time the button is pressed?
Here is some code to clarify my question:
class Foo(models.Model):
def get_image_url():
if(random.randint(0,1)):
return 'http://img1.jpg'
else:
return 'http://img2.jpg'
This is how I would want it to behave in javascript, if it were possible.
function updateImage(){
document.getElementById("testImage").src="{{ foo.get_image_url }}";
}
Thanks.
Sounds like you have to use AJAX for this. You can define a Django view which returns a JSON message with something like:
{
status: "ok",
url: "img1.jpg"
}
So in your code, you can define an event handler (in JavaScript) with something like this:
// Attach a listener to a button for a click event,
document.getElementById("testImageButton").addEventListener("click", function() {
var xhr = new XMLHttpRequest();
// This URL returns the above JSON.
xhr.open("GET", "/images/random");
xhr.onloadend = function() {
// Should have error handling in case response does not return correctly.
var imageResult = JSON.parse(xhr.response);
if(imageResult['status'] == 'ok') {
// update the image src
document.getElementById("testImage").setAttribute("src", imageResult['url']);
}
}
xhr.send()
})
So the only "dynamic function part" is whatever is inside your Django view function.

XPages: Get the contents of a - this._partialRefresh AJAX call?

I'm doing a partialrefresh of an XPage (Domino 8.5.1) but need to get the contents of the response.
The reason is that IE8 seems to (sometimes) have an issue with partial refreshed HTML not showing. I can see that the response is correct but the DOM isn't updated.
There's an easy fix for this:
div.innerHTML = div.innerHTML
But for me to apply this I need the content so I can insert it in the first place.
So, is it possible to get the returned HTML from a partialRefresh? Or is there another way to solve this?
You can trigger a partial refresh as a client-side event:
XSP.partialRefreshGet("#{id:targetId}", {
onComplete: function(responseData) {
// examine the response content
}
});
The onComplete function will be passed the response from the server, and you can parse or otherwise respond to the data within that function.
To hijack a partial refresh you can add this CSJS code:
// --- hijack dojo XHR calls
dojo._xhr = dojo.xhr;
var loadOld;
function hijacked( response, ioArgs ){
alert( response ); // change code here to do whatever you want. //
loadOld( response, ioArgs ); // call the original function
}
dojo.xhr = function( mode, args, bool ){
loadOld = args["load"];
args["load"] = hijacked;
dojo._xhr( mode, args, bool );
}
Just change the function "hijacked" to fullify your requirements.
Hope this helps
Sven
Edit:
The method "hijacked" is executed BEFORE the changes to the DOM will be applied (and before OnComplete event)

Modifying the DOM based on an AJAX result with jQuery

I'm unsure of the best practice for modifying the DOM based on an ajax response. I'll try to let the code do the talking because it's hard to explain.
// page has multiple checkboxes
$("input[type='checkbox']").live('click', function {
var cb = $(this); // for the sake of discussion i need this variable to be in scope
$("form").ajaxSubmit({ dataType: "script" });
}
The server sends a response back, and the js gets eval'd and that means "cb" is out of scope.
What I've done so far is create a couple of helper functions:
var target = undefined;
function setTarget(val) {
target = val;
}
function getTarget() {
return target;
}
And that turns the first snippet of code into this:
// page has multiple checkboxes
$("input[type='checkbox']").live('click', function {
setTarget($(this));
$("form").ajaxSubmit({ dataType: "script" });
}
Then on the server's response I call getTarget where I need to. This seems hackish... Any suggestions?
It's unclear what you're actually trying to do, but I feel like you want to be looking at the success parameter for that AJAX call. The success callback function should execute in parent scope and do what you're looking for.
See 'success' on this page in the jQuery docs.
So what you are trying to do is get the form to submit the content via ajax whenever the user checks/unchecks a checkbox? And because there are several checkboxes, you need to find out which one triggered the submit, so you can change its value to whatever is stored on the server?
If you submit the entire form everytime, why don't you reply with all the checkboxes values, and then change each and every one of them? If not, get the server to reply with the id and the value of the checkbox, then use jquery to find the checkbox with that ID and then change it's value.
How about:
jQuery(function($) {
// give it scope here so that the callback can modify it
var cb,
cbs = $('input[type="checkbox"]');
cbs.live('click', function {
// taking away var uses the most recent scope
cb = $(this);
// disable checkboxes until response comes back so other ones can't be made
cbs.attr('disabled', 'true'); // 'true' (html5) or 'disabled' (xhtml)
// unless you are using 'script' for something else, it's best to use
// a callback instead
$('form').ajaxSubmit({
success : function(response) {
// now you can modify cb here
cb.remove(); // or whatever you want
// and re-enable the checkboxes
cbs.removeAttr('disabled');
}
});
}
});

Categories

Resources