Calling PHP scripts from Javascript without leaving current page - javascript

I'm having some trouble calling PHP scripts from Javascript without leaving the current HTML page (if it is at all possible). I understand it is possible using AJAX, although is it possible using Javascript alone?
Context:-
I want my page to perform a short animation using Javascript (using onclick), then immediately call a PHP script to insert data into a MySQL database - all without leaving the page so it does not inhibit the animation.
The animation part I can do and the inserting the data into the database, etc. but how can I call a PHP script at the end of that Javascript animation function?
Any pointers, code fragments, etc. would be greatly appreciated! ^_^
Apologies if this question has been asked previous.

AJAX is Asynchronous Javascript And XML,
Its a Javascript technology that allows you to send a request to the server (as your browser does when you enter a URL) and have the response in a javascript string instead of rendering it in the page.
The problem is different browsers do not implement AJAX the same way, So I suggest using jQuery for abstraction.
do this with jQuery:
<script>
$.get("backend.php",{param:value},callbackFunction);
callbackFunction(data)
{
alert(data);
}
</script>

Just happened to have the same issue, so I came up with something like that. All you have to do is add the code you need, and assign the do_the_script function to the onclick event.
<script type="text/javascript">
var myIntv;
function do_the_script() {
// play animation ...
var address='fancy_script.php';
var tmp = new XMLHttpRequest();
myIntv=setInterval(function(){
tmp.addEventListener("load", doneHandler, false);
tmp.open("POST", address);
tmp.send(null);
}, 1000);
}
function doneHandler(event) {
// maybe do something when script is executed
clearInterval(myIntv);
}
</script>
As you may have noticed, the code that "calls" the address is executed every 1 second. This, is to ensure that the call is made enough times so as to get a single positive answer, call the doneHandler and clear the interval afterwards. If you believe that your server can respond faster or slower you should change those milliseconds accordingly.

you can use jquery ajax:
http://api.jquery.com/jQuery.ajax/

PHP is a server-side language.
JavaScript is a client-side language.
If you want to execute server-side code, you don't have the choice to do a round-trip to the server. If you don't want to leave the page, your only option is doing an asynchronous request (aka AJAX).
Using a JavaScript library such as jQuery or MooTools greatly simplifies that kind of task. For example, you could use MooTools to do a request at the end of your script as such:
var req = new Request({url: '/backend/doPHPInsert.php'});
req.send();
There are ways to do so without AJAX by, for example, creating an iFrame dynamically (or any other element that fetches a resource).

I understand it is possible using AJAX, although is it possible using Javascript alone?
If you don't want to use XHR, you could use this ugly hack...
var request = 'mysql-insert.php',
image = new Image();
image.onload = function() {
// Success
}
image.onerror = function() {
// Error
}
image.src = request;
Except that was only really used before widespread use of AJAX (or needing to make a cross domain request).
I would just use AJAX. jQuery provides some great abstractions for working with XHR.

If you do not want to include the jquery library you can simple do the following
a) ad an iframe, size 0px so it is not visible, href is blank
b) execute this within your js code function
window.frames['iframename'].location.replace('http://....your . php');
This will execute the php script and you can for example make a database update...

This has some good examples for using unadulterated XMLHttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
(Particularly, scroll down to the asynchronous examples - now you're cooking with gas.)
Edit: see also http://msdn.microsoft.com/en-us/library/ms535874%28v=vs.85%29.aspx which has examples for dealing with versions of IE which don't have native window.XMLHttpRequest.
Now, let's be frank - yes, working with XHR itself (especially cross-browser) is kind of obtuse. You can use just about anything out there (jQuery, Dojo, MooTools, Prototype, Closure, YUI, etc.) to do XHR more easily, because all of them, among other things, give you more concise XHR facilities.
It's still good to know what you're working with under the surface before you start letting a library do it for you though. :)

Related

AJAX request to only load/open a specific div without using JQuery?

Im looking to do something like this
$('#thisdiv').load(document.URL + ' #thisdiv');
where only the elements with the specified selector are loaded from the server, but I can't use Jquery, anyone know how to do it?
Read the XHR documentation here.
Basically, you create an XMLHttpRequest object (be wary of older browsers), then trigger its methods to load some content, then take the response and copy it where you want it.
The link above goes on to discuss XML parsing, which may come in handy if you want to use just the "#thisdiv" part of the XHR response.

A good way to pass information javascript?

I have an asp.net website, but I need to pass stuff to javascript to do stuff there. At the moment, I am doing things like this:
<script type="text/javascript">
var userHasMicrositePhoto = '<%=hasMicrositePhoto%>';
</script>
But I've been told that putting lots of script tags in like this is bad, and also its annoying to have to keep writing Properties in my code behind.
What is a better way to do this?
This is pretty much the ideal way to go IMO. If you have a lot of stuff like this, try putting it all in one <script>block. You could also use an array to reduce the code overhead, or have asp.net output a JSON encoded array with all the needed properties in it.
Depending on your architecture, you could consider fetching those properties through a separate Ajax request which would make the page body a bit cleaner, but it would be an extra request that can't be cached, so I would use this only in very extreme cases.
The same applies to embedding a separate <script src=....> it looks nicer in the generated markup, but needs another request to the server.
The only alternatives would be
write a page that generates AJAX and have your JavaScript access
that with XHR
write a page that generates JavaScript and have your
HTML access that with a single script tag
I don't think either of those solutions are obviously superior to what you're doing now, except they could be used by other pages more easily, if that helps.
I would use JSON when you're passing information to be used by javascript.
This may require you to reconsider how you're developing your website or application. I usually use it when the server is passing information via ajax but ajax isn't the only solution.
http://code.google.com/p/aspjson/
http://www.json.org/
I may not quite understand your question though so forgive me if I am totally off.

Importing external json files to a javascript script client-side without external libraries

I'm a bit new to javascript. Is there a way to do what I am describing in the title completely client-side and without any external libraries? Or is using jQuery the best/only way to go?
You can import a json file from a server via AJAX and them simply eval it. You don't need a library for that but using one makes it a lot easier. Of course just evaling a json string is not very secure as it can contain arbitrary text so all libraries parse it to see if it's well formed etc.
EDIT:
If you want to learn about AJAX you can start with this tutorial from w3schools. Ajax stands for Asynchronous Javascript And XML and it allows you to send a request to the server without reloading the whole page. In your case you will not be using Xml but JSON. Anyway, the tutorial explains the whole idea.
Yes there is. You can use the "document.write" to add scripts to the DOM at runtime:
in your case:
document.write('<script ...></script>');
Basically you are adding the script tag to the dom that will request the new file.
However there is something else to consider, although the script will be downloaded, you will need to have a variable assignment in it in order to use it in your page:
var x = { //json object };

Using jQuery to listen for an AJAX load that is not loaded using jQuery.AJAX

Okay, have a bit of a tricky one (for me anyway, i'm pretty rubbish at jQuery/JavaScript).
I'm pulling in data using standard AJAX (ie, NOT using a framework like jQuery or whatnot... there is a reason for it)
However, I then need to load up a jQuery script as soon as the page has been loaded in. So, here is the question, how do I bind the script once the DOM has been updated? I have been using Ariel Fleser's listen plugin (http://flesler.blogspot.com/2007/10/jquerylisten.html) for picking up on events such as clicks which works a treat, but I can't see how this can be used to listen for a load event.
Any ideas? I'm pretty stumped on this one!!
What's wrong with:
yourXMLHTTPRequest.onreadystatechange = function () {
if (this.readyState == 4) {
doJQueryStuff();
}
}
Also, what's the reason for not using the AJAX functionality provided in jQuery?
As an aside, it looks like that plugin you mention just replicates the functionality given by the live() and delegate() methods brought into jQuery in 1.4
In order to parse javascript loaded via ajax, you'll need to use eval(). Although, as far as these things go, a lot of coders consider eval() to be, um, evil... (a link, another link).
Regardless of the right and wrong of eval, this thread on webdeveloper should get you a lot of the way towards a solution.

I have an issue with inline vs included Javascript

I am relatively new to JavaScript and am trying to understand how to use it correctly.
If I wrap JavaScript code in an anonymous function to avoid making variables public the functions within the JavaScript are not available from within the html that includes the JavaScript.
On initially loading the page the JavaScript loads and is executed but on subsequent reloads of the page the JavaScript code does not go through the execution process again. Specifically there is an ajax call using httprequest to get that from a PHP file and passes the returned data to a callback function that in onsuccess processes the data, if I could call the function that does the httprequest from within the html in a
<script type="text/javascript" ></script>
block on each page load I'd be all set - as it is I have to inject the entire JavaScript code into that block to get it to work on page load, hoping someone can educate me.
If you aren't using a javascript framework, I strongly suggest it. I use MooTools, but there are many others that are very solid (Prototype, YUI, jQuery, etc). These include methods for attaching functionality to the DomReady event. The problem with:
window.onload = function(){...};
is that you can only ever have one function attached to that event (subsequent assignments will overwrite this one).
Frameworks provide more appropriate methods for doing this. For example, in MooTools:
window.addEvent('domready', function(){...});
Finally, there are other ways to avoid polluting the global namespace. Just namespacing your own code (mySite.foo = function...) will help you avoid any potential conflicts.
One more thing. I'm not 100% sure from your comment that the problem you have is specific to the page load event. Are you saying that the code needs to be executed when the ajax returns as well? Please edit your question if this is the case.
I'd suggest just doing window.onload:
<script type="text/javascript">
(function() {
var private = "private var";
window.onload = function() {
console.log(private);
}
})();
</script>
On initially loading the page the js loads and is executed but on subsequent reloads of the page the js code does not go through the execution process again
I'm not sure I understand your problem exactly, since the JS should execute every time, no matter if it's an include, or inline script. But I'm wondering if your problem somehow relates to browser caching. There may be two separate points of caching issues:
Your javascript include is being cached, and you are attempting to serve dynamically generated or recently edited javascript from this include.
Your ajax request is being cached.
You should be able to avoid caching by setting response headers on the server.
Also, this page describes another way to get around caching issues from ajax requests.
It might be best not to wrap everything in an anonymous function and just hope that it is executed. You could name the function, and put its name in the body tag's onload handler. This should ensure that it's run each time the page is loaded.
Depends what you want to do, but to avoid polluting the global namespace, you could attach your code to the element you care about.
e.g.
<div id="special">Hello World!</div>
<script>
(function(){
var foo = document.getElementById('special');
foo.mySpecialMethod = function(otherID, newData){
var bar = document.getElementById(otherID);
bar.innerHTML = newData;
};
//do some ajax... set callback to call "special" method above...
doAJAX(url, 'get', foo.mySpecialMethod);
})();
</script>
I'm not sure if this would solve your issue or not, but its one way to handle it.

Categories

Resources