AJAX calls - where does logic go? - javascript

This might not even be an AngularJS question and could just be an AJAX question. I'm new to the "developer" side of the frontend so bear with me.
When making an AJAX call to fetch JSON data, where does the logic behind what data is returned and viewed fall? In my mind, there would be a couple of possibilities and I want to understand which is the proper choice and why.
Let's use an example of searching and playing a Youtube video.
The logic could fall to the backend (controller), where the JSON is rendered based on some logic to give you a JSON file with exactly the right data. i.e. you search "cat videos" and when making an AJAX call, the JSON file you pull has been rendered to be only cat videos.
The opposite end would be that the Angular controller has the logic. This would imply that all data is called (cat videos along with everything else... music videos, funny videos, tutorials, and so on) and then sorted through on the client side. This, to me anyway, would be more inefficient / slow for the client, so doesn't seem to make sense. I suppose still might do some filtering of the data on the client side though. So, maybe a search for "cat videos" wouldn't return ALL videos, but definitely all cat videos and any filtering based on, say, # of views, video length, and so on would be done on the client side (vs. calling the database again for a "new" set of videos).
Not sure if this is accurate, but could you have logic in your factory to return only a portion of the data? However, I believe the entire JSON file would need to be rendered, but only portions would be returned. I guess depending on where the JSON file renders (i.e. backend or frontend) this could be similar to either option #1 or #2.
Or maybe I'm misunderstanding things entirely and the way this works is entirely different!
I'm basically looking to figure out how the scenarios of 1. user searches a term and results are shown, 2. user clicks a search result and now more detailed data of the result is on it's own page. And how this ends up working out. I'm looking for help with AngularJS, but I think this ultimately an AJAX question (single page app or not) more than anything.

There's a few critical concepts you may be confused about.
First. JSON is not a file, it's a format, more simply, a type of string. It's really good for collapsing arrays and storing address-value pairs, so a lot of data flies around in that format. Strictly speaking, they are JSON objects, but they're a lot like strings and arrays. It looks like this, if I remember correctly:
{ "name" : "john doe", "pet" : "dog", "hobby" : "parasailing" }
Second, AJAX is a request to the server, made from the client (the browser) after the original page has loaded. That is, you type in 'youtube.com' and the youtube server receives the request and sends a big pile of HTML back to your browser.
You watch your video, make a rating, and the browser doesn't reload the page but instead sends a separate request back to the youtube server with your rating. There's a parameter in the request that says "send it to ratingspage.php". This request is AJAX.
Now, the logic happens (server-side). ratingspage.php receives your request. It contacts the databases, updates or fails or whatever, and sends back a response to your browser. This response may be in JSON format.
Finally, your browser parses that response and updates the DOM (HTML document) as appropriate.
At this point, it's worth noting that if the logic happened on the client-side (browser), the user could see it - this is a security problem! So, sensitive operations should be carried out on the server side, where you can test and sanitize the request data.
In summary:
AJAX is separate from the initial load event.
Information sent is gathered from the client browser
Logic happens server-side
Logic can use whatever language the server understands (PHP, Java, Ruby, etc.)
Information is returned to the browser
Information sent and received may use JSON format
Everything client-side happens in Javascript
Here's a bare-bones ajax request (done in Javascript) with comments. This has no exception handling, state checking, or anything so don't use it! But it gives you the basic idea.
// Make a new request
var req = new XMLHttpRequest(); }
// Requests will have various states depending on whether they're processing,
// finished, error, etc. We'll assume everything went OK.
// We need to establish a handler before the request
// is sent so it knows what to do.
req.onreadystatechange = function() {
// Here's what the server sent back to the browser
alert(req.responseText);
}
// Using the GET method, set up some parameters
req.open("GET", "somelogicpage.php?blah=blee&bloo=bar", true);
// Send the request
req.send(null);
Server-side, somelogicpage.php may look like:
<?php
if ($_GET['blah'] != 'blee']) {
// This is the response text!
echo "Sorry, you need to blee when you blah.";
}
else {
// (or this)
echo "I'm ecstatic to report nothing is wrong!";
}
?>
Your alert(req.responseText) from the handler function in the previous Javascript will say whatever the PHP has dumped out.
So yes, you can use whatever portion of the request you like, and return whatever you like. Javascript kicks bleep.

Related

how to commuincate between php and JS?

I am new to web development and I am trying to build my first website.
I am having some troubles because web development is dependant on several programming languages like PHP and JS, and the most difficult part for me is to communicate between these languages.
For example, I am trying to create a function that compresses a folder and generate a download link to that new archive, this can be easily done by PHP. However, when the user clicks the zip button, I also wish to display a pop-up window that tells the user to wait while the folder is being compressed, and when the compression is done I want to change the text on that pop-up and display the download link, and this, of course, requires JS.
I've tried many solutions but none of them seemed perfect for me, and I feel like that these solutions are quick and dirty, which I don't want.
If there is a secret I do not know, please tell me about so I can finally work with these languages as if they are a single language.
Also, if you can help me with my current problem, I would be extra grateful.
I just want to know how to construct a form that can call the JS function that displays the pop-up, then calls the PHP Zip_Folder function, and once the PHP function is done, I want to display the download link on the pop-up window.
This is my form code: (It only calls the javascript function that displays the pop-up)
<input type = 'button' onclick = 'Show_PopUP(\"Folder_to_zip\")' value = 'Download Folder'>
And this is the Show_PopUP function code:
function Show_PopUP(folder) {
var e = document.getElementById('Folder_Download_PopUp');
if(e.style.display == 'block')
e.style.display = 'none';
else {
e.style.display = 'block';}}
I already have the PHP function that compresses and generate a download link for the archive, so what I need now is a way to call it after the pop-up is displayed, and a way to print the download link on the pop-up once the function is done.
This might not be the best approach since I am a beginner, so if you have suggestions on how to get my task done without this complexity, I would be very happy.
Sorry if my question is too long, and thanks in advance for your help.
What you need to do is use these things called XHRs, or XMLHttpRequest (Google it), from within JavaScript to php, which basically is kind of like an invisible browser going to the php page behind the scenes and "loading" whatever the php page gives back, only this is all happening within JavaScript itself, so you can read that this "invisible page" loaded, which is from php, and do stuff with that, without actually refreshing the page. This process is known as AJAX (look it up)
What you can do is, when you set up this "invisible page", you can also send certain kinds of information along with it that the php page can read, and when it's done the php page can echo something back to the invisible page, which can then be read with JavaScript. This easy you can communicate between php and JavaScript, by sending certain values, in JavaScript, along with this invisible page, and waiting for php to echo something back to it, then reading that with JavaScript
So how do we actually do this?
First on the JavaScript side, we need to make this "invisible page", which is really not technically a page, it just does the sane thing as what is done to display any other web page, which is technically called a "request" since it's like asking the server for some data, it's basically "requesting" it, then when the server echoes something back, that's called he "response" to what was requested
So to make this new request in JavaScript we can do the following
var asking= new XMLHttpRequest ()
now that it as if an invisible page was created, but not yet navigated to anything, but we have to now metaphorically "enter in the URL" to this invisible page (without actually "navigating" to it yet) to do that we do
asking.open("GET", "pathToPHPpage.php?hi=there")
So the first part is called "GET" because we want to simply get a response back, without actually sending anything (if we were sending a file though, we would instead use "POST" then put the file date in the next step), then we enter in the URL to the php page that you want to get. If it's the same as the JavaScript page just put location.href instead, but it's important to add at least something to the end of the URL, notice the "?hi=there", you can call it anything, but it's important to have a question mark immediately following the .php page, then the name of something (in this case"hi") followed by it's value (in this case "there"), because the php page is able to read that, and give a different response back depending on what it says
Ok so now we have to actually "send" that request to the server, which is like metaphorically "navigating" to the URL on the invisible page, to do that
asking.send()
(And if you put "POST" before, you can add the date you want to send in between the parenthesis, usually in the form of a string but it can be different depending on the data, look it up for more reference)
Now, before we continue in the JS side, let's quickly switch over to PHP (doesn't have to be in this order though) to see what happened
We need to listen for any "requests" on the php page, that contain the name "hi" (since that's what we at the end of the URL before), to do that, around the top of PHP (technically anywhere in php though) we do
$isHi = $_GET["hi"];
if(isset ($isHi)) {
//Do some php code
echo "hi back!".$isHi;
}
Basically we just looked for the *hi" name in our "GET" request that was sent to PHP, we checked if it is "set", meaning not nulll, then we echoed some message back to JS, now let's listen for that message on the JavaScript side
Back to JS, after the .send line (or before), we need to listen for when the page echoes back.
To do that we check if it successfully loaded, because sometimes there can be errors, so let's do
asking.onreadstatechange= function () {
if(asking.readyState == 4 && asking.status==200) {
alert(asking.responseText)
} else alert("ooh something happened")
}
Now we have access to the response the php code gave us
You can extend this to other forms of communication, let me know if you have any questions

$_POST responding back to webpage, and how to deal with data on a dynamic web page [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am fairly new to php so this functionality stumps me, I'll give you a picture for context. layout of application for reference image
So I can query my data base and set each bit of data to an individual variable (maybe not the best way for this situation?)
But I don't know how to $_post that data (in variable form... :) probably bad idea, and I'll have to set the data as variables where ever I work with the formulas and only send information over ajax) back to the displayed page (note: I don't want my page to ever have to refresh)
And I foresee another problem, and its due to lack of knowledge and google failing to answer my questions, how can I have php Run my algorithms and keep the original data in the page every time my users change one field on the page, I want them to all run on the server and not in browser so I'm planing on having ajax send all the data including the changed data to a php file every time they change something and have it reset the information on the page after it runs its formulas. i have been studying $_post and get and request ect. and not been able to mentally layout how the transmission of data would be the most efficient and easiest to work with.
Sorry for the ramble, I hope for some constructive criticism, solutions and explanations to a newbie at php and thank you for any and all help.
HI it works like this in jQuery
$.post('url', {input}, function(data){
});
The javascript will make a web request, same as if you put url in the browser, right ( if it's $.get that is, obviously we cant send post data using the browser url bar, however you could go to the page just without the post data ). Now because it's AJAX anything returned goes into data. It's asynchronous, which means your JS wont wait for the request, for example if you put
$.post('url', {input}, function(data){
});
alert(data.result);
It wont work, for 2 reasons, one is scope ( data is a function input parameter not accessible outside the function ). The other is that the alert will fire before the post completes, even though it is written after the $.post request. Because of this, you have to use the data in the call back function.
Now on PHP side where ever that url is it gets ran just like you went there normally. Essentially there is no difference to the server its AJAX or a browser request. It's just like submitting a form. The interesting things you can do is return your data as JSON. by using the application JSON header and by using json_encode() in PHP. This is essentially JavaScript String Object notation. ( not sure if I remember that right ) but that is what it is.
There is no magic in the request. Most people don't really understand that anything the server returns is only text. Be it a PDF file, a JPG, a webpage, anything its only text. JSON allows you to keep the structure of your data, such as an array. It's a special format of text that JavaScript understands as object and arrays.
I explained this to one of my Junior Developers the other day. That if you set the correct headers you can generate CSS files with PHP, images etc. Because it's all just Text. The web is very simple. You only have get and post for requests and text as a response. That's it for the most part.
Anyway,
Right, so now in PHP ( for a quick example )
header('Content-Type: application/json');
$a = array('one'=>1);
echo json_encode( $a );
With json_encode() it becomes ( this is the response sent back from the server )
'{one:1}'
And in JS on the client side ( inside the $.post callback ) its
data.one;
We can take this data in the callback then you can just use some basic jQuery to replace the values of inputs or content of HTML tags with your returned data.
$('#input').val(data);
$('#htmlElement').text(data); // or data.one - whatever you had in php array keys.
Make sense? Above, we take a PHP array use json_encode(), to make it a JSON string, and then (with the correct header ) we can access that normally in JS using its dot syntax. Remember what I said above about only returning text from the sever, this is why we have to convert it to a JSON string. The dot in JS is like the -> in PHP. You could also use data['one'] which is even more like PHP, but that is technically not the correct way if you know what one is.
The process flow is also simple, just like we only have post get, and text. We only can make requests from the client and responses from the server. So it always goes
Client Request -> Sever Response -> Client receives response.
We cannot for example call the Client from the sever.
Sever Call-> Client receives
This doesn't work without things like NODE.js or a socket server.
For reference ( about json responses )
Returning JSON from a PHP Script

Creating a smart remote upload script with jQuery AJAX and PHP

I'm currently creating an image hosting script and so far so good. I've used several plugins to create the local uploading process with drag & drog + AJAX which works totally fine. Now I've moved to the part where I need to create the remote uploading process with jQuery AJAX and a PHP script to handle the whole thing.
How it's gonna work
My thought are like this: There is a big box in the middle of the page that accepts the URLs to be remote uploaded. Once valid URL(s) are passed into the text area, they will be immediately sent to the server side script via jQuery AJAX. It's bound with a keyup event.
This is how it looks like: http://i.imgur.com/NhkLKii.png.
The "HERE COME THE URLS" part is already a text area - So that part's already done.
Where I need help
The issue with this whole situation is: Once there are valid URLs pasted into the text area, those must be immediately be converted to some sort of box which also includes an uploading progress. Something that looks like this (copied from the local uploading part): http://i.imgur.com/q7RyDmb.png
It was easy implement the progress indicator for the local uploading, since it was a feature offered by the plugin I've used, but I don't know how to indicate the progress of remote uploading, which is totally being made from scratch.
So this is how I've imagined the logic to flow:
User pastes some URLs into the text area
There is a client-side check to validate the pasted URLs
Validated URLs are send to upload.php on keyup (?)
URLs are being processed
While the upload goes on, we show the users the progress in the knob (?)
PHP script finishes the process and returns back the uploaded URLs
I update the page in the AJAX success callback to display the uploaded files
So, the two process flows marked with (?) are unclear to me - I don't know how to achieve those...
What I have tried
Well, I didn't just come here and ask you to do everything for me, but I've come across a dead end and I don't know how to continue. What I've done so far is collect the URLs from the text area, and if there are multiple URLs separated by a line break (\n), I simply use split to get an array of pasted text and then use another function inside the loop to validate if they are URLs. If there is no line break detected inside the text area value, then I simply check the one line that was provided. On each case, I send the whole text area to the PHP script, because I don't know how to get rid of the invalid URLs in jQuery. I've created a function called debug() in PHP which stores anything into a debug.log file and this is what I'm getting (in one try) when I paste something into the text area:
https://www.google.com/https://www.google.com/
I paste https://www.google.com/ once in the text area, but it gets logged twice in the PHP side and I can't determine why.
This is how my jQuery looks like:
// Remote upload
var char_start = 10;
var index = 0;
var urls = $('.remote-area');
var val_ary = [];
urls.keyup(function(){
if (urls.val().length >= char_start)
{
var has_lbrs = /\r|\n/i.test(urls.val());
val_ary = urls.val().split('\n');
if (has_lbrs)
{
for (var i = 0; i < val_ary.length; i++)
{
if (!validate_url(val_ary[i]))
{
val_ary.splice(i, 1);
continue;
}
}
$.ajax({
type: 'POST',
url: 'upload.php',
data: {
upload_type: 'remote', // Used to determine the upload type in PHP
urls: val_ary, // Sending the whole array here
},
});
}
else
{
if (!validate_url(urls.val()))
{
// Display an error here
return;
}
$.ajax({
type: 'POST',
url: 'upload.php',
data: {
upload_type: 'remote', // Used to determine the upload type in PHP
urls: urls.val(), // Sending what's in the text area
},
});
}
}
});
The questions
So the final questions are:
How do I send my information correctly to the PHP script, only valid URLs and have them kind of "process-able" in my PHP script.
How do I indicate the progress of the upload?
If I was somewhere unclear during my question, please let me know, I'll try to reexplain.
Thank you.
Updates
09/12/2013
I think I have managed to solve the double-sending issue where my AJAX would send the same information twice to the PHP script. What I did was code in a delay anonymous function that sends the text area content to the PHP script after an user stops typing for 2 seconds. Once the user stops typing again, the timer resets and a new AJAX request will be made. So, I'm assuming that this issue has been solved. I'll come back to it if anything strange occurs.
Now I'm still left with the progress indicators part. I'd appreciate your thoughts on that one.
My new code: http://pastebin.com/SaFSLeE9
What you're looking for in terms of communicating progress back and forth is "pushing". That refers to the technique of server sending data to the client, rather than the other way around, which is the standard HTTP way of doing things.
You've got plenty of options available, as described in the explanatory Wikipedia article, though perhaps more relevant to this topic would be Comet. What happens is you trigger and $.ajax call just like the one you have now, but you set a very long timeout. That essentially gives the server a "channel" to send data back to the page whenever it's available.
So what you need is a .php on the server that is capable of handling long polling and will send data back to the page as the upload progress changes (probably in array form for multiple uploads). This article should get you started with some jQuery code. Just remember that this request doesn't go to upload.php. This request goes to a different script that deals solely with upload percentages and only returns data when that is available, it doesn't return immediately as all others scripts - the Ajax will happily wait for the data.
Also, don't separate your code like that with has_lbrs. One line or many are not distinct cases, one line is just an edge case of many lines. You're duplicating the code unnecessarily. What does the else case do that would break in the general case? Further, the "error handling" in the else case is misleading. The only error reporting you do is if there is only one line and it's wrong. What if you have two lines and they're both wrong? Your code will happily send an empty array to upload.php.
This is why I think you shouldn't separate your code like that, because then you'll split logic and not even notice it.
In my opinoin, the best way is to call your cURL script with ajax and use it to upload your files on remote server. You need ajax.js, curl.php, index.php (whatever name you want) on your app server. And image.php, class.image.php (whatever name you want) on your remote server.
Steps that I did for my app
1) I am going to upload an image from my index.php file. It will call curl.php file using ajax.js and the cURL file will check file's extension and all (for your app's security, make sure what you want to allow users to upload).
2) Now the curl file will upload the file to your pre defined temporary folder with the default file name.
3) Now if move_uploaded_file function (which I used in my script) run successfully, you can call your cURL function to send your data as post on your remote server, where image file will receive posts and will process further. You can keep your class in image.php or you can create two PHP files on your remote server, as you want.
4) Now in your class file, you should check file once again that it is image file (and whatever you want to allow) or not for better security. If file is good, process to rename it and add file into folder if you want to.
5) Add file's new name and folder name into your database by using remote database connection. So, cURL will show you result on the same page.
Now, why cURL? I prefer cURL because, you can add secret key or API for your communication to make it more secure, with if else conditions. Your remote server file which is going to receive all posts, will check if API == 'yourKey' then will process other wise it wont process and nobody will be able to send images on your server with bots and all.
I don't know that my answer is going to help you or not, probably my method is lengthy or not good for your app, but try to Google about cURL and you will understand what I am trying to say. Hope you like it and understood it. If any doubt, you can ask me any time.

Asynchronous Servlet Client, Server push

Hello guys i want to process some server pushes. I have an asynchronous servlet processing something, pushing it to the client and then it processes something else and pushes it again to the client (same connection). The servet just returns data (Json in this case, but that does not really mather) nothing more.
So my problem is the client. How do i build a client for that? If i make an ajax request with JQuery for example how can i react on the data that comes after the first response?
To make it more clear what i want here is a comparison : With websockets i have the method onmesssage.
websocket ws = new WebSocket("ws://myserver.com");
ws.onmessage = function(event)
{
var x = event.data
.... // some other code here
}
So all i want is a onmessage Method :). I guess it is not that easy as it is with websockets but maybe someone has an idea.
Greetings Aleks
You can have your server generate a response which is loaded into an hidden iframe by the client. The generated response would contain occasional JavaScript statements which call to the "outside" (the containing document). You can get your hands on the containing document using parent.
But please not that this technique is pretty hackish (at least it seems to me). You might want to re-consider just using the XMLHttpRequest, especially because it gives you simple and robust error handling. You can just do more requests (instead of appending to an "old" response on the server side). This will probably introduce additional lag, but that iframe trick is really troublesome in practice.

Can Django/Javascript handle conditional "Ajax" responses to HTTP POST requests?

How do I design a Django/Javascript application to provide for conditional Ajax responses to conventional HTTP requests?
On the server, I have a custom-built Form object. When the browser POSTS the form's data, the server checks the submitted data against existing data and rules (eg, if the form adds some entity to a database, does that entity already exist in the database?). If the data passes, the server saves, generates an ID number and adds it to the form's data, and passes the form and data back to the browser.
if request.method == 'POST':
formClass = form_code.getCustomForm()
thisForm = formClass(data=request.POST)
if thisForm.isvalid():
saveCheck = thisForm.saveData()
t = loader.get_template("CustomerForm.html")
c = Context({ 'expectedFormObj': thisForm })
(Note that my custom logic checking is in saveData() and is separate from the html validation done by isvalid().)
So far, standard Django (I hope). But if the data doesn't pass, I want to send a message to the browser. I suppose saveData() could put the message in an attribute of the form, and the template could check for that attribute, embed its data as javascript variable and include a javascript function to display the message. But passing all that form html back, just to add one message, seems inelegant (as does the standard Django form submission process, but never mind). In that case I'd like to just pass back the message.
Now I suppose I could tie a Javascript function to the html form's onsubmit event, and have that issue an XMLHttpRequest, and have the server respond to that based on the output of the saveData() call. But then the browser has two requests to the server outstanding (POST and XHR). Maybe a successful saveData() would rewrite the whole page and erase any potential for conflict. But I'd also have to get the server to sequence its response to the XHR to follow the response to the POST, and figure out how to communicate the saveData outcome to the response to the XHR. I suppose that is doable, even without the thread programming I don't know, but it seems messy.
I speculate that I might use javascript to make the browser's response conditional to something in the response to the POST request (either rewrite the whole page, or just display a message). But I suspect that the page's javascript hands control over the browser with the POST request, and that any response to the POST would just rewrite the page.
So can I design a process to pass back the whole form only if the server-side saveData() works, and a message that is displayed without rewriting the entire form if saveData() doesn't? If so, how?
Although you can arrange for your views to examine the request data to decide if the response should be an AJAXish or plain HTML, I don't really recommend it. Put AJAX request handlers in a separate URL structure, for instance all your regular html views have urls like /foo/bar and a corresponding api call for the same info would be /ajax/foo/bar.
Since most views will examine the request data, then do some processing, then create a python dictionary and pass that to the template engine, you can factor out the common parts to make this a little easier. the first few steps could be a generic sort of function that just returns the python dictionary, and then actual responses are composed by wrapping the handler functions in a template renderer or json encoder.
My usual workflow is to initially assume that the client has no javascript, (which is still a valid assumption; many mobile browsers have no JS) and implement the app as static GET and POST handlers. From there I start looking for the places where my app can benefit from a little client side scripting. For instance I'll usually redesign the forms to submit via AJAX type calls without reloading a page. These will not send their requests to the same URL/django view as the plain html form version would, since the response needs to be a simple success message in plain text or html fragment.
Similarly, getting data from the server is also redesigned to respond with a concise JSoN document to be processed into the page on the client. This also would be a separate URL/django view as the corresponding plain html for that resource.
When dealing with AJAX, I use this:
from django.utils import simplejson
...
status = simplejson.dumps({'status': "success"})
return HttpResponse(status, mimetype="application/json")
Then, AJAX (jQuery) can do what it wants based on the return value of 'status'.
I'm not sure exactly what you want with regards to forms. If you want an easier, and better form experience, I suggest checking out uni-form. Pinax has a good implementation of this in their voting app.
FYI, this isn't an answer...but it might help you think about it a different way
Here's the problem I'm running into...Google App Engine + jQuery Ajax = 405 Method Not Allowed.
So basically I get the thing to work using the outlined code, then I can't make the AJAX request :(.

Categories