Javascript-invoked php content not displaying after load - javascript

Thanks to the help I received here, I have a piece of javascript that toggles the visibility of a div and loads content from a php file into that toggled div:
function compare_toggle_visibility(id, line, collection)
{
var e = document.getElementById(id);
e.style.display = ((e.style.display!='none') ? 'none' : 'block');
$(e).load('http:/www.minorworksoflydgate.net/XML/XQuery/test_command_line.php'+ '?collection=' + collection + '&zone=' + id + '&line=' + line, function(responseTxt, statusTxt, xhr){
if(statusTxt == "success")
alert("External content loaded successfully!");
if(statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
}
This works great with the small php files I'm using for testing, but the problem I'm running into is that my actual production file takes some time to load. So the div is toggled and exists before the code can be loaded into it. I get the alert message I put in as a test indicating that the external content loaded, but I see nothing in the div itself.
To try to fix this, I've attempted to place the toggle after the load function, but that made no difference. I also have tried to load the results of the php call into a variable and then call the results of that variable into the div when it loaded successfully, but that does not work either.
function compare_toggle_visibility(id, line, collection)
{
var e = document.getElementById(id);
e.style.display = ((e.style.display!='none') ? 'none' : 'block');
var l = load('http:/www.minorworksoflydgate.net/XML/XQuery/test_command_line.php'+ '?collection=' + collection + '&zone=' + id + '&line=' + line, function(responseTxt, statusTxt, xhr){
if(statusTxt == "success")
$(e).html(l);
if(statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
}
I'm not sure where I'm going wrong -- I'm pretty comfortable with php and XML, but less so with javascript and especially with Ajax and Jquery.

Try this
function compare_toggle_visibility(id, line, collection){ var e = document.getElementById(id);
e.style.display = ((e.style.display!='none') ? 'none' : 'block');
$.get('http:/www.minorworksoflydgate.net/XML/XQuery/test_command_line.php'+ '?collection=' + collection + '&zone=' + id + '&line=' + line, function(responseTxt){
$(e).html(responseTxt);
});
}

Related

How to load the external url in div without iframe

I want to load external url in a div without using iframe/embed/object tag. I already used examples but it is not working
For example:
$("#testDiv").load("//localhost:8000/cities/Mountain%20View/521/bottle-service/new");
or
$("#testDiv").load("//www.xyz.com");
Could anyone please help me fix this issue?
Based on your comment I think you need something like this:
$('#mydiv').load('http://localhost:8000/cities/Mountain%20View/521/bottle-service/new #testDiv', function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
alert(msg + xhr.status + " " + xhr.statusText);
}
});
For better insight I'm linking this question with this SO post

sapui5 - javascript error handling - without try-catch in every callback

I am developing a SAPUI5-App. Is there a way to show all errors directly to the customer without having to put a try-catch-block into every callback of sapui5? He will use my app in a mobile device and wouldn´t be able to see the log.
I tried already the following code:
<script type="text/javascript">
window.onerror = function(msg, url, line, col, error) {
var extra = !col ? '' : '\ncolumn: ' + col;
extra += !error ? '' : '\nerror: ' + error;
alert("Error: " + msg + "\nurl: " + url + "\nline: " + line + extra);
return false; //true = suppress error alert
};
window.addEventListener("error", handleError, true);
function handleError(evt) {
if (evt.message) {
alert("error: "+evt.message +" at linenumber: "+evt.lineno+" of file: "+evt.filename);
} else {
alert("error: "+evt.type+" from element: "+(evt.srcElement || evt.target));
}
}
jQuery.sap.log.addLogListener({
onLogEntry : function(oLogEntry) {
if(oLogEntry.level == '1'){
alert(oLogEntry.details + ' - '+oLogEntry.message);
}
}});
</script>
But I like to actually copy the error-message from the log into an alert for the customer, so he can send me screenshots of the error in his device.
All my attempts did not show enough information or didn´t fire on every error in the console-log.

UI kit notify pos issue

<script>
$(function(){
var ws_scheme = window.location.protocol == "https:" ? "wss": "ws";
var ws_path = ws_scheme + "://" + window.location.host + "/dashboard";
console.log("Connecting to " + ws_path);
var socket = new ReconnectingWebSocket(ws_path);
socket.onmessage = function (message) {
// Decode the JSON
console.log("Got websocket message " + message.data);
var display = '<div class="uk-alert uk-alert-success">'+ message.data + "</div>";
console.log("Got websocket message " + display);
UIkit.notify({
message : display,
status : 'info',
timeout : 0,
pos : 'top-center'
});
}
});
</script>
For the following snippet of code, UI kit notify is displaying the notification in the bottom left corner of the screen.
It doesn't change if I can the position to other possible values.
I must be doing something very silly. Any help is appreciated.
Message inside uikit notify is string only, maybe using div inside spoils the rest, try to make fiddle out of that.
Also notify component has its own css, be sure to include it.

Lag for just part of AJAX response

I made a simple chat. It's working properly, but not behaving as expected. When a user submits a message, the user's name, time and message are supposed to display.
It so happens that the username and response appear first and the time seems to be inserting itself after a slight delay (that's the lag). I can't figure out why, especially since the response is (or at least seems to be) sent as a whole and nothing is being inserting once the response is sent from the server...
Here's the link to the chat. You can input dummy username and dummy messages.
And here are the important pieces of code:
PHP
while ($row = $result->fetch_assoc()) {
$time = date('g:ia', $row['time']);
echo "<p class=\"message\"><i>{$row['username']}</i> ($time): {$row['content']}</p>";
}
JavaScript
ajax.onreadystatechange = function () {
if (ajax.status === 200 && ajax.readyState === 4) {
document.getElementById('messagesArea').innerHTML = ajax.responseText;
}
};
Your culprit is this section of the script:
var content = document.getElementById('messageBox').value;
if ( content === '') {
return;
} else {
var ajax = new XMLHttpRequest();
var username = document.getElementById('signedin').innerHTML;
document.getElementById('messageBox').value = '';
ajax.open('POST', 'postmessage.php', true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.onreadystatechange = function () {
if (ajax.status === 200 && ajax.readyState === 4) {
// if there are errors echoed from the PHP file
if (ajax.responseText != "") {
document.getElementById('mysqliError').innerHTML = ajax.responseText;
return;
}
document.getElementById('messagesArea').insertAdjacentHTML('beforeend', '<p class="message"><i>' + username + '</i>: ' + content + '</p>');
}
};
ajax.send('username=' + username + '&content=' + content);
}
Notice this line: document.getElementById('messagesArea').insertAdjacentHTML('beforeend', '<p class="message"><i>' + username + '</i>: ' + content + '</p>');
You are inserting the message, without the time, into #messagesArea. Then, in getRecentMessages later, it is set to fetch the entire chat log from displaymessages.php and overwrite #messagesArea with the content of the output, which does have the time.

JQUERY LOAD unable to load same html again

I have created an html page which renders differently depending on the parameter 'resourceType'.
ResourceType can be IO/CPU/STORAGE etc . I have adopted this design for reusability as we have same layout for all the charts except that the inputs to chart differs based on resourceType.
<script>
require(['../js/viewmodel/db-resource-analyze']);
</script>
<div class="oj-row" id="pageContent">
<div class="topchartRegionDiv">
.....
</div>
</div>
Now I am loading this page from my HOME page which have vertical tabs (like a left side menu)
On click of a tab ,I load my page dynamically using jquery load
window.paramObj =
{
resType: "cpu"
};
$('#cpuContent').load("db-analytics-resources-home.html", function(responseTxt, statusTxt, xhr) {
if (statusTxt == "success")
alert("External content loaded successfully!");
if (statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
The next time user click on IO tab ...i do same operation but with different parameter
window.paramObj =
{
resType: "io"
};
$('#ioContent').load("db-analytics-resources-home.html", function(responseTxt, statusTxt, xhr) {
if (statusTxt == "success")
alert("External content loaded successfully!");
if (statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
The first load happens without any issues , but subsequent load do not happen and page comes as blank.
I am suspecting the page is cached and not loaded. How to enforce reload skipping cache using JQUERY load. Any pointers ?
Try this Stop jQuery .load response from being cached
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});
As the guy mentions if the convenience functions like .load, .loadJSON, etc don't do what you need, use the .ajax function and you can find a lot of configuration options in there that will likely do what you need
you can try this methode. this will prevent all caching
$('#ioContent').load("db-analytics-resources-home.html?"+Math.random(), function(){})
Many Thanks for all response . I could get this resolved by passing JS script as parameter to JQUERY load callback and invoking it there on successfully load of html doc .
smthing like this :
$('#' + resType + 'Content').load(url, function(responseTxt, statusTxt, xhr) {
if (statusTxt == "success")
{
alert("External content loaded successfully!...calling JS");
new self.dbResourceAnalyze();
}
if (statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});

Categories