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
Related
Dear Firends I have large number of forms on a single web page all of them calls a single PHP function. However what I want is that the forms should call a jquery function and if there is a need then jquery should let it call the PHP function.
I do not want to use Ajax just want to create a PHP function call if the matter can not be solved by jquery.
Each of the form is associated with some data. how ever all the data that is displayed on the page is not available all the time. So what I want is
if (data == available) { call PHP}
elseif (data != available) { jquery alert('sory bro');}
if data can not be seen now just use jquery to say sorry (no need to check from server). When a page is loaded we know which all pieces of data can not bee seen and are given in different color.
The forms are generated using a PHP loop with each form showing different data but of same type (each form is assocaited with a sort of Article).
All the questions that I have seen are about Ajax. Where as my current PHP code is working fine. all I want it that before making a trip to server if the data is not available the jquery shoould say so. We already know which data is not avaiable so far.
I hope I have explained it
Thanks a lot
**I think I have not made my point clear.. When the page is loaded is already know which data is not available for display and it is marked in seperate color and the div has different arrtibute...*is there some way so that I do not call PHP function for those forms?
PHP executes on the server side. Javascript (jQuery) executes on the client-side. So PHP is completely done executing before Javascript starts executing.
That's why everyone is saying you need to use AJAX. AJAX is a way to make a call back to the server in order to execute PHP code. PHP code only executes on the server. So in order to execute PHP, you have to make a call back to the server.
According to your logic, the data is present on the server.
If you want to know if the data is available or not then you have to contact the server right.
If that's the case how can it be solved without sending an ajax request..
You need to make the request as jQuery is a client side code and cannot contact the server directly.. You need the server side script to execute it which is PHP in your case
The easiest solution:
if (data == available) { $("form").trigger('submit') }
elseif (data != available) { jquery alert('sory bro');}
Obviously you need to adapt the selector according to your specific form / requirements.
Just make sure your form does not get submitted accidentally when you press submit by adding something like event.preventDefault(); in your function.
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.
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?
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.