Interworkings of php/javascript/json/ajax [closed] - php

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
This question may be conceptual (not programming oriented) but i feel i need to understand how these work together in order to program correctly.
what I know:
1) php is a programming language which can be used with html
2) javascript is called from html
3) json is used to convert php array to javascript array
4) ajax is a way to call json
so my questions are...
1) which has the priority? i.e. is javascript codes called before php?
2) when you have ajax in javascript requesting for json.. when is that called? is that after php?
I am confused how things work with each other like in steps which goes first and last.

I'm going to correct all the inaccuracies in what you've said. Looks like you're self-taught (isn't a bad thing, by the way).
HTML is a mark-up language.
PHP is a server-side processing language that can (if needed) output HTML
JavaScript is a client-side processing language that can (if needed) modify the document object model (the HTML document, if you prefer, though not strictly accurate)
JSON is a mark-up language. Typically used to transfer data.
AJAX is a JavaScript technique commonly used to trigger server-side processes from the client without refreshing the page.
So, PHP "builds" your HTML, and JavaScript allows you to enrich it. AJAX is a subset of JS functions (xmlHTTPRequest & co), which allows you to ping PHP pages (or others!) to get data back from them. If they output JSON, you can parse this JSON object to get an object back.
Typical example:
testpage.html
<!doctype html>
<head>
<title>Test page</title>
</head>
<body>
<textarea id="test""></textarea><button id="mybtn">Test</button>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#mybtn").click(function() {
$.ajax({
url: "page.php",
type: "GET",
dataType: "json",
success: function(d) {
$("#test").text(d.randomNumber);
}
});
return false;
});
});
</script>
</body>
</html>
page.php
<?php echo json_encode(array("randomNumber" => rand(1,10))); ?>
If you run it (I've taken the freedom of hosting it at http://www.sebrenauld.co.uk/testpage.html ), when you click the button, you'll see a random number in the textarea.
What actually happens when you click that button?
When you click the button, your browser fires a request to /page.php via GET. This request returns a JSON object, which jQuery automatically interprets as the d object. jQuery then fires the success callback, which updates the form. Voila!
Any questions, don't hesitate. I'm here to help.

PHP is a dynamic programming language which can produce HTML - it runs on the server
JavaScript is a dynamic programming language which runs on the client (browser)
JSON is JavaScript Object Notation and isn't specific to PHP, though it can be used to print PHP arrays into JavaScript arrays using PHP.
AJAX is a way to make asynchronous requests and receive responses in JavaScript.
PHP must produce the HTML containing the tags required to invoke JavaScript, so it comes first.
PHP is invoked at the start when producing the page. An AJAX request can call a URL where PHP code resides. JavaScript on the orignal page can be running while PHP is producing the response.

Here's a broad overview of how these pieces fit together:
Server vs Client
To understand all the pieces, you need to understand the difference between the server and the client.
When you open a webpage by typing an address into your browser's address bar, clicking a link, etc, your web browser sends a request to another computer sitting somewhere else where the web page you want is stored. It is essentially asking that computer for the webpage, and that computer gets to decide what you get back. We refer to this computer as the "server", since it is "serving" you the webpage.
Once the server does whatever processing it needs to do, it sends the page back to your browser. Your browser then interprets the data you get back and displays it to you in a pretty way (assuming the web designer made it pretty). We refer to your browser as the "client".
Now for the specific technologies you asked about:
PHP
PHP is referred to as a "server-side" language. This means it runs on the server to help produce the webpage that will be sent back to your browser. It runs before your browser ever sees it.
JavaScript
JavaScript is called a "client-side" language. It runs within your browser, changing things, loading new information, making the page interactive. It never runs until the page is loaded (sometimes as the page is loading, but never until your broswer begins interpreting the page). An important thing to remember is that PHP can generate JavaScript within the HTML it produces, since that's where JavaScript lives anyway.
JSON
JSON is an acronym standing for "JavaScript Object Notation". JSON is not a language; it is an element of JavaScript. JSON doesn't do anything; it is a way to represent data in an organized, useful way.
PHP can "print" a JSON object within a block of JavaScript as a way of passing data directly to the client in a useful format. PHP objects can be "dumped" to JSON using a function such as json_encode(), which, generally speaking, returns a JSON representation of a complex array or object.
Note that JSON is much more than just an array. Please look into this more.
AJAX
AJAX is another acronym standing for "Asynchronous JavaScript And XML". (It's a somewhat misleading name, since XML is not necessarily a part of the process and is becoming increasingly rare these days, so don't worry about that part of the name.)
In short, AJAX is also not a language in and of itself; it's more of a technique within JavaScript of requesting more information/data from the server without having to reload the whole webpage.
One of the more common uses of AJAX is, like you said, to request a JSON object from the server. This is by no means the only use for AJAX, but it is a common one, especially within interactive applications.
Priority
Short answer: PHP comes before JavaScript, since it lives on the server; JSON and AJAX are elements of the JavaScript language, so they happen within JavaScript, in the browser.
Whenever your JavaScript makes an AJAX call to request some JSON from the server, there's a good change that PHP will be the language used to interpret the request and send the JSON back to your browser.
--
Hopefully that helps. You should check out resources like Zend and the Mozilla Developer Network. Here are some good places to start:
PHP
JavaScript
JSON
AJAX

Related

How to pass value from html file to php file

I am new to jQuery,Ajax and all, I don't know to pass a value of html file to php file.
For Eg:
my html file as
<html>
<script>
$(document).ready(function(){
$(".teachers_but").click(function(){
//alert('teacher');
var id=0;
alert(id);
});
$(".students_but").click(function(){
//alert('student');
var id=1;
});
});
</script>
<div class="teachers_but">TEACHER SIGNUP</div>
<div class="students_but" style="text-align: center; margin-top: 8px;">STUDENT SIGNUP</div>
</html>
How to pass id value in html file to php file and set cookie for that value.
I think this question comes up somewhat often, and the comment answers are correct; but you also have to understand what's happening during the request. I'll try to keep it kind of simple.
On the SERVER, PHP processes all the PHP tags of your file, and turns it into a file consisting of pure HTML, Javascript, and CSS. The server sends this to the CLIENT (the person with the web browser hundreds of miles away). That client doesn't even know what PHP is, and the server will actually then shut down that little PHP environment it had created; all variables are destroyed, and it waits for the next client request to process a page again.
Using a specially-coded in-page request, often referred to as AJAX (Asynchronous Javascript and XML, the XML part being a misnomer) you can start new requests against the PHP server to save information, request new information, etc, without loading a new webpage.
HOWEVER, your specific question has a unique aspect to it; you want to set a cookie. Although you normally only see cookies when working in PHP, the cookies are actually stored on the client's computer, and are sent to the server on each request. Javascript is able to access them on its own, and some libraries can help with that.
I haven't followed this tutorial myself, but a quick Bing search found this, which might help you: http://www.electrictoolbox.com/jquery-cookies/

How Ajax enables a Javascript string to be passed to php

I've been learning Ajax and now I'm wondering how it allows a string from Javascript to be passed to php.
It was said before that the problem with passing Javascript to PHP is that the PHP code gets run first, and then the Javascript gets run. So when Javascript generates a string it's already too late.
Does this mean that Ajax allows PHP code to be run after Javascript?
I think this is what they're getting at:
Before Ajax -- specifically, before XMLHttpRequest came along -- a single web page was served as a single page load. If it was a PHP-generated page incorporating Javascript, the browser would request the page, PHP would generate the page (including Javascript code, includes, fragments of script on the page, etc.), would send the page to the browser, and the browser would display it. So, the PHP happened up-front. Until the next page load -- when the entire page was refreshed from scratch -- PHP wasn't involved again.
After the advent of XMLHttpRequest, which helped put the "X" in "AJAX", as it was back then, you had another option. Once the page was loaded, your Javascript could make requests "behind the scenes" of the page, to request more information from the server, without reloading the page. In effect, the loaded page could cause more PHP to be run on the server, and display the results.
So, if you're considering a single page load from a PHP-based website, that is (sort of) what Ajax means; without it, you get a single PHP page-build that's delivered and then your Javascript has to run on that result alone. With Ajax, you can make further requests to your server and throw the results out onto the existing page without a full page load.
The php interpreter sitting on the server is basically interprets whatever php script into (usually) HTML page.
That's why you can never "pass" javascript variable into php as to the interpreter, your javascript is just yet another string, without any special meaning. Your javascript is run by your browser and doesn't even aware that it was being produced by PHP.
I believe that's what it means by "too late".
You should know, that Javascript is always (except Node.js) Client-Side.
PHP is a Server-Side language.
You can't pass Javascript variables to PHP - at least not at the Pageload.
What you can do is doing a AJAX-Request after the Page is laoded to send something to PHP.
With the Response of that call you can replace some other things on the current requested Page.
No it does not mean that "Ajax allows PHP code to be run after Javascript". AJAX is a new request to the server and it allows you to manipulate with the server's response. You can observe this by coping the url to which AJAX request is being made and pasting it into the browser.
So basically when you open a web site with the browser, you send a request and any AJAX call is also a request, but done in a background, so you cannot see it directly. You can use for example firebug or other developer's tool to see what happens behind the scenes. It has nothing to do with the scripts executions orders.

PHP website basics, some clarification please

I currently am using PHP to render a dynamic JS+CSS+HTML website via echo statements. The PHP is filling in some of the JS variables.
I want to expand this to include If/Else statements but I have some questions about how PHP interacts with the rendered page
After the site is rendered (all the echo statements have printed) can I still call additional PHP functions? For instance, if I click something can I have that call a PHP function?
Feel free to point me toward PHP tutorials that explain how PHP interacts with the site. Ironically I have done a lot of PHP coding for other tasks I just never thought about it from the ground up
PHP does not interact with the site. PHP's only function is to output text to the browser.
Look at it this way: if you had no PHP, the website would be composed of HTML pages. HTML pages can contain JavaScript and the user can interact with them. The difference with PHP though is that you can generate these HTML pages dynamically (which by association means that you can also generate the JavaScript contained in the HTML pages dynamically). Nothing else has changed.
Basically once the PHP script has finished running and printed (echoed) all the html content to the browswer then it stops running.
Essentially if you are clicking on a web page then that can either call a new page via a form POST or a GET OR maybe javascript can handle the click. And then that Javascript can perhaps perhaps trigger a new request. And that new request can call a PHP script which performs whatever task you want it to.
So if you click on an <a href='action1.php?param1=yes'>Click here</a> link then that will call the script action1.php (with $_REQUEST['param1'] set to 'yes') on the webserver and the webbrowser displays anything it returns. And that new html replaces all the html currently in your browser window.
OR if you have a form:
<form action='action2.php' method='POST'>
<input type='text' name='stuff'>
<input type='submit>
</form>
And you click on submit then again the webserver will be called but this time the script action2.php will be called with $_POST['stuff'] set to whatever is in the text field. And whatever the script returns will be what is displayed in the browser.
Now if you want to click on something in the browser and just change something small on the page or just perform some action on the server then you should probably investigate AJAX handlers and jQuery in particular
Good Luck.
I've learned in coding to never say never....
Aside from standard Ajax, there --IS-- a way to run PHP functions asychronously: xajax In a nutshell, it allows you to call PHP functions directly without reloading the page. A word of warning-- the documentation is weak....
PHP is server side technology as others have mentioned. Getting it to run asynchronously (or after the main page has rended, as the case may be) is only facilitated with some Javascript voodoo, which is what xajax brings to the table. It does a "good enough" job making this possible. I personally have chosen to use Jquery because of the sheer power it brings for UI development. There's tons of options out there to make Ajax calls.
The key to moving your understanding forward is thinking about coding for the FRONT END. When I was beginning my career I was solely a back-end guy, focusing on the standard if/thens/elses and echoing out the relevant code. Once it was on the screen, I was done with it. Moving over to concentrate on the front end requires understanding of the dom structure -- what you'll be using to "grab" elements and then understanding of tech such as javascript to "do stuff" with your data. In a nutshell, it's just a different way of doing what you're used to with a slightly different syntax. Rather than just jumping in feet first to tackle Ajax or this specific task, take some time to familiarize yourself with the basics of traversing the Dom, and perhaps some Javascript or Jquery basics as well. It'll make your job much easier in the long run.

How to parse content loaded by javascript after the dom is complete

I have been working on parsing some of the data from the wow armory and have come into a bit of a snag. When it comes to the site serving up the achievements that players have received, it uses javascript to intemperate a string such as #73:1283 to display the requested information. (I made this number up but the data for the requests are formated like this).
Is it possible to pull data from a page that requires javascript to display its data with php?
How do you parse data from a site that has been loaded after the dom is ready or complete using php?
By using Firebug, I was able to look at the HTTP headers to see what AJAX calls were being made to generate the content on these pages: http://us.battle.net/wow/en/character/black-dragonflight/glitchshot/achievement#96:14861 and http://us.battle.net/wow/en/character/black-dragonflight/glitchshot/achievement#96
It looks the page is making an asynchronous call to load this page: http://us.battle.net/wow/en/character/black-dragonflight/glitchshot/achievement/14861 when the part after the hash is 96:14861, and a call to http://us.battle.net/wow/en/character/black-dragonflight/glitchshot/achievement/96 when the part after the hash is just 96. Both of those pages return XML that can be parsed to render HTML.
So generally speaking, if there's just one number after the hash, just put http://.../achievement/<number here> as the URL. If there are two numbers, put the second number at the end of the URL instead.
What you'll need to do, rather than pulling the Javascript and interpreting it, is make HTTP requests to those URLs by yourself in PHP (using cURL, for example) and parse the data on your own.
I would really recommend learning JavaScript and jQuery, since it will be very hard for you to really build a good site that pulls information from the WoW Armory without understanding all the AJAX loads that are going on in the background.
I would recommend seeing if you can replicate the query sent by JavaScript in PHP. While I don't believe there is a way to process JavaScript in PHP, there definitely isn't a simple or scalable way.
I would attempt to scan the first page's source that you downloaded with PHP for strings of that format you mention. Then if the JS on their site is querying something like http://www.wow.com/armory.php?id=#72:1284 you can just download the source of that next. You can find out how the JS is querying the server with something like FireBug or the Inspector in Chrome or Safari.
So in summary:
Check to find the JS URL format and if you can replicate it.
Create PHP to get main page and extract all strings.
Create PHP to loop through these strings and get these pages (with URL that JS requests).
Do whatever you wanted to with that information.
You can try jquery's $(document).onready function which helps
to run java script code when the web page loads up.
ex
<div id="wowoData">#4325325</div>
<script>
$(document).ready(
function(){
$("#wowoData").css("border","1px solid red");
}
)
</script>

PHP and JQuery Question

Is there a way I can pass a PHP variable from a PHP page to a JQuery page and back to a PHP page?
Maybe I'm wrong but I believe you may be confusing things.
Server Generates page using PHP.
Generated page is composed of HTML, JAVASCRIPT whatever...
Client receives page
Received page is interpreted (JavaScript code is run)
In the end what you are asking for is possible but, by the way you put the question, I though that the above should be clarified.
How to do it?
Say you want to pass id=123 from server to client and then back.
generate page with a tag, say <span id="js-val">123</span>
have client read the contents of id="js-val
client can then resend the 123 using POST or GET that really depends on what you want.
Hope it helps to clear things up.

Categories