O'Reilly Forums: ?callback=Callbackfunction - O'Reilly Forums

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

?callback=Callbackfunction parsing the above

#1 User is offline   tomtom505 

  • New Member
  • Pip
  • Group: Members
  • Posts: 8
  • Joined: 01-July 12

Posted 10 August 2012 - 06:23 AM

HI Beth or any other helpful soul,

I typically work on both the server side and the browser/phone client side of AJAX requests etc. So typically I write PHP code on the server to handle a XMLHttpRequest . The request can send variables in the POST or GET. The server can then extract this in for from the super globals and then echo back the response in json or xml. When parameters are included in the url how does the server side app handle that?

For example how does the server side get it's hands on the call back function's name? How does it then call that function? Is the only way of passing info to that callback via the response? How does one pack up the response? What is the url that the server script actually resides at? Perhaps the browser parses the url before packs it up? You would have told us that though, wouldn't you? What is actually going on?

Come to think of it I don't realy understand how this works in a XMLHttpRequest. How does the browser or ios know the the response has been rec'd? Does the browser keep track of the call back function's name? or the annomous function's position?

Can you point me to a reference source for this info? What is your favorite client language? Learning Ruby is next on my to do list but should it be?

PS I enjoyed the HTML5 book. Sorry it ended.
0

#2 User is offline   tomtom505 

  • New Member
  • Pip
  • Group: Members
  • Posts: 8
  • Joined: 01-July 12

Posted 10 August 2012 - 08:02 AM

To whomever is interested.

Apparently the callback is a key in a key value pair packed up in the super global GET array so we jsut need to look for it in the GET parameter nad then behave accordingly. We can even pass data as arguments to the function. I found the following PHP code on line at stack overflow
http://forums.oreill...llbackfunction. All of this makes the "Zen Moment " in the book seem trivially obvious. Perhaps a bit of server side explanation would be nice.


<?php

$data = '{}'; // json string

if(array_key_exists('callback', $_GET)){

header('Content-Type: text/javascript; charset=utf8');
header('Access-Control-Allow-Origin: http://www.example.com/');
header('Access-Control-Max-Age: 3628800');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');

$callback = $_GET['callback'];
echo $callback.'('.$data.');';

}else{
// normal JSON string
header('Content-Type: application/json; charset=utf8');

echo $data;
}


?>

There is a Python example there as well.

hmm... perhaps python should be next?
Coursera has a class for free.

This clearly shows a good way to do this but it goes around the request.response property. I am curious to find out how that property is set on the server side in an XMLHTTPRequest. Does the script at the url in the XMLHttpRequest explicitly set this property? How does it get it's hands on it?? I cannot find this on line. All thr examples deal with the responseText or responseXML after it is set. I cannot find info re setting the text.

So i will have to dig a bit more if I want to use the response. Not sure there is an advantage to it but I need to know this!
0

#3 User is offline   tomtom505 

  • New Member
  • Pip
  • Group: Members
  • Posts: 8
  • Joined: 01-July 12

Posted 10 August 2012 - 08:34 AM

Hi Beth
If you have been reading any of this post perhaps you could help me by explaining how the data in the file at the url localhost/gumball/sales.josn gets into the request .responseText? (page 233) If the data was xml whould it be in request.responseXML? who put it there? Does whoever did this use the file extension to determine if it is xml? Is the who the browser? Do echo-ed PHP strings go here? If the browser does this then what does it recieve from the server? A stream of data? Is this part head first networking? Why is this so mysterious?
0

#4 User is offline   tomtom505 

  • New Member
  • Pip
  • Group: Members
  • Posts: 8
  • Joined: 01-July 12

Posted 10 August 2012 - 10:27 AM

Hi Beth et al,
I think I have figured out that the XMLHttpRequest must set its responseText to whatever is in the file at the url, perhaps skipping text in scripts. I am not sure if this is true but it seems to be based on experiments I have done. I would love to know if this is correct. Also, the upshot seems to be that one cannot set the value of the responseText. Again I do not know this for certain but it fits with what I have figured out. So it seems that the responseText is pretty limited in it's usefulness making the script with callback methodology even more important. Still hoping for some input
0

#5 User is offline   Beth Robson 

  • Veteran Member
  • PipPipPipPipPipPipPipPipPip
  • Group: O'Reilly Employee
  • Posts: 375
  • Joined: 17-September 08
  • Gender:Female
  • Location:Seattle, WA
  • Interests:I am interested in computer science, the Web, social media and the internet, Mac development, and adult learning.

Posted 10 August 2012 - 06:47 PM

Hi, Sorry about my delayed response, I am just now seeing this thread!

When JavaScript sends a POST or GET via XMLHttpRequest to a server, the server just sees the request - it really has no idea whether it's coming from XMLHttpRequest or you typing a URL into a browser or submitting a form. In PHP, you'll get the data from the $_GET or $_POST just like normal.

Likewise, the server knows *nothing* about the XMLHttpRequest object, your callback, or anything else in your JavaScript. All it's doing is responding to the GET/POST with data using an HTTP response. It does it's thing (in the case of a PHP script, simply "echo"ing data to "output" which in this case, is the HTTP response...

From the JavaScript's side, your browser is sitting there waiting for a response to the request you just sent. (And since XMLHttpRequest requests are usually sent asynchronously, your browser is also doing other things potentially). When your browser gets a response, it puts it into a property in the XMLHttpRequest object which your JavaScript has created! So yes, the browser is keeping track of that for you. Behind the scenes it knows that this request object sent that request to that server, and when it gets a response to that particular request, it will put it into the *same* request object (as the response). This is a tricky part to understand: the XMLHttpRequest object is used for both the request and the response.

Regarding your second question about resonseText vs. responseXML: the browser puts the response there. Which one of those two properties it uses is dependent on the "mime type" of the response from the server. If the mime type is plain text or json, then it goes into responseText. If it's xml, it goes into responseXML. You need to know in advance which one to expect (or you need to test both and respond appropriately in your JavaScript, but in general, you'll know in advance).

What gets put into responseText (or responseXML) is whatever the server responds with. Hopefully the server responds with something valid that your program can make sense of. If not, then you need to be able to handle it.

Keep in mind this is *VERY* different from how JSONP works. With JSONP we are not using a built-in browser object, XMLHttpRequest to send/receive the request. We are building our own GET by creating a URL and requesting that URL via a script element. And yes, we are sending the callback in that URL. In that case, the browser can call your callback because the server's response uses the name of the callback in its response. And because of the way that <script> works, when the browser loads that response, the JavaScript is executed. Again, *very* different from XMLHttpRequest.

In both cases, it's important that you make requests to 1) servers you trust and 2) servers you know what you're expecting from (e.g. well known web services, like Twitter), for security.

I hope this helps!!

Elisabeth
Elisabeth Robson
Co-founder, WickedlySmart.com
Author: Head First JavaScript Programming, Head First HTML5 Programming, Head First HTML and CSS, Head First Design Patterns
0

#6 User is offline   Beth Robson 

  • Veteran Member
  • PipPipPipPipPipPipPipPipPip
  • Group: O'Reilly Employee
  • Posts: 375
  • Joined: 17-September 08
  • Gender:Female
  • Location:Seattle, WA
  • Interests:I am interested in computer science, the Web, social media and the internet, Mac development, and adult learning.

Posted 10 August 2012 - 06:48 PM

p.s. Rails, PHP or Python are all good next steps for server side scripting!
Elisabeth Robson
Co-founder, WickedlySmart.com
Author: Head First JavaScript Programming, Head First HTML5 Programming, Head First HTML and CSS, Head First Design Patterns
0

#7 User is offline   tomtom505 

  • New Member
  • Pip
  • Group: Members
  • Posts: 8
  • Joined: 01-July 12

Posted 11 August 2012 - 12:46 PM

Thank you. That was all as I had surmised but I am so much more comfortable having it confirmed. That was great of you to put so much effort into the response. I already use PHP extensively but I hear so much about rails. I will try rails and or python next.

I have used the jsonp approach and it works except I find I have to handle the jsonp object as an array in stead of an object. Not sure why. I do know that there are not any associative arrays in javascript but I am basically just using code like

$dbc = mysqli_connect(kDB_Host, kDB_User, kDB_Password, kDB_Name);
$query = "SELECT movies.movieTitle FROM ShopSearchDemoMovies AS movies ".
"INNER JOIN ShopSearchDemoAuthorizedMoviesForUser AS authMovies ON authMovies.movieFK = movies.moviePK ".
"INNER JOIN ShopSearchDemoUsers AS users ON authMovies.userFK = users.userPK ";
$data = mysqli_query($dbc, $query);
//create array of movie titles
$movies = array();
$i=0;
while ($row = mysqli_fetch_array($data))
{
$movies[$i] = $row['movieTitle'];
}
$data = json_encode($movies);

if(array_key_exists('callback', $_GET))
{
header('Content-Type: text/javascript; charset=utf8');
//header('Access-Control-Allow-Origin: http://www.tsquaredapps.com/');
//header('Access-Control-Max-Age: 3628800');
//header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
$callback = $_GET['callback'];
echo $callback.'('.$data.');';
I realize this is a bit much to look over but the esscence is
1)mysqli select query on database connection

2)iterate over rows to create an array
while ($row = mysqli_fetch_array($data))
{
$movies[$i] = $row['movieTitle'];
}
3) json_encode array
$data = json_encode($movies);
echo back function call
0

#8 User is offline   tomtom505 

  • New Member
  • Pip
  • Group: Members
  • Posts: 8
  • Joined: 01-July 12

Posted 11 August 2012 - 01:04 PM

oops i sent email prematurely - hit some command sequence

Any way the end should have been

3) json_encode array
$data = json_encode($movies);
4) get callback name
$callback = $_GET['callback'];
5) echo back function call
echo $callback.'('.$data.');';
Although this works and the call back gets called as expected. The java script function treats the jsonp object as an array


function setMovieTitles(movies)
{
//call back function for ShopSearchDemoMovieTitles.php
movieTitles = movies;
playlist = new Array();
var moviesString = "";
var video = document.getElementById("video");
var linksDiv = document.getElementById("linksDiv");
for (var i = 0; i<movies.length; i++)
{
moviesString = moviesString + movies[i] +", ";
playlist[i] = baseURL +"Videos/"+ movies[i] + getFormatExtension();
var movieLink = document.createElement("a");
var br = document.createElement("br");
movieLink.setAttribute("class","movieLink");
movieLink.setAttribute("id",playlist[i]);
movieLink.onclick = playVideo;
movieLink.innerHTML = movies[i];
linksDiv.appendChild(br);
linksDiv.appendChild(movieLink);
}
}

Don't waste your time on the bult of this. The for loop is treating movies as an array. I checked in the debugger in safari to verify this and then just went with it.

Also my anchor elements inserted do not get styled. The CSS is


a:link{
font-size: 125%;
color: black;
}
a:visited{
font-size: 125%;
color: #888888;
}

Ths CSS does work for anchor elements placed in the page originally but not the ones apended by java script. They just get treated like plain text.

Anyway regardless of whether you have time to respond to this I appreciate your previous response and your books. The nice thing about HTML 5 book and the recent jQuery head first book is that they both did not try to isolate technolgies from one another. I think that this is essential to understanding how the whole enchilada works. Not knowing haw it all fits together leaves way to many mysterious black boxes. To really be a developer one needs to understand all the moving parts.

cheers
0

#9 User is offline   tomtom505 

  • New Member
  • Pip
  • Group: Members
  • Posts: 8
  • Joined: 01-July 12

Posted 11 August 2012 - 01:31 PM

Hi Beth,

I figured out the CSS issue so don't waste your time on what I am sure is an obvious error to you.
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users