difference from using ajax from jquery and javascript - javascript

i cant find an answer to this
i have been learning ajax lately but i learned how to do it all in javascript
now i go swiming around ajax question here and almost all are using jquery
so i end up confused. should i use normal javascript or do it through jquery?
so what are the differences?
this is my normal approach
var xmlHttp = createXmlHttpRequestObject(); //you first create the object to this function global
function createXmlHttpRequestObject() //here you instruct the function
{
var xmlHttp; //here you tell it to use the local variable not the global version of it because this returns to the global with the propper values
if (window.XMLHttpRequest) //if the "window" or browser is aware of this Object 90% of browsers
{
xmlHttp = new XMLHttpRequest(); // if true then the variable is now equal to the heart of ajax
}
else //for internet explorer
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp; //we return it back to daddy the global variable this objects does everything
//this object is everything in ajax for the most part
}
function process() //function that gets called on load of the body
{
if(xmlHttp) //if its not void or if you can run ajax
{
try //try catch statement are sort of required for the heart of things like ajax and server communication
{
xmlHttp.open("GET", "bacon.txt", true); //here 1st type of call 2nd from where 3rd
//is it true assyscronly or at the same time
//it does not start the connection to the server, its only sets up settings for the connection
xmlHttp.onreadystatechange = handleServerResponse; //anytime something changes[propertie]
//i want to call that function handleserverresponse
//begin communication
xmlHttp.send(null); //this is what communicates to the server makesure on ready statechane before this
//if the server responds you want to make sure everything is taking care of like what function onready state change is it going to call
//or what to do like open a text file in this case
} catch(e)
{
alert( e.toString() ); //alert the error message as a string on a popup
}
}
}
//handling the server response
function handleServerResponse()
{
theD = document.getElementById('theD'); //get the div in a var
if(xmlHttp.readyState==1) //if the connection to the server is established
{ //google crhome may not show this one, some browsers ignore some states
theD.innerHTML += "Status 1: server connection established<br>";
}
else if(xmlHttp.readyState==2) //request received, hey client i am the server and i received your request
{
theD.innerHTML += "Status 2: request reveived <br>";
}
else if(xmlHttp.readyState==3) //while is doing its thing
{
theD.innerHTML += "Status 3: processing request <br>";
}
else if(xmlHttp.readyState==4) //your request is finished and ready
{ //it means your response is ready but doesnt guaranteed no trouble
if(xmlHttp.status==200) //if the status is 200 then is succesufll
{
//IF everthing finally good THE GOOD PART
try //put all your calls on a try statement REMEMBER
{
//get the txt file as a string
text = xmlHttp.responseText; //response text n a normal string
theD.innerHTML += "Status 4: request is finished and response is finished";
theD.innerHTML += text;
}catch (e)
{
alert( e.toString() );
}
} else //for the other statuses like 404 else somehting went wrong
{
alert( xmlHttp.statusText ); //this will give you a status report on the wrong
}
}
}

jQuery simply wraps all of the XmlHttpRequest calls into a simple to use library. In the guts of jQuery you will see code that creates the XmlHttpRequest objects.
You can see the code that does this here:
https://github.com/jquery/jquery/blob/master/src/ajax/xhr.js
The nice thing about using a framework like jQuery is that they handle a lot of the browser idiosyncrasies for you. They also handle a lot of the edge cases you might not think about when writing your code.

Using jQuery is just for ease of use. If you prefer doing it the javascript way then carry on doing that.
jQuery ajax calls do exactly the same as what you are doing but jQuery is a javascript framework which simplifies what you write.

jQuery is a javascript framework which contains library of simplified functions compared to the Native Javascript. One of the functions is the XMLHttpRequest.
This way we just need to implement functions that is needed to implement without needed to write the traditional codes to setup the AJAX system to work
You may learn more about jQuery ajax here:
http://api.jquery.com/jQuery.ajax/

Related

Calling php function inside Javascript code

I know that this question has been asked before but all of them are using jQuery library and i would like to use Javascript only, no libraries so please bear with me.
This link shows the PHP function being called from jQuery.
How can I call PHP functions by JavaScript?
The code is calling a function that displays images.
I have the following code and I don't understand how to call the function from the mainfile.php and not functions.php.
mainfile.php
<button id="btn">Click</btn> // button that calls ajax file
<div id="div"></div> // div where it should appear
<script>
function loadXML(method, url, div, index)
{
var xmlhttp;
try
{
xmlhttp = new XMLHttpRequest();
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e)
{
alert('sorry');
}
}
xmlhttp.onreadystatechange = function()
{
if( xmlhttp.readyState === 4 && xmlhttp.status === 200 )
{
if( index === null || index === 'undefined' || xmlhttp === '')
{
document.getElementById(div).innerHTML = xmlhttp.responseText;
}
}
};
xmlhttp.open(method, url, true);
xmlhttp.send(null);
}
document.getElementById('btn').addEventListener('click', function()
{
loadXML('GET', 'imgs.php', 'div', null);
}, false);
</script>
functions.php
<?php
function getImgs($dir, $type)
{
$images = glob($dir . $type);
print_r($images); // for now i'm printing the array the way it is to see the function work
}
getImgs('images/', '.*JPG'); // calling function from php file works
?>
I would like to call the function from inside mainfile.php without using any jQuery library, only plain Javascript, it should be possible considering that the libraries are made with Javascript. I don't know where to call the function from inside mainfile.php. Any help would be appreciated.
The reason I am getting files from php is because it is easier to load them into the DOM, I need to make an image gallery so I would like to know if it will be possible to manipulate the images when they are loaded into the DOM using AJAX.
You can only do it by Making an AJAX request to a php page while passing in a parameter to initialise the function.
That means your AJAX will send in for example "functionName" to the php page "functionsListPage.php"
The GET will be recieved :
if (isset($_GET['functionName']))
functionExec();
This is the only way so you are not calling direct from the client however you are indicating to the server you want to run a predefined request.
You cannot call a PHP function directly from the clientside.
It's just like the answer from #Pogrindis, but i think so explanation is needed
It is possible to do it with with plain JavaScript with a little workaround!
What you need to do is the following in JavaScript after the xmlhttp.open();
var functionname = getImgs;
xmlhttp.open();
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.send(functionname);
What this does is simple: it sends the data to the server, so you php file can get this parameter!
In your called php file you need something like this:
if( isset($_POST['functionname']) )
{
if($_POST['functionname']) == 'getImgs'
{
getImgs();
}
}
Of course you need to make sure that you post the data with post in this case, if you want to use get you need to change the php to $_GET
Notice: This is totally unsafe right now! No escaping from the coming data and anything else.

Problems understanding/using callback function

In this discussion and in chat I understood that a callback is the only way to go!
"
Get from the server a link with ajax, write the link in a variable, open an xml with this link, doing some stuff with the xml: is callback the only way?
"
I'm trying to understand what a callback is. I read some blog, but I still have problems.
What I have now in JS is
1) a function to open an xml.
2) function to request the link of the xml in first function
Can someone provide an example in PLAIN JAVASCRIPT of how to nest these two functions?
The server generate the link of the xml because I'm making a multi user web site and every user has it's own xml. So I need to ask the server what is the link of the xml and then open it. Is there an easy way to achieve this? I need plain javascript no jquery.
Thanks!
In general, a "callback" is a function which will be executed at a later time when an asynchronous process is completed.
So you might start by defining the function that should happen when the data is retrieved from the server (the "second" function, intuitively, but you should define it first because it's the business functionality you're looking to achieve and not just an implementation concern). Something as simple as:
var doSomethingWithTheData = function () {
// do, well, something with the data
};
This assumes that you have the data, which you don't yet. But the AJAX call will get that data. You can now use this function as your callback for the AJAX call. Taking the AJAX example from MDN, you might have this:
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = doSomethingWithTheData;
// perform the AJAX request
The httpRequest object will contain the response from the server after the AJAX call is executed and completed. (Remember that this happens asynchronously, so it won't contain the response on the immediate next line of code. It will at some later time which you don't control. Hence the need for the callback.)
I recommend walking through that full MDN article to get all the details, particularly on handling errors and such. But the data you're looking for (assuming nothing went wrong) would be in httpRequest.ResponseText. So, also assuming your variables are scoped to allow this (you can modify that as needed):
var doSomethingWithTheData = function () {
var data = httpRequest.ResponseText;
// do, well, something with the data
};
Excuse me, #David
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari,
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "http://myserver.mydomain/getMyUsersXMLUrl?user=pete";
httpRequest.open("GET", url, true); // next ajax to retrieve XML - File
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 4) { // response received
var response = httpRequest.responseText; // this should contain you url
httpRequest.open("GET", response, true); // next ajax to retrieve XML - File
// and the same as for the first request
}
}
If You just need to download a xml you dont need a callback . Just take a look at jquery and ajax. Retrieving a callback from a server is not possible . JSONP does deal with callbacks that are called by the server (actually they arent ) Butter you wont need it. I think you are messaging the xhttprequestobject
A callback function is simply a piece of executable code passed as a parameter to another piece of code. For example:
function first (arr, predicate) {
// no predicate supplied, return first element
if (!predicate) return arr[0];
for (var i = 0; i < arr.length; i++) {
// return first element satisfying predicate
if (predicate(arr[i])) return arr[i];
}
// no element satisfying predicate, return null
return null;
}
// second parameter is an anonymous function
// will alert 4, as it's the first element which will return true
alert(first([1, 2, 3, 4, 5, 6], function(n) { return n > 3; }));
Callbacks are useful for asynchronous tasks, or for library functions which need extra customization at runtime.

AJAX function that uses the POST method creates the following error. Error: returned status code 414 Request-URI Too Large

I'm using an AJAX function to transfer data to a PHP file. The data that I'm passing to the AJAX function is 17000 characters long. This is generally too long to transfer using the GET method, however one would think that the POST method would allow for such large variables to be be passed on.
Here's the AJAX function I'm using:
function ajaxFunction(id, datatypeString, pathToFileString, variable){
var myRequestObject = null;
document.getElementById(id).innerHTML = "<span>Started...</span>";
if (window.XMLHttpRequest)
{
myRequestObject = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
try
{
myRequestObject = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
myRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
myRequestObject.onreadystatechange = function()
{
document.getElementById(id).innerHTML = "<span>Wait server...</span>";
if(myRequestObject.readyState == 4)
{
if(myRequestObject.status == 200)
{
// process a document here
document.getElementById(id).innerHTML = "<span>Processing file...</span>"
if(datatypeString == "txt"){
//Injects code from a text file
document.getElementById(id).innerHTML = myRequestObject.responseText;
}
else if(datatypeString == "xml"){
//Injects code from an XML file
document.getElementById(id).innerHTML = myRequestObject.responseXML.documentElement.document.getElementsByTagName('title')[0].childNodes[0].nodeValue; // Inject the content into the div with the relevant id
}
else{
document.getElementById(id).innerHTML = "<span>Datatype exception occured</span>";
}
}
else
{
document.getElementById(id).innerHTML = "<span>Error: returned status code " + myRequestObject.status + " " + myRequestObject.statusText + "</span>";
}
}
};
myRequestObject.open("POST", pathToFileString+variable, true);
myRequestObject.send(null);
}
And this is the function call to that AJAX function:
ajaxFunction("myDiv", "txt", "processdata.php", "?data="+reallyLargeJavascriptVariable);
Also this is the error that I'm getting when the AJAX function is called:
Error: returned status code 414 Request-URI Too Large
I've looked around on Stackoverflow and other websites for a solution to this problem. However most answers come down to: "Use the POST method instead of the GET method to transfer the data."
However as you can see in the AJAX function, I'm already using the POST method.
So I'm not sure what's going on here and what to change in my code to solve this issue. I simply want to be able to pass very large variables to my function, but with this function that doesn't seem possible.
Given the error, the limitations of the URI seem to be causing the problem. However, I'm using the POST method and not the GET method, so why is the variable still passed via the URI? Since I am not using the GET method, but rather the POST method like many people suggested in other threads about this problem, I'm not sure why the URI is involved here and is seemingly causing a problem.
Apparently the URI is putting a limit on the size of the variable that I can transfer, however I'm using the POST method, so why is this error occurring and how can I adjust my AJAX function to make it work with the large variables that I want to transfer using AJAX?
When you're doing a POST you need to pass the POST data on the .send (you're currently passing null). You need to set a few header details, as well.
myRequestObject.open("POST", pathToFileString, true);
myRequestObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myRequestObject.setRequestHeader("Content-length", variable.length);
myRequestObject.send(variable);
If you're currently passing a question mark in the start of variable or end of the path go ahead and remove it.

XMLHttpRequest asynchronous not working, always returns status 0

Here's a sample XMLHttpRequest I cobbled together from w3schools
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var T="nothing";
xmlhttp=new XMLHttpRequest();
xmlhttp.overrideMimeType('text/plain'); // don't sc
xmlhttp.onreadystatechange=function()
{
alert ("rdystate: " + xmlhttp.readyState);
alert ("status: " + xmlhttp.status);
alert ("Text: " + xmlhttp.statusText);
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
T = xmlhttp.responseText;
}
}
xmlhttp.open("GET","SBL_PROBES.htm",true);
xmlhttp.send(null);
//T = xmlhttp.responseText;
alert(T);
}
</script>
</head>
<body>
<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">CHange Content</button>
</body>
</html>
XMLHttpRequest always returns a zero status.
Nothing shows up in Firefox's error console.
If I change the request to synchronous one by changing the line
xmlhttp.open("GET","SBL_PROBES.htm",true);
to
xmlhttp.open("GET","SBL_PROBES.htm",false);
and un-comment the line
//T = xmlhttp.responseText;
The text of the requested file is returned.
The HTM and the file reside in the same directory. If you try this you will need a file SBL_PROBES.htm there also, it's contents are irrelevant.
I'm using Firefox 3.6.22.
Could this be a cross domain problem? If so, why does it work as a synchronous request?
You can use a function inside the if statement. This function is executed when readystate changes to 4.
var handleResponse = function (status, response) {
alert(response)
}
var handleStateChange = function () {
switch (xmlhttp.readyState) {
case 0 : // UNINITIALIZED
case 1 : // LOADING
case 2 : // LOADED
case 3 : // INTERACTIVE
break;
case 4 : // COMPLETED
handleResponse(xmlhttp.status, xmlhttp.responseText);
break;
default: alert("error");
}
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=handleStateChange;
xmlhttp.open("GET","SBL_PROBES.htm",true);
xmlhttp.send(null);
Your old code did a asynchronous call and continued just with the alert Statement. T was empty at this time.
Ok, I'll explain a little bit how this whole thing works:
First we define two callback functions, which we call later in the request, named handleResponse and handleStateChange.
Afterwards we create a Object, which represents the XMLHttpRequest
var xmlhttp=new XMLHttpRequest();
This results in an Object as follows (simplyfied):
XMLHttpRequest { status=0, readyState=0, multipart=false, onreadystatechange=handleEvent()}
With the open(...) function call you set parameters for the request:
xmlhttp.open("GET","SBL_PROBES.htm",true);
This means, do a asynchronous GET Request to fetch the Page SBL_PROBES.htm
Then the send(...) function is called which fires the request itself.
We registered a callback function for the onreadystatechange, as you can imagine, this is actually an eventHandler. Each time the state changes this function is called. (It is the same as if you register a callback function to an onKeyUp Event in a form, this callback is triggered each time your key goes up :) )
The only case which is of interest for your problem is state 4. Therefor the handleRequest callback function is called only in state 4. At this time you Request has actually a result, and further a status. (Status means your webserver returned a status code 200=ok, 404=not found etc.)
That is not all the magic which is behind the ajax stuff, but should give you a simplified overview, what is actually happening behind the scenes.
It is important that you test this on a webserver, do not use file:// for testing.
If you need more in detail info, just let me know.
Status Zero happens for two reasons.
You are running off the file protocol.
Something is posting back the page when the Ajax request is active.
I believe you are seeing #2 here. SO you need to cancel the button click.
<button type="button" onclick="loadXMLDoc(); return false;">CHange Content</button>
In your code above that alert(T) will always say nothing when the request is asynchronous.
Its because async returns before the request returns. Synchronous requests return after the request returns.
Try manipulating your logic in here.
xmlhttp.onreadystatechange=function()
{
alert ("rdystate: " + xmlhttp.readyState);
alert ("status: " + xmlhttp.status);
alert ("Text: " + xmlhttp.statusText);
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
T = xmlhttp.responseText;
alert(T);
}
}
I've battled the problem of not getting a result when using asynchronous XMLHttpRequest open statement. Since this question is the first I found when using google, here is how I solved it:
If you use a button that is inside a form, make sure it is set to type="submit" and onclick="return myFunction()". And in myFunction(), make sure you return false, not true! By returning true from the function, you reload the page and the XML object disappears. If you return false, the XML request gets the time it needs to complete and the onreadystatechange function will be run.
Source: Flask Mailing List
I have now received the good response to this common problem. The response follow:
This is a very common problem when developing for the web. There's two ways around it.
The first is to use JSONP, which our API supports when you add a query parameter ("?callback=foo"). This should get you up and running right away and is great for development, but it isn't secure for production use since users get access to your API key.
The second (which is what we use on Forecast, and is the best method for production) is to set up a proxy server on your own domain which can make requests to Forecast on the user's behalf. This sidesteps the browser's same-origin policy, prevents users from accessing your API key (which can be stored server-side), and also allows you to make use of request caching, if desired. (Our favorite web server, NGINX, supports this out of the box and is really easy to configure. If you need some sample configurations, let us know!)

Javascript: XMLHttpRequest Task Switch

document.getElementById('contactButton').value = "Sending";
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
function stateChanged(){
if (xmlhttp.readyState==4) {
var response = xmlhttp.responseText;
if(response == "true"){
document.getElementById('contactButton').value = "Sent :)";
}
}
When running this javascript, contactButton never gets set to "Sending...". It hangs for one second, and then changes to "Sent :)".
I'm not real sure about the processing order of javascript, but it seems like it needs some sort of task switch to process the XMLHttpRequest().
This is obviously an abbreviated code, but I have several other javascript/css things I am trying to do before the xmlhttp. It seems like the xmlhttp just takes over when the request is sent.
Any ideas?
You're passing false to open, so it's running synchronously. That means it doesn't use the readyState and instead just delays until the request completes. If you want to do sync, it should be:
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
if(xmlhttp.status == 200)
{
var response = xmlhttp.responseText;
document.getElementById('contactButton').value = "Sent :)";
}
You should change to async to avoid hanging your script, and you will probably find it easier to use a JavaScript library.

Categories

Resources