Ok ... I'm just an amateur, so please forgive me for any inaccuracies in typing, but it works: The format that I use to call ajax in the <a> element is:
<a href="javascript:" onclick="functionThatReallyCallsAjax()">
So I have more flexibility (in case I need to check something before sending ajax). Now to call ajax you need:
- What file to call
- What to do with the answer from the file you named
- What to do if an I / O error has occurred
So, we have this function, and not mine, because of which I erupted from somewhere - perhaps here :) - and, probably, it is well known, my apologies to the author, he is a genius: This is what you call ajax, where "url" is the file you want "ajax", "success" is the name of the function that deals with the results, and error is the name of the function that deals with I / O errors.
function doAjaxThing(url, success, error) { var req = false; try{ // most browsers req = new XMLHttpRequest(); } catch (e){ // IE try{ req = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { // try an older version try{ req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { return false; } } } if (!req) return false; if (typeof success != 'function') success = function () {}; if (typeof error!= 'function') error = function () {}; req.onreadystatechange = function(){ if(req.readyState == 4) { return req.status === 200 ? success(req.responseText) : error(req.status); } } req.open("GET", url, true); req.send(null); return req; }
Naturally, you need to enable the success + error functions:
function dealWithResponse(textFromURL) {
And now that you are armed with this, you are creating a real call inside the function that you called in <a> :
function functionThatReallyCallsAjax() {
One scenario may be when you need to pass a variable to PHP that you did not have before. In this case, the call will look like this:
doAjaxThing("serverFile.php?parameter1=dogsRock",dealWithResponse,ohNo);
And now you have PHP sending stuff to JS, you also send JS to PHP. Weeeee ...
Final words: ajax is not a language, its a javascript trick. You do not need to fully understand what the first doAjaxThing function does to use this, just make sure you call it correctly. It will automatically “call” the “WithResponse Deal” function after receiving a response from the server. Please note that you can continue to carry out your activity (asynchronously - the process is not time-bound) until you receive an answer - this is when the "WithResponse transaction" is triggered - as opposed to stopping the page and waiting (synchronously - time is bound) until the answer comes. This is the magic of ajax (asynchronous JAvascript and Xml).
In your case, you want to add an echo ("success") - or an error! - in PHP, so the "dealWithResponse" function knows what to do based on this information.
That is all I know about ajax. Hope this helps :)