Render DIV using javascript - php

I have a page with a load of tables on that are created using SQL lookups. Obviously, all of these together take time to load, each table (<div>) is "minimised" as default (I use javascript to hide it until a button is clicked). But these tables are still rendered in the background. What I really want is a way to block all of the div's content until called. I tried using a php if loop, which worked, but the page needed refreshing, so gave that one up.
Any ideas please? I've been looking for ages now.

I agree with Andre. If your page is always loading these tables, it will always take forever to build your whole page, there is no way that hiding the tables will increase your processing time. What you need to do is use an AJAX request that returns your table when needed, and then populate your div on the return.

I would go with the jQuery load method.
Basic example:
$(document).ready(function() {
$(".data").each(function(index) {
var tableName = this.id;
window.setTimeout(function() {
LoadData(tableName);
}, index * 1500);
});
});
function LoadData(tableName) {
var url = "load.php?table=" + tableName;
var oDiv = $("#" + tableName);
oDiv.html(url + " - To load real data, have here such code: <b>oDiv.load(url);</b><br />Good luck! :)");
}
This comes with such HTML:
<div class="data" id="cats_table"></div>
<div class="data" id="dogs_table"></div>
<div class="data" id="flowers_table"></div>
Live test case: http://jsfiddle.net/4H8Fa/

As the comment above says, it sounds like what you're looking for requires AJAX. Have a look at this Jquery library:
http://www.datatables.net/
UPDATE (based on comment from OP):
Since you have a custom solution, there isn't going to be a "recipe" that will work exactly with what you wrote. Generally, you should be looking at making a call back to your server using AJAX with a library like getJSON. Then populate your table by building TR/TD DOM objects and attaching them to your table object.

I did it using $.ajax and load()
<html>
<body>
<div id="load-div" class="functions">
<span>Load</span>
<input type="submit" value="Go" id="load_basic" />
</div>
<div id="result" class="functions">
</div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
var ajax_load = "<img class='loading' src='img/load.gif' alt='loading...' />";
// load() functions
var loadUrl = "page1.html";
$("#load_basic").click(function(){
$("#result").html(ajax_load).load(loadUrl);
});
</script>
</body>
</html>

Related

jQuery's GET is acting up for me. Using CodeIgniter. It returns source code for a view instead of one value

I am trying to test the jQuery GET method, but what I am getting as result is completely insane. All I am trying to do is call a function from my controller with jQuery and then display the echoed value in a div within my view. Below is my code and finally a breakdown of the problem I am encountering.
Controller
public function generate_suggestions2() {
echo "James";
}
View views\suggestions_v.php
<body>
//This DIV is used a button to call the jQuery function
<div id="next_btn">
<p>Click here to display a name</p>
</div>
//In this div the value retrieved by the jQuery should be displayed
<div id="listB"></div>
//This is the function that calls the function within my controller
<script type="text/javascript">
$( "#next_btn" ).click(function() {
$.get("core/generate_suggestions2/",
function(data) {
$( "#listB" ).html(data);
});
});
</script> //For some reason I need to put the script at the end of the body. When it's in the head nothing happens when I click the button. Also something I do not understand.
</body>
Now the problem is that when I click the DIV next_btn it does NOT display the James in the DIV listB.
Instead it populates the DIV listB with my source code from my main view views\core_v.php
I have no idea how this is even remotely possible, so please if you have a clue or even better you know what I am doing wrong please tell me. I am trying to get this to work for the past three days without any success or progress :(
Try using this code in your view
<script type="text/javascript">
"$( "#next_btn" ).click(function() {
$.get("<?php echo site_url().'/core/generate_suggestions2';?>",
function(data) {
$( "#listB" ).html(data);
});
});"
</script>
Also delete the </script> tag just right before this block comment.
Regarding this comment you have:
//For some reason I need to put the script at the end of the body. When it's in the head nothing happens when I click the button. Also something I do not understand.
It is because the DOM is not yet fully loaded and Javascript executes its code when the browser has finished loading the DOM you are referring to. So you either have to put it after the DOM element you want to edit, like you do now or you could use $(document).ready(function(){
}
); .
Read more about it here
This line is pretty strange:
</script><script type="text/javascript">
Try to delete first closing tag 'script' on it.

jQuery not updating div content after database update

I am loading a php file in a div using jQuery. The php file displays the content of a MySQL database. It works fine but here is the problem: if I make a change to the database, I add a row for example, the div does not reflect the change. Whatever I do I just see the data as they were the first time I accessed the page.
The code I am using is pretty simple:
// This goes into head
<script src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
function recp(id) {
$('#myStyle').load('displaydata.php?id=' + id);
}
</script>
// Set id to '1' onload
<body onload="recp('1')">
// Then I have a few links that will change the value of id onclick
Materials | Manufacturing
// Finally my div
<div id='myStyle'>
</div>
I do not put here the displaydata.php code. Anyway it is just a simple php file that SELECT and ECHO data.
Does anyone know what I am doing wrong? Why the div does not reflect the changes I make to the MySQL database? Thanks.
I would suggest you to think of a problem in terms of caching. If you are okay with moving away from load method, you could take a look at following code and make it into a right use.
var recp = function(id) {
$.ajax({
url: '/displaydata.php?id=' + id,
cache: false,
dataType: 'html',
success: function(data) {
$('#myStyle').html(data);
}
});
};
Hope it helps.
Is your php page cached? If you're making changes to the database behind the scenes, you need to clear your cache.

Allowing javascripts in an AJAX Called file

I have read numerous methods of allowing scripts that are called by an AJAX function but I am having trouble making it work, so if possible an example for this specific code would be great as I am relatively new to JS and AJAX.
This is the main javascript(which is looped in the index page) to request updated content
(Lets call this index.php)
if (window.XMLHttpRequest)
xmlhttp2 = new XMLHttpRequest();
} else {
xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange = function () {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
document.getElementById("botcontain2").innerHTML = xmlhttp2.responseText;
}
}
xmlhttp2.open("GET", "chat/shownew.php?fie=" + Math.random() + "&id=" + id + "&nm=" + nm, true);
xmlhttp2.send();
}
Here is the javascript it will call in the shownew.php file which is meant to hook to the below form
<script id=runscript2 type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/ext-core/3/ext-core.js"></script>
<script type="text/javascript" id="runscript">
Ext.onReady(function(){
Ext.fly('form').on('submit', function(e){
e.preventDefault();
var date = Ext.fly('date').dom.value;
var me = Ext.fly('me').dom.value;
var them = Ext.fly('them').dom.value;
var n = Ext.fly('text').dom.value;
var hi = "submit.php?me="+me+"&them="+them+"&date="+date+"&ty=ty";
Ext.Ajax.request({
url: "chat/insertchat.php?me="+me+"&them="+them+"&date="+date+"&ty=ty",
success: function(){ alert(hi); },
failure: function() { alert(hi) ; },
params: { text: n }
});
return false;
});
});
</script>
Yeh, its meant to hook onto this form in the same file that is called by ajax(shownew.php)
<form id="form">
<input id="date" type="hidden" name="date">
<input id="me" type="hidden" name="me">
<input id="them" type="hidden" name="them">
<input id="text" type="text" name="text">
<input type="submit">
</form>
So yeah, at the moment I can't get the shownew.php javascript to function at all.. any advice would be great, or a simple example on how I could make it work.
Script tags loaded through XMLHttpRequest will not be evaluated. You can as you said go in a number of directions. Use an image hack and define your function in the parent file from where you make the ajax call.
You could use eval(), although no one ever should if there are another solution.
Append your script to in the parent document.
Or simply use JQuery as that might be the easiest way.
I resolved this problem by only updating the inner form segments, so my index page has this on it, instead of starting the form inside the file that is updated. While it isnt updating scripts after ajax calls, its a workaround. Hope this helps someone.
<form id="form">
<div id=divupdatedbyAJAX>
Ajax information is inserted here.
</div>
</form>
When dynamically loading javascript the easiest way is to attach it as a script element (as suggested by Ben Carey in comments above). Here is the code in normal javascript rather than relying on JQuery:
function loadJs(file) {
var head= document.getElementsByTagName('head')[0],
script=document.createElement('script');
script.setAttribute("type","text/javascript");
script.setAttribute("src", file);
head.appendChild(script);
}
EDIT: You can call this function at the point you want the script to be loaded. It is probably best done immediately before the ajax call so that both requests can run concurrently:
loadJs('runscript2.js');
if (window.XMLHttpRequest)
...
However, having looked at your question a little more carefully, there is still a problem. The script may load before you have updated the dom with the new form. This will prevent your script working as it assumes the dom is there before it is called. You could solve this by only calling loadJS once the dom has been updated but this would result in an unnecessary delay before the form was functional. The alternative is to change runscript.js so that it reads:
<script id=runscript2 type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/ext-core/3/ext-core.js"></script>
<script type="text/javascript" id="runscript">
var runscript2 = function() {
Ext.fly('form').on('submit', function(e){
...
};
</script>
you can then call the function runscript2 after you have manipulated the dom (not shown in your code snippets but presumably looks something like this)
document.getElementById('someDiv').innerHTML=xmlhttp2.responseText;
var runscript2Ready = function() {
if (typeof runscript2 === 'function') {
runscript2();
}
else {
setTimeout(runscript2Ready, 50);
}
}
runscript2Ready();
Here, after the dom has been updated, we run a function which executes the javascript if it has been loaded or, if not, keeps trying again at 50ms intervals until it has.
Note: If I was cleverer, I would have said this at the start, but do you actually need to dynamically load the js? Why not just include it in the original index file (modified as I've suggested) and then just call the runscript2 function after manipulating the dom. That way you don't need to worry if the js has loaded yet.
Note2: If I was even cleverer I would know something about extJS (which it appears you are using) but, unfortunately, I don't. It is possible (but unlikely) that the Ext.onReady method does something more special than simply waiting for the dom to load. In this case my code will fail. More likely is that ExtJS has the facility to deal with dom elements that don't yet exist (as JQuery does). This would simplify your situation enormously.

running a js function via onmousedown for newly added ajax

i'm using JQuery ajax to load new content into the page, on the server side I load a new div:
<div id="newFuncDiv" onmousedown="javascript:newFunc("VAR");">Click me</div>
In previous cases i used a function as follows:
function newFunc(){$("#newFuncDiv").click(function(){alert("something");});}
But in this case onclick of this div I need to pass a variable, which I extract from the db on server side, how can i achieve this, as even when I add the newFunc(); with the ajax response it doesn't work,
EDIT:
by the way, forgot to say that i'm looping the response from server so the variable i need to pass is gonna be unique for each div.
since you are using jquery, i'd built the click handler jquery style and attach a data object to the html element:
<div id="newFuncDiv" data-foo="bar">Click me</div>
$("#newFuncDiv").on('click',function(){
alert("something" + $(this).data('foo'));
});
You can use this to reference that div.
function newFunc(myVar) {
$(this).click(function(){
alert(myVar);
});
}
You can save your variable into some attribute to each div and assign a same class a to each div like this
<div class="clickme" id="youvar1"></div>
<div class="clickme" id="youvar3"></div>
<div class="clickme" id="youvar3"></div>
then in jquery
$(document).ready(function(){
$(".clickme").click(function(){
var uniquevar = $(this).attr('id');
/*your ajax code here*/
});
});
Hope this help

Save data to PHP / Mysql with inline edit in CKEditor

I want to use "inline edit" of the new CKEditor 4 (http://docs.ckeditor.com/#!/guide/dev_inline-section-2), but can not find any example of how to save the data with PHP / MySQL.
Can you help me?
You need some AJAX magic. Via JavaScript inside the page you get the edited HTML. Then you send it to the server where a PHP script gets it and can pass it onto MySQL.
Here is a simple test case which will show you the ropes.
Let's start with the editable HTML.
<div id='textToBeSaved' contenteditable='true'>
<p>Using the <strong>Terminal</strong> in OS X makes you all-powerful.</p>
</div>
We also need a "Save" button which will be used to start the POST event.
<button onclick='ClickToSave()'>Save</button>
Such a button could well we positioned in the CKEditor toolbar itself, but that would require more coding and I'll leave it to someone who's better at JavaScript than me.
Of course you want to include CKEditor. For my sample code I'll also make use of jQuery, which I'll use for AJAXing the results.
<script src='//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
<script type='text/javascript' src='CKEditor4/ckeditor.js'></script>
Now the script which will execute when you press the "Save" button. It will use CKeditor to grab the edited HTML, then jQuery to send it.
<script type='text/javascript' language='javascript'>
// <![CDATA[
function ClickToSave () {
var data = CKEDITOR.instances.textToBeSaved.getData();
$.post('save.php', {
content : data
})
}
// ]]>
This is it, you don't need anything else clientside.
On the server, you must have the PHP code which will act when the script POSTs the updated HTML. The script must be called save.php and be positioned in the same directory where the HTML is if you use my code verbatim.
My one-liner here will just save your HTML in a temporary file inside the /tmp folder. Feel free to add your MySQL magic instead.
<?php
file_put_contents('/tmp/serverside.html', $_POST['content']);
?>
This is the way I've done it in the past:
The current_page_id relates to the table row we wish to update, otherwise we wouldn't know what record we need to update.
<div id="editable">My body text</div>
<input type="hidden" name="page_id" id="current_page_id" value="10" />
<script type="text/javascript">
CKEDITOR.disableAutoInline = true;
CKEDITOR.inline('editable', {
on: {
blur: function( event ) {
var params = {
page_id: $("#current_page_id").val(),
body_text: event.editor.getData()
};
$.ajax({
url: 'php_file_to_post_to.php',
global: false,
type: "POST",
dataType: "text json",
data: params,
success: function(result) {
console.log(result);
}
});
}
}
});
</script>
The inside of your php_file_to_post_to.php PHP file you simply catch the ajax post request and update the row based off of the page_id variable which has also been posted along with the edited content.
This is how you will get text area data
CKEDITOR.instances.editor1.getData()
CKEDITOR is nothing but the object you used to create functionality.
Thanks so much for the code. Try to improve de code with file_put_contents('page.php', stripslashes($_POST['content']));
And add to the div onBlur="ClickToSave()" and now you can to delete de save button.

Categories