I have an AJAX POST which runs a php script which updates MySQL. The page is part of a Joomla site. Its part of a series of POSTS which return HTML to div's in the page. It all works well but I currently use a simple echo statement to say "Record Updated !" etc. But I have little control over where this message goes - and I don't know how to remove it when the user moves to another record - I'd like the message to disappear. I've just realised that HTML created by Ajax is "on the fly" - i.e you don't see it when you view source. So it's not possible to use Javascript and the DOM to change it.
What I think I want to do is run a Javascript function within the php - but this doesn't work either !
Any help here appreciated - or an alternative approach to give a database update confirmation message which can then be removed when the user moves to handle another record.
echo statements in php are not shown to the user when you use ajax unless you use the php output in your ajax success function yourself.
So you just need to remove the part of the javascript that adds the ajax return data to the dom / screen (in case of an alert).
As to an alternative solution, you could use a statically fixed status bar that shows up on an update and slides away after a few seconds. I don't know if you are using a javascript library, but using jQuery that would be very easy to implement.
Related
In a nutshell.... what i want to do is a install script for my website... but i want everything to be done in 1 page which will connect to another php file that will have all the server side processing code. In order to do that i use JQuery, Ajax & PHP...
Now my question lies in what are the best practices in order to do that. How do I make my server side PHP script to take multiple user inputs that will happen throughout a lengthy installation processes?
I was thinking on using switch statements that will trigger classes & functions and like that being able to access multiple processes (Classes and functions) that will be stored in the same file?... or people normally use other things?? never done this before and couldnt find a straight forward tutorial for it on how is best to design it.
I was thinking on maybe being able to access classes through AJAX in php but that doesn't seem to be possible.... can i trigger functions from AJAX in php?
I really appreciate the help in how normally this is approached
thx
It would be too lengthy to define the whole process in SO in detail. But the basic idea is:
User fills in form clicks NEXT button.
You get all the form values (in JavaScript), post it to a PHP page using AJAX
The PHP page gives you back a flag (SUCCESS/ERROR) [In the background, if it is success, PHP has persisted the data into a database]
If JavaScript receives ERROR, you show user the error message and ask him to correct the form
If java script receives SUCCESS, you call the next PHP script, which generates the next form and sends it to your JavaScript
JavaScript populates this form content within a DIV in your page, effectively wiping out the current form and showing the new form in its place.
..and the whole process restarts from the first step once again for the new form..
I implement a custom form validation in Drupal 7 - hook_FORM_ID_form_alter(), by setting a simple callback function like here:
$form['#submit'][]= 'mymodule_myformid_submission_submit';
In the submit function I do the form validation myself, and, based on this operation, I want to execute a JavaScript function in the original page, where I redirect (either using a header('Location: ...') or $form_state['redirect']; both work fine).
I have reached to implement the JS sending and execution by using:
unset($_SESSION['messages']);
drupal_set_message("<script>aftersubmit();</script>");
The only problem I have is that I have a small, empty stripe on top of the page, corresponding to the Drupal message area (although I use a completely customized theme with just a content region + panels), that I can take out by doing location.reload(true); at the end of the JS function. But that takes 1s to reload.
I have tried to use echo, but is doesn't work (and I know why).
I am certain that the way I send the JS code, using drupal_set_message(), is not the appropriate one. What should I do? (don't want to use Ajax because I'm at the beginning of learning Drupal)
Thanks
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.
Context
I'm working on a project that I'd like to make more dynamic with PHP + AJAX.
I'm using jQuery for the AJAX part because I totally suck in Javascript, and anyway it seems to be worth something.
I reached a point where my application needs to use a form to send a post, and I want to use an ajax call to perform this action. In the page I'd like to send the post, there is also a list of the most recent 15 posts submitted.
First question: Should I just forget about it and use just PHP?
The action
The user writes something in the <textarea></textarea> and clicks on a <a id="myPostSubmit">Submit</a> that is the handler that I'll manage on the jQuery script with something like $("#myPostSubmit").live('click', function() { /* here i make the ajax call */ });. If the post is successfully submitted we are going to do something (I'll talk about it in the next section), either we will alert the user using my showAlert(text) function, that shows a black box for 4 seconds with the text in it.
Second question: Should I manage the click event in any other ways? Should I create a function, such as sendpost(post) and attach it into the HTML onclick="" event?
If the post is successfully sent
I'd open a discussion about 2 options:
We refresh the page [not actually
loading the entire page but making
another ajax call that retrieves the
posts lists and makes disappear the
old one, load the PHP file to
retrieve the new posts (including
the one we just sent), and then make
the post list appear]. Pro: 1) We are sure that what the user is reading after the post list is loaded is the real post sent. So it actually double checks the action. 2) We load also some possible posts sent in the mean while. Cons: 1) We have to create a PHP file that gets the post list template, slicing the template of that page in 2 files. 2) It doesn't really seems that smooth to me.
We just use Javascript to get the post template, add it to the list. Pro: 1) We make it really smooth, without reloading the entire page. 2) We don't need of any PHP file to reload the page. We just use Javascript (jQuery). Cons: 1) How do we get the post html template to add it to the list? 2) How do we get the user (logged) informations without PHP?
Third question: Is it better the 1st or the 2nd solution? Would you provide a even better 3rd solution?
The PHP page
The PHP page that will receive this AJAX call is : ?p=action&a=sendpost. The page require $_POST['myMessage'] to be set and not empty and nothing else. The page itself will get all the user infos from the cookies and will manage to perform the needed query.
The application
It is divided in 3 parts: App, Template, Library. Basically each page of the application has its own .app.php and .tpl.php file.
The .app.php file manages the building
of the basis of the page, using classes
and other stuff from the library. In
our case it retrieves datas from the
database and put them into
variable.
The Template is called at the end of the .app.php file. The .app.php file send to the template the retrieved data and the .tpl.php file outputs them.
The library is used to contain the classes and functions we need in the application file.
Fourth question: Is this a good way of manage my web application?
Edit: What about returning the alert message to the user?
I read about an option, inside $.ajax() that will manage the response on success or in error. The documentation about it is very simple and I didn't get it.
Fifth question: How should I return (from the PHP file) the error
or the success?
First question: Should i just forget about it and use just PHP?
Well, you application will relay on JavaScript if you use ajax, this days i think it just fine ;)
Second question: Should i manage the click event in any other ways? Should i create a function, such as sendpost(post) and attach it into the HTML onclick="" event?
Create a function and bind onclick. Code will be more readable ;)
Third question: Is it better the 1st or the 2nd solution? Would you provide a even better 3rd solution?
My solution: ajax submit the form and on callback insert new comment in to the list or display error message if user can't comment.
Check jQuery serilize() for submitting forms data with ajax.
Fourth question: Is this a good way of manage my web application?
It's just fine ;) When you application get's bigger you will have to redesign it, but don't do it know, do it when current solution becomes to hard to work with.
Read some good book on building MVC framework. And on programming patterns in general.
You seem to be on the right track with everything. There are lot of opinions called "best practices" about how to exactly attach event handlers, how to reload the data on the page and how to organize your application, etc, but I personally would rather build more software instead of worrying about details like that. The details will come to you eventually.
I personally find that updating whole chunks of server-side-rendered HTML on the page is more robust solution, but I have seen people getting excellent results with templates.
I'm writing an app that uses ajax to retrieve data from a mysql db using php. Because of the nature of the app, the user clicks an href link that has an "onclick" event used to call the javascript/ajax. I'm retrieving the data from mysql, then calling a separate php function which creates a small html table with the necessary data in it. The new table gets passed back to the responseText and is displayed inside a div tag. The tables only have around 10-20 rows of data in them. This functionality is working fine and displays the data in html form exactly as it needs to be on the page.
The problem is this. the HREF "onclick" event needs to run multiple scripts one right after the other. The first script updates the "existing" data and inside the "update_existing" function is a call to refresh a section of the page with the updated HTML from the responseText. Then when that is done a "display_html" function is called which also updates a different section of the page with it's newly created HTML table. The event looks like this:
Update
This string gets built dynamically using php with parameters supplied, but for this example I simply took the parameters out so it didn't get confusing.
The "update_existion() function actually calls the display_html() function which updates a section of the page as needed. I need to update a different section of the page on the same click of the mouse right after the update, which is why I'm calling the display_html() again, right after it. The problem is only the last call is being updated on my screen. In other words, the 2nd function call "display_html()" executes and displays the refreshed data just fine, but the previous call to update_existing() runs and updates the database properly, but doesn't display on the screen unless I press the browsers "refresh" button, which of course displays the new data exactly how I want it to, but I don't want the users to have to press the "refresh" button. I tried adding multiple "display_html() calls one right after the other, separating all of them with the semicolon and learned that only the very last function call actually refreshed the div element on the html page with the table information, although all the previous display_html() calls worked, they couldn't be seen on the page without a refresh of the browser.
Is this a problem with javascript, or the ajax call, or is this a limitation in the DOM that only allows one element to be updated at a time. The ajax call is asynchroneous, but I've tried both, only async works period. This is the same in both Firefox and Internet Explorer
Any ideas what's going on and how to get around it so I can run these multiple scripts?
I'd recomment you to use jQuery javascript library. It has some funcions, like live() that can "wait" for that table to appear on the browser and apply the remaining functions on it.
Also, it's a great set of functions that will certainly help you out reducing the ammount of code you write, making it more human-readable.