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).
Related
What are the advantages of using jQuery Ajax to POST data to the backend?
Is it necessary to use jQuery Ajax to POST if your html and php are on the same page? (meaning it only reloads, not redirect, after being submitted traditionally).
Whether to use jQuery or vanilla JavaScript is your choice. Ajax is useful if you just want to send a small size of data to the server without downloading the entire page from the server.
Suppose you have a page with 1000s of lines of HTML and you need to submit a simple yes or no response to a question to the server. Now, if you just redirect to the same page, it will still download most of the HTML page again. Ajax will just send that bit of data you want to send to the server and get a response which you can use within the client side to make changes to the page.
I have a text file storing one string. I anticipate that the text file will be changing frequently, so in order to keep my page up to date, I would like to use PHP (preferably) to fetch data from the text file every 20 seconds so I can explode it into an array and use the contents accordingly. The variables would also need to update every 20s.
So: on page load, the contents are fetched and displayed. But the contents of the text file may be changed thus making the page outdated while a user may already have it open.
I tried META Refresh, but the whole page refreshes in the middle of browsing and interrupts the user.
Sorry for the confusing description, it's hard to explain. :)
I've searched the web for ages and not found an answer to my question. Please remember I am using a text file and not MySQL, since I'm only storing one string.
Thanks in advance.
If you want to stay with PHP, I'm afraid a refreshing HTML Meta is the solution :
<meta http-equiv="refresh" content="10; url=http://example.com/" />
Refresh the page every X seconds, so that the file gets reloaded.
Another way could be the use of frames, however I cannot seriously recommand it to you.
However, you can load a content without reloading the whole page, using Ajax. It allows you to perform a HTTP request to the server (using a Javascript code) and place its result on the current page, using Javascript as well. You could create a PHP script "my_string_parsed.php", which reads the file, and then parses/prints its content. Then, you could call this script through an Ajax request to http://yoursite.com/my_string_parsed.php, and place its result in a specified HTML tag on your page.
W3Schools.com provides an Ajax tutorial here : http://www.w3schools.com/ajax/
A warning concerning Ajax though : an Ajax content loading must never replace the typical HTTP behavior your browser and the server have. If the string in your file is the only content on your page, then the best solution would be the refreshing meta. Ajax should only be used to refresh parts of a page. Never the whole thing.
Why not using a database instead of a file. You could also use jQuery to update your page smoothly.
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.
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.
Currently I'm doing this in two steps:
1.post it to ask.php
2.after inserting it into database,use header("REFRESH: 0;URL=post.html") to jump to the result page
But how to do it all in one step,say,like SO here?
SO does it using Ajax. But for the easier win, why not just use header('Location: http://example.com/post.html') instead of a refresh?
It happens using ajax, I'm guessing.
-User types post, hits submit.
-Post content is sent via ajax to the server where it tries to save it.
-If it is saved:
The post is added to the page using javascript and some pretty animations and all the various listeners are added to the clickable elements.
-If not:
Show some error.
I'm sure there's more to it than that, but that's probably the basic idea.
Instead of a that refresh header, after processing the POST request, tell the client to view the result with a Location redirection header
header("Location: http://www.example.com/post/$post_id");
That kind of thing is done with Ajax. Using javascript to request small(er) amounts of data from the server, then updating the page, bypassing a full page request/refresh.
Here's a few libraries that may help get you started with Ajax and PHP:
XAJAX
Zend_Json_Server (more complex)
PHP Ajax Example at W3Schools