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.
Related
I have a form inside a DIV (normally the div is hidden using "display:none;")
The user open the DIV with: onclick='$("#Details").show("slow");
Fills out the form and save the data.
I don't want the entire page to be reloaded, and I need only this DIV to be reloaded
I tried:
function(data) {
$('#Detalils').load(location.href + ' #Detalils');
});
and:
$("#Detalils").load(location.href + " #Detalils, script");
and:
$('#Detalils').load(location.href + ' #Detalils', function() {
$('#script').hide();
})
where in #script I put my script
In this div I have some script, and because of the jQuery on load script execution, the script is not executed.
I cannot put the script in an external file, it must be in the page body.
Is there a way to execute the script a well?
Thanks
Your actual Javascript code should not be within the div, that is the issue. If you wish to reload the form for the user to enter new data, then use ID's on the elements within your forms and write your JQuery code outside of it or in an external file, here is a simple example :
Instead of something like :
<form>
<input type="button" onclick="alert('hello');"> Click me ! </input>
</form>
Do something like :
<form>
<input id="myButton" type="button"> Click me ! </input>
</form>
<script type="text/javascript">
$("#myButton").click(function()
{
alert('hello');
});
</script>
You will have to adapt your code to this, of course, but you don't have another choice. HTML code can be removed and added at will, but Javascript code must not be treated the same way. There are many reasons for this, but one reason is that the browser will only load the Javascript functions once, for obvious optimization reasons.
The works within my local environment. Give it a shot in yours.
The HTML:
<div id="wrapper">
Remove
Reload
<div id="Details">my details box</div>
</div>
The jQuery:
<script type="text/javascript">
function mload() {
/*LOAD IN MY EXTERNAL STUFF*/
mtarget = $('#Details'); //the element on your page, that houses your external content
mscript = 'external.js'; //the js script required for your plugin to work
mtarget.load("external.html", function(){
$.getScript(mscript, function() {
//run the plug-in options code for your external script here
});
});
//*/
}
function madjustments() {
/*ADJUST THE LOADING PROCESS*/
//remove the load request on click from your remove button
$('#mremovebtn').on("click",function(e) {
e.preventDefault();
$('#Details').children().remove();
});
//reload the request on click from your reload button
$('#mreloadbtn').on("click", function(e) {
e.preventDefault();
mload();
});
//*/
}
(function($){
mload();
madjustments();
})(jQuery);
</script>
You will obviously need 2 additional files. One called external.html and another called external.js, for my demo code to work. But you can change the naming process to whatever works for you.
Extra:
Set a class in your external html file (on the parent element), for example #external. And by default, set the CSS to display:none in the style sheet. Then when the page loads in, simply show() it in the jQuery code.
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>
Is it possible to get an element id into a PHP variable?
Let's say I have a number of element with IDs:
<span id="1" class="myElement"></span>
<span id="2" class="myElement"></span>
How do I get this into a PHP variable in order to submit a query. I suppose I would have to resubmit the page, which is OK. I would like to use POST. Can I do something like:
<script language="JavaScript">
$(document).ready(function(){
$(".myElement").click(function() {
$.post("'.$_SERVER['REQUEST_URI'].'", { id: $(this).attr("id") });
});
});
</script>
I need to pass $(this).attr('id') into $newID in order to run
SELECT * from t1 WHERE id = $newID
jQuery is a very powerful tool and I would like to figure out a way to combine its power with server-side code.
Thanks.
This is like your question: ajax post with jQuery
If you want this all in one file (posting to active file) here is what you would need in general:
<?php
// Place this at the top of your file
if (isset($_POST['id'])) {
$newID = $_POST['id']; // You need to sanitize this before using in a query
// Perform some db queries, etc here
// Format a desired response (text, html, etc)
$response = 'Format a response here';
// This will return your formatted response to the $.post() call in jQuery
return print_r($response);
}
?>
<script type='text/javascript'>
$(document).ready(function() {
$('.myElement').click(function() {
$.post(location.href, { id: $(this).attr('id') }, function(response) {
// Inserts your chosen response into the page in 'response-content' DIV
$('#response-content').html(response); // Can also use .text(), .append(), etc
});
});
});
</script>
<span id="1" class="myElement"></span>
<span id="2" class="myElement"></span>
<div id='response-content'></div>
From here you can customize the queries and response and what you would like to do with the response.
You have two "good" choices in my mind.
The first is to initiate a post request every time the ordering changes. You might be changing the ordering using jQuery UI sortable. Most libraries that support dragging and dropping also allow you to put an event callback on the drop simply within the initialization function.
In this even callback, you'd initiate the $.post as you have written it in your code (although I would urge you to look up the actual documentation on the matter to make sure you're POSTing to the correct location).
The second strategy is to piggyback on a form submission action. If you're using the jQuery Form Plugin to handle your form submissions, they allow you to indicate a before serialize callback where you can simply add into your form a field that specifies the ordering of the elements.
In both cases, you'd need to write your own function that actually serializes the element IDs. Something like the following would do just fine (totally untested; may contain syntax errors):
var order = [];
$('span.myElement').each(function(){
// N.B., "this" here is a DOM element, not a jQuery container
order.push(this.id);
});
return order.join(',');
You're quite right, something along those lines would work. Here's an example:
(btw, using $.post or $.get doesn't resubmit the page but sends an AJAX request that can call a callback function once the server returns, which is pretty neat)
<script language="JavaScript">
$(document).ready(function(){
$(".myElement").click(function() {
$.post(document.location, { id: $(this).attr("id") },
function (data) {
// say data will be some new HTML the server sends our way
// update some component on the page with contents representing the element with that new id
$('div#someContentSpace').html(data);
});
});
});
</script>
Your approach looks perfectly fine to me, but jQuery does not have a $_SERVER variable like PHP does. The url you would want to provide would be window.location (I believe an empty string will also work, or you can just specify the url on your own). You seem to be sending the ID just fine, though, so this will work.
If you want the page to react to this change, you can add a callback function to $.post(). You can do a variety of things.
$.post(window.location, {id: this.id}, function (data) {
//one
location.reload();
//two
$("#responsedata").html(data);
//three
$("#responsedata").load("affected_page.php #output");
});
I think number 2 is the most elegent. It does not require a page reload. Have your server side php script echo whatever data you want back (json, html, whatever), and it will be put in data above for jQuery to handle however you wish.
By the way, on the server side running the query, don't forget to sanitize the $id and put it in quotes. You don't want someone SQL Injecting you.
Sorry if title is not too clear but I think it's about right. NEhow, what I would like to do is a bit like (well is to a certain extent) building a widget with JQuery (pref), PHP & CSS.
What I would really like to happen is for a "member" of my site to simply paste 2 lines of code in their HTML to load the widget. Something like this:
<script type="text/javascript" src="http://www.mydomain.com/script.js"></script>
Then to display the widget something like this <div id="displaywidget"></div>
OK that bit is "easy" and ok. But how do I include JQuery or "something" to generate the widget in script.js
What I mean is "displaywidget" - the ID of the widget div will be the name of a php file on my server so essentially script.js will need to load displaywidget.php into the div displaywidget.
I think I use document.getElementById('displaywidget') to get the div but how do I then "write/insert/load" displaywidget.php inside the div?
Thinking as I write "pure" java can do "most of what I want i.e. document.getElementById('displaywidget'), BUT I would prefer to also "include" Jquery.js as I would like some aspects of the widget to use JQuery. Example being the JQuery UI date function.
Sorry if I am rambling a bit but trying to think as I go along. My "real" problem is I am not too sure on "pure" javascript i.e. getting the div to display/load displaywidget.php
Suggestions please. (Oh if I am barking up the wrong tree please feel free to tell me - nicely:) )
Thanks in advance
I think I use document.getElementById('displaywidget') to get the div but how do I then "write/insert/load" displaywidget.php inside the div?
You're looking for the AJAX behaviors inside of jQuery which would make the call to the php page and then push the data into the div.
You should be loading jQuery early on in the process, right up front in your head element. Once its loaded it will be cached so no worries of its on every page. No real overhead incurred.
Once jQuery is installed you can call one of many AJAX functions related to obtaining data and popluation elements. Theres $.load(), $.ajax(), and a few others that escape me unless I go and check out their docs section.
You can do all of this without jQuery, but its more code and you have to control for browser differences.
You can load jquery into script.js, just copy and paste it after or before whatever javascript lives in script.js.
So if script.js is:
//start of file
alert('ex');
//end of file
Make it:
//start of file
alert('ex')
Copy and pasted Jquery source
//end of file
After a bit more "trawling & thought" I found this code:
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src","http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
script_tag.onload = scriptLoadHandler;
script_tag.onreadystatechange = function () { // Same thing but for IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
/******** Our main function ********/
function main() {
jQuery(document).ready(function($) {
******* Load CSS *******/
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "style.css"
});
css_link.appendTo('head');
/******* Load HTML *******/
var jsonp_url = "http://al.smeuh.org/cgi-bin/webwidget_tutorial.py?callback=?";
$.getJSON(jsonp_url, function(data) {
$('#example-widget-container').html("This data comes from another server: " + data.html);
});
});
}
})(); // We call our anonymous function immediately
writtend by Alex Marandon and found here http://alexmarandon.com/articles/web_widget_jquery/ - works a treat, exactly what I wanted, including/installing JQuery into a .js file
echo "<a href=#> Delete </a>";
Whenever a user hits Delete, a javascript function should be called for confirmation. Somewhere in the Javascript function, php code should be used for delete operation. How do I do that? Use something like "some php code goes here" and "some javascript function();" for me to know where to put what. Thanks.
This assumes that you are using jQuery...
<a href='javascript:delete();'>Delete</a>
<script type="text/javascript">
function delete()
{
$.post("/your_script.php", {}, function(result) {
});
}
</script>
JavaScript functions execute on the client (in the browser) and PHP executes on a server. So, the JavaScript must send a message - via HTTP - to the server to be handled by PHP. The PHP would perform the delete. Make sense?
The message sent to the server might be sent via AJAX.
Maybe you should use Ajax: http://en.wikipedia.org/wiki/Ajax_%28programming%29
PHP is a server-side technology, while JS is a client-side. They cannot interact with each other - in other words: they're completely independent.
PHP can only output code that is a JS code:
echo 'document.getElementById("test").appendChild(document.createTextNode("' . $myVar . '");';
It's all PHP can do. JavaScript cannot direct interact with PHP as well. You'll have to use AJAX to send a new HTTP request and process returned data.
PHP is a server-side language, thus you can not output PHP script to the browser and expect that it will parse it with the PHP engine.
What you're looking for is probably AJAX, or simply redirecting the user to another page (with different URL parameters) or submitting a form.
AJAX doesn't require from the browser to reload the page, while the two other methods does.
Anyway, you can execute a JS script with the "onclick" method, that's executed when the user clicks on the element: Delete
But the following approach looks better and considered as an ideal one:
Delete
<script type="text/javascript">
document.getElementById("myId").onclick = myFunc;
</script>
Since this involves Ajax, let's assume you can use jQuery to handle the XHR an so on.
<script>
$('#del').click(function(ev){
ev.preventDefault();
var del_conf=confirm('Are you sure you want to delete this item?');
if(del_conf){ $.post('delete.php',{'del':1,'id':123123},function(data){
alert(data.result);},'json');
}
});
</script>
<a id='del'>Delete</a>
Okay, so that's some JS and HTML. Now, you need a separate PHP script to handle the post. To go with the example, this would be saved in the same directory, named 'delete.php'.
<?php
$del=(int)$_POST['del'];
$id=(int)$_POST['id']
if($del<1 || $id<1){ exit; }
else{
//do your DB stuff
}
if($db_success){
echo json_encode(array('result'=>'success'));
}
else{
echo json_encode(array('result'=>'error'));
}
here is another example using jQuery:
<div id="message"></div>
<a class="action" type="delete" rel="1234567">delete</a>
<script type="text/javascript">
$('a.action').click(function(){
var $this = $(this);
var processResponse = function(data){
//optionaly we can display server response
$('#message').html(data);
return;
};
var postPparams = {
module:'my_module_name',
action:$this.attr('type'),
record_id: $this.attr('rel')
};
$.post('/server.php',postPparams, processResponse);
});
</script>