How to get javascript to run after AJAX calls - php

Okay, a little preface: I am still a beginner when it comes to AJAX, and dynamic web stuff. My problem is similar to what was asked in the following, but I think that discussion is using a framework, and I am not.
Potentially related post
Here is my scenario:
I have several select elements in a form. The initial select's option elements are populated each time the page loads. The option elements for the subsequent selects get populated depending on what the user selects in the previous select. So it is like a chain. The options in the selects are populated by making AJAX function calls (just my own javascript) that in turn call a php file to get values from a database and build a responseText to fill each subsequent select based on the selection made in the previous select. Hopefully that is clear? All that works fine and dandy.
My problem starts here:
When the user submits the form, a php file is run to process the data, displaying success or any issues, and then I return the user to the form page. I want to reselect all the options they had selected prior to submitting, since some of this is a repetative task and this would save them time. My first step is to recall the required AJAX functions to repopulate the select elements, and then I thought I could run javascript in the form page to select the previously selected options. However, when I try to run javascript on the form page to select the options, it is running before the AJAX calls finish. Therefore, because the options are populated by the AJAX calls, the options do not exist yet in the selects, so I cannot select them. I tried writing some test code to insert a new option to see when the code runs, and sure enough, that new option gets added to the select before my AJAX populated ones go in. In order to track if options were selected, I am passing back the selection option values through the URL, and then processing the $_GET array in my form page.
So my question boils down to:
Is there something I could do that would prevent my javascript that selects the selected options from running until the AJAX populating functions finish?
I would also accept responses like "Your whole approach is bogus! Where did you get your AJAX coding license??!! A Cracker Jack box??" Although, just a few of those responses please, I'm a fragile flower ;)
Thanks in advance,
Carvell Fenton
P.S. Hopefully that's not too much preamble, but I thought the background was necessary.

How many levels deep are the chained selects? I'm doing this with only 2 levels (1 ajax driven select) and for the second page load I would add some code to my jquery document ready function that would initiate the ajax call to load the select list but also send it the id of the field I wanted selected so when the ajax call completes it will have loaded my select and also set it's necessary value.

It would help if you show us your code.
Are you making the AJAX call synchronously? That is one way to do it, but that will stop execution of any subsequent code until the call completes.
Another (and the more correct, I think) way is to make the call asynchronously, and put the code you want to execute after in the onComplete handler.

http://docs.jquery.com/Ajax/jQuery.getJSON#urldatacallback <-- Take a look at the callbacks with jQuery
Also look at the Start \ Stop http://docs.jquery.com/Ajax/ajaxStart#callback and http://docs.jquery.com/Ajax/ajaxStop#callback - you can execute javascript to do anything you require....

Use the onreadystatechange event listener.

Thanks for all the answers! Once again the Stackoverflow folks have enlightened me. Based on the comments, I think I have several options:
(1) I can avoid a framework and just pass more information to be processed in the onreadystatechange event listener (I think this is what Jeremy Stein was suggesting, even though my comment confused the issue). In this case, when I am dynamically adding the option elements to the select, I would just set one of them to selected. In that case I have to pass the selected option (via URL I guess) to the php file, then have the php file include that in the built responseText so I know which option to set as selected in the onreadystatechange listener.
(2) I can use an AJAX call to wrap the form post and never leave the form page (as Mikeb suggested).
(3) I can add in a framework that does the work for me (CRasco, Ben Hall, OrbMan).
I have spent the last few hours trying to understand the pros and cons of jQuery, Prototype, and MooTools to see which is easier for me to implement and best suits my needs. I have been successful in getting a very basic form page behaving close to what I want with jQuery. It carries out the process and never leaves the form page, so it is options 2 and 3 together I think. Now I just have to figure out a bit more about how the $.ajax call actually works and where I can get the responseText from if I need it. I can look that up though :)
So thanks again all.
What are you supposed to do on here when more than one answer pointed you in the right direction?

Related

On select/unselect of checkbox, query DB, return array, then update array without refresh

I am currently using Jquery UI to display checkboxes, which right now, don't do anything!
you can see the current set up here: rickymason.net/letschat/main/home/
I am still trying to understand JSON, AJAX and Javascript...but i know they are required to make this work:
When the user checks one, or more of the checkboxes, I'd like it to refresh the thread list at the bottom of the page based on which list is checked.
I don't need exact code (though the more the merrier!), just a good outline on the process that needs to take place.
I'm using codeigniter, thus php and mysql. The thread list is generated based on a * query for the threads table. Then, it is filtered based on a session variable which contains all active filters (user input, AND i'd also like it to be selectable via the jquery select box).
Any help is greatly appreciated!
The magic word here is AJAX.
Use jQuery to bind to the events of the form elements
Send the event through AJAX calls to the server
Parse the response from the server and use javascript to update the page

How to access values displayed in a php dropdownlist populated from a mysql database

Firstly, let me say that I've been searching the Internet, rewriting scripts and I still can't seem to find a solution to my problem or even one that could possibly help. I've even searched this site for similar questions and the focus seems to be on actually displaying the database values but what I want is to access those values. Or rather let me put it like this, I have a drop down that is generated through php and it contains data retrieved from mysql... all that works fine no errors.
My current problem is that when a user select an option from my dropdown, I want to use that value to do more operations based on the user's selection. Please help, I've been at it for a week with no avail. Thanks in advance. If you need samples of my code please tell me.
Your problem is not that easy since php only runs on the server and does not directly get any information about what a user is clicking and selecting in his browser.
One possible solution (and the most common one nowadays) is to load any further information asynchronously via AJAX as soon as the user selects something in your dropdown. jQuery is a neat framework that can help you with this.
An other method is to automatically submit the form as soon as something is selected and read the selected value with php ($_POST variable). With this you could then easily generate a more custom website according to the selection that was made. Code could look like this:
<form method="post" action="" name="myform">
<select name="myfield" onchange="this.form.submit()">
<option .... >
...
</select>
</form>
(Note that the form is submitted when the onchange event is triggered)
This method clearly has the disadvantage that the whole page has to be reloaded whenever a selection is made. With the AJAX approach the user does not even notice that some additional information was fetched form the server. (Except a small waiting time that may occur)
What you want to do depends on your own decisioin. However the first approach may need you to get into some javascript programming. But the result is certainly more comfortable for the user...
You could make a callback function on the onselect Event. This is the easiest with jQuery in my experience.
http://api.jquery.com/select/
Wrap your select in a form which had a post of type 'get'. This will post to the same page you are in and then you can use the get parameter on page refresh to load your second list

Can't post data to self because of design

i have a website that uses a number of containers (div's). In this scenario, we have three boxes down the left side and one bigger box on the right of these boxes. The bigger box on the right is the only thing that changes when a link is pressed, this is done with Javascript.
SO i have the index which is the main layout of the website and i also have the "pages" of the site, so when a link is pressed the main box (on the right) loads the new data.
On one of my pages i want to collect data and then run it through a PHP script that is in the head of the file, but when i click the button i realise it refreshes the whole page and it doesn't run the script on the page with the form.
Anyone had a problem like this, or know of something i could do to work around it?
I'm not really sure what code would be useful for helping me but if you need something just ask.
Thanks for the help
Since you are loading all your content via JS already, you could just POST the form data via AJAX to a PHP script to process, then read the output and either provide an error message or remove the form from the page and show your success message.
How to approach your AJAX call is dependant on what you've used as a basis for the rest of your JS.
Personally I like to use the JQuery library, as it makes AJAX calls (and much more) very simple.
How about you make the page design able to do it. Have the backend be able to spit out the state of the page when it posted.
Or use Ajax to post the data back and set the new state like you do already.

Is my logic correct? Ajax and/or PHP with Mysql

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.

Send a post with PHP + AJAX

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.

Categories