I've been studying PHP for a while now, and Ajax for about a month or two. I still can't figure out how does PHP send data to Ajax and how does Ajax retrieve the data.
Can anybody post an example or something?
Maybe After submitting some text.. PHP sends the data to the Database, but how would Ajax also receive it and post it to a specified field without refreshing?
If it helps, I use jQuery a lot, so i'd be using it with AJax too,
It's actually a lot less complicated than you may think. Think of AJAX as just requesting any old webpage, the trick being that it does it behind the scenes, "on the fly," without regard to anything in the URL bar of the browser.
In that sense, you're almost asking the wrong question (almost) because it doesn't matter (sort of) how PHP serves the page. AJAX can request any page that's served up from PHP. So, for example, say you have a simple PHP page that looks like this:
<?php
$content = '<div class="content">content</div>';
echo $content;
?>
And you save the file as /content.html
From another page, you can load that content dynamically, using AJAX, and as jQuery is your preference, that might look like this:
$('#result').load('/content.html #content');
.load() is specific kind of AJAX function (there are several, the most basic being .ajax() I believe) that loads HTML content directly into a given page. In this case, what's happening above is that when you call the .load() function, it loads via AJAX /content.html into memory, looks for the element called #content (which happens to be a div), then inserts that loaded #content element into the #result element.
Note, that the reason I'm saying "almost" and "sort of" above is that it will matter, depending on what you're doing, how you format your PHP page. For example, it's common to request pages with AJAX that are formatted in either XML, JSON, or just plain old HTML snippets. That is, of course, a much more dense subject, but here are a couple example tutorials:
http://www.xoops.org/modules/news/article.php?storyid=5103
http://www.factsandpeople.com/facts-mainmenu-5/26-html-and-javascript/89-jquery-ajax-json-and-php
http://www.phpriot.com/articles/php-json-jquery-ajax-screencast
Hope that at least helps. There are A THOUSAND tutorials online, however, and simply searching on Google should yield plenty of results.
If you make an Ajax request to a PHP script,
Anything you echo in PHP will turn up in the Ajax request's response body. As #webbiedave says, that can be for example clear text, or XML, or HTML, or JSON encoded data.
Any status code you throw in the PHP script (e.g. header("HTTP/1.1 404 Not Found")) will be reflected in the Ajax result. If you throw a non-successful HTTP status code (e.g. 404 or 500) the Ajax request will fail, and (if you use jQuery's Ajax) the error callback will be called.
It just sends a request to the server like a browser, only in the background, without reloading. The received data is the content of the page. The same you would see if you'd open the url in the browser.
Related
I have a PHP page that displays a form. The buttons are a buttons (not submit). When clicked they call a function in Javascript that issues and Ajax call. The URL that the Ajax uses is to to the same php page, passing variables. The top of the php page checks if these variables exist and if so they do their database work, in objects, echo a message back to Ajax and call exit().
My question is, after the exit() is the rest of the php page re-evaluated/executed? I can't seem to find an answer. Basically, right after I call exit(), if I use the objects to query the database to determine what to display, does this happen?
If the ajax calls the same php page, is the entire php reevaluated?
Short answer: It depends. It should not if is designed correctly.
Long answer. Normally you use PHP scripts to serve HTML, and in your case this is what it does - it returns the HTML that displays the form and probably on submit will interpret the results. But, an PHP script (program) can do much more things. You should consider the URL only your entry point to an application, not to a PHP script. This URL can serve different parts of code depending on the type of request. For example it can detect that some part of the form is doing an AJAX request to the same entry point and divert that call to a part of the code that will respond only to the AJAX request. In PHP this kind of branching can be done using control structures. Branching when some AJAX headers are detected or when a POST request is presented are quite common examples in PHP world.
So to respond again to your question. The entire page should not be reevaluated if you branch your code for this, and then execute only the parts of code that correspond to the AJAX request not the ones that are creating your HTML.
Example:
if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
// treat the ajax request
}
if ($_SERVER['REQUEST_METHOD'] === "POST"){
// do stuff for a POST request
}
I was trying to submit a HTML form that includes text fields and an image file using AJAX and jQuery. So it turns out you cannot do file upload using AJAX. Are there any nice ways to submit text form data along with a file? I'm aiming for broad browser compatibility, particularly with older IE versions.
One way I've tried is to eliminate using AJAX and simply use normal POST (although AJAX is the preferred way). After the POST another page loads. I can redirect the browser to load another page from my PHP using
header("Location: new_page.html");
but after this, how can I send the JSON response to the JavaScript script on new_page.html. If I do something like this, will the response now go to the JS script on new_page.html?
header("Location: new_page.html");
$data = json_encode(response);
echo $data
So it turns out you cannot do file upload using AJAX.
That isn't true
I can redirect the browser to load another page from my PHP using
The Location HTTP header accepts an absolute URI only. Most browsers will silently recover from that error, but you shouldn't let that be a reason to make it.
after this, how can I send the JSON response to the JavaScript script on new_page.html.
You don't. You generate that page programatically and build it in the state that the JavaScript would have put it in if you had run it after the page had loaded.
Loading a page that immediately fetches data with JSON to update itself is just cutting corners. You end up with the flash-of-default-content problem that used to plague Twitter (before they started building pages server side on initial load and using Ajax only to update them when the view changed).
I have a page which shows a list of items. Page coded with html, css, php and using mysql db.
On that page a user can request to add one of the items to their special list.
I want to do this within the page without having to do a complete page refresh. So user clicks button to add, item is added to their list and button changed so they can't add it again.
Do I use ajax calls to run code behind the page and then refresh the div?
Or is there a better more efficient way to do it.
I'd prefer a php option of possible in case user has js turned off, but don't know if it can be done with using js.
Any help appreciated.
If you want dynamic content (changing the page without refreshing) you are going to have to use Javascript. To do what you are asking, you could call a PHP script via Ajax that outputs the contents of the div with the new item, and then change the div based on that response.
Dagon is exactly right. Create a form which handles the request and set the action of the form to the PHP script you want to handle the request. Note that although this can be the same php script that you use to process your ajax request, it does not necessarily have to be.
Many times when I implement such functionality, I'll set the PHP to send variables as POST (in the event of JS disabled) and have my ajax request as a GET so I can use a single PHP page to handle the 'same' request. When using AJAX, I'll have the script echo a specific code then have the ajax response handle that return.
if(val == 'OK') {
//in event of success, perhaps you want to hide the original form and show a success message
} else {
//do something like unhide a hidden div to display an error
}
If JavaScript is turned off, the page has to be reloaded. In your case jQuery could be very handy and simply rewrite the element you need to rewrite. The server send's a simple json. Using a PHP Framework might also be a good idea, since the way you ask it seems (with respect, and not wanting to offend), that you are not using any framework and might run into falls making your script vulnerable (sql injections for example)
If your visitor doesn't have JavaScript enabled and you want to serve anyways, then you have to do a page reload. First check if that is worth to do, who is your client/visitor, what browser do they use, ... questions like that help you to design your page/app.
I am working on a social network website similar to facebook. But, I am facing a rather confusing stage in the programming.
I am done with the register/login/logout pages/scripts, and you can view profiles with the www.mywebsite.com/profile.php.
Now, I want to do what facebook does and allow users to click links while on their profile page (info, notes, photos) but never actually leave www.mywebsite.com/profile.php — just the appropriate content is printed to the screen.
How is this done? I am not asking anyone to code this for me, just point me in the right direction!
You can use Ajax for this purpose.
Put the content that you want to replace in a div and using ajax replace that div and only send that content.
Are you trying to do something like this?
http://www.99points.info/2010/05/how-to-create-dynamic-content-loading-using-ajax-jquery/
That will have to be done via Javascript and Ajax.
A javascript function will fire when the link is clicked. An ajax request is sent to the corresponding php script which sends back a response to your javascript function. You then parse this response and place it on the screen.
If you go that way, have a fallback option that does not rely on javascript as well in case a user has JS turned off.
You Can use this reference...
function showdiv(id)
{
if(id)
{
var selected_offer="yourpagename.php"
HTML_AJAX.replace('divname',selected_offer);
}
}
call showdiv on onChange() function of your link..
For this, you need the technique known as Ajax, which is short for asynchronous JavaScript and XML. The basic idea is that when the user does something - in your case clicks on a link or button - instead of loading a page, a script runs that calls on a server side script to send back some data. This is sometime XML, but you can get other types of data back as well. The asynchronous part is that the user and the page can go on doing other things while waiting on your script to return the data you asked for.
There's a good book for beginners in Ajax that I read myself: Head First Ajax. Looks like you can pick up a used copy for about $10. It's a nice intro, has a quirky style that appeals to some, and the authors do whatever they can to keep your attention. Hardcore programmers probably won't like this one, but I sense you're a little newer to the game and this may be a good read. Otherwise, Google "learning Ajax" and there are a bajillion resources.
Good luck!
To respond to your comment, you can set up a "router" script that takes input and runs a specific function in response. This "router" function looks at the $_GET[] superglobal for a parameter like "action" and then calls a corresponding function. If not action parameter is sent over, the router calls a default function.
Now for a little more detail. Your page script would have 3 basic parts: The router, the various action functions, and the page template function. The router just calls the appropriate function from the action functions and passes the output into the template function. Here are a few examples.
The user arrives on the page, index.php. No action is specified, so the router finds $_GET['action'] == '' and it calls default_action(). This returns a welcome message, status, whatever, and the router passes this output to the function that displays your page, output included.
Now the user clicks a link/button for updates and arrives at index.php?action=update. $_GET['action'] == 'update', so the router calls update_action(). The output goes on to the template function for display.
Does this help you envision how you might accomplish this?
I have a PHP-script that loads page-content from another website by using CURL and simple_html_dom PHP library. This works great. If I echo out the HTML returned I can see the div-content there.
However, if I try to select only that div with the simple_html_dom, the div always returned empty. At first I didn't know why. Now I know that it's because its content apparently is populated with javascript/ajax.
How would I get the content of the site and then be able to select the div-content AFTER the javascript has populated it with the correct content?
Is it even possible?
Thanks!
Yes its piece of cake if you are interested only in that particular html which is returned by ajax.
Gather information like url, parameters and request type (post/get) from that ajax request.
Generate the same request from your php/curl code and you got it.
And hope that server logic will not check who sent the request.
For this kind of screen scraping you could try phpQuery or Snoopy.
phpQuery has a web browser plugin and scoopy claims to simulate one
you can always bind to the event that is fired when the xhr returns data to the browser and do your operations there.
var xhReq = createXMLHttpRequest();
xhReq.open("GET", "ur_php_url.php");
xhReq.onreadystatechange = onResponse;
xhReq.send(null);
function onResponse()
{
// do the necessary
}
Yes, it is possible.
What you need to do is the following:
Create a CURL call to that webpage in order to retrieve any parameter used in the Ajax call that loads the content, which you are looking for.
Create another CURL call to the file called by that webpage Javascript using the parameters that you have gotten using step number 1.
ex. Say you want to get the content of http://www.domain.com/page.html and this page.html retrieves some other data using Ajax, say $("#div").load("http://www.domain.com/ajax/data.php?time=48484&c=487387").
What you will do is to make a CURL request to page.html first, and get the full URL of the Ajax call using preg_match() PHP function or any equivalent function in any other language. After that, create another CURL request to that URL - http://www.domain.com/ajax/data.php?time=48484&c=487387 - and get its content.
You're all set!
Unfortunately Javascript is run client-side, in a browser, so unless the page is loaded in a web browser there is no simple way to do it.
The only way I can think of, is having a browser running in a server’s background, reloading and saving the generated page automatically in a file which will be available for a PHP script to fetch.
Well... I don’t know about anyone who has implemented such an idea.
Better try to get the URL where the div is being populated from. If the div contents are generated through AJAX for example, maybe if you fetch the data-origin URL with cURL, the data will be available for you as well.