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
Related
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.
Why use AJAX for dynamic web pages when you can do it only with php?
The main reason to bother with AJAX is User Experience (UX).
Now AJAX won't necessarily improve UX in every single instance so in a lot of places sticking with pure PHP is perfectly okay.
But imagine the case where you have a text field on the site and a link to vote on something. Kinda like this site. When you add AJAX your users won't loose the text they entered in the textfield when they decide to vote on the link! How incredibly useful!
So if you care about your user's experience it is a good idea to use AJAX in situations like that.
PHP creates and outputs the Content to the Client Browser as it's a Server-Side Language and that's what it was built for, so on a request your code will access database, files etc. and then output the constructed html/text to the client.
Ajax just gives the User a more Desktop like feel. For example deleting a record and instead of the entire page reloading just letting the one element disappear from say a list and letting the server know that the record is to be deleted. But Remember to let the User know when you are busy sending data to the server (With a progress bar in .gif format for example). As lot's of user feel that if nothing happens on the screen to notify them, that the application is frozen which means they will either reload the page or just try to click the button again.
But you will need to provide some sort of compatibility with browsers that have Javascript disable and thus cannot use your AJAX functions, just something to keep in mind.
AJAX stands for Asynchronus Javascript and XML, meaning that a page can get new data, without having to reload a page.
PHP cannot send data without reloading the whole page. A user has to press a button, to send data.
An example of AJAX is for example google suggestions or the tag suggestions on this website.
can any one please help how to get the values from the javascript to php other than while using submit button.
scenario:
i am searching for record, if the record found then, i need confrim alert asking to continue or not, if he click continue how can i say he selected continue
If you want to check without having a page reload, you probably want to execute an AJAX call, then depending on the result returned by the underlying PHP script, take the appropriate action. If you have no knowldege of how to implement this, take a look here
You can never use JavaScript to communicate with the page while it is loading, you can only send a new request to the web server from the JavaScript layer... although you can send that request to the same script that's already running, it will still be a new instance of the PHP script, just like when you open a new browser tab to the same page.
The only way for JavaScript to communicate with PHP at all, is by sending an HTTP request. But you don't have to refresh the page in order to do that if you use AJAX.
AJAX is basically a word to describe JavaScript exchanging information with web pages without refreshing the page. But note that it will still not be able to change variables in the PHP script which is running when the JavaScript code is executed.
In the case of PHP, I've used the open-source library SAJAX which is quite simple. You will find it at http://www.modernmethod.com/sajax/
Hope it helps and good luck!
You can use this as an example using jquery and PHP:
$.post('searchimage.php', { action: 'searchimage', imgreference: $(this).val() },
function(data) {imgsample.html(data);}
);
Basically apply the above function in a document ready function so its run when the page loads.
This can be triggered using $("#prodcode").click() or what ever event handler you want to use.
The php page in my example will get sent the value from imgreference as a post, you can do whatever you want in the php page then return the value which gets added to the imgsample (in this case a td)
hope this helps.