Submitting form without refresh - php

I am retrieving Google's weather API XML and using PHP. I'm retrieving the weather for any searched city.
Now, this "app" is under a tab and whenever I submit the form it refreshes and I want to prevent this.
Is it possible? This will be implemented in a dashboard - thats the reason I want to prevent the refresh.
This is what I mean: http://www.screenr.com/30As
The entire code is here: http://jsfiddle.net/ZshpF/
Simply, copy paste the code in a php file and it will work.

You'll want to use AJAX. Since you mention jQuery in the tags, it has a very handy function for making the call to the server. But making the call from the JavaScript is only half the story, you'll also need something on the server listening for that call. It would essentially be another PHP script which acts as a page in and of itself, but would return data in the form of (most likely) JSON instead of HTML. It's not meant to be human-readable, but rather to be a sort of web service for your JavaScript code to use.
You can find a simple example here.

I think you can use jQuery ajaxForm

Related

Calling PHP function after jquery code

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.

How to design a script that will use many user inputs from another page using AJAX & PHP?

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..

Store jquery variable, transfer to php and check

Ok, so I'm trying this again. I'm trying to validate a users age by country - all selected from dropdowns.
First I use the dropdown to select country, the value of each is 16/17/18 etc so I'm using this script to capture that:
function displayVals() {
var singleValues = $("#country").val();
}
then I'm sending that variable to php:
$countryAge = $_GET['singleValues'];
next I want it to be the result of this function:
function age_required() {
return absint($countryAge);
}
It's just reloading the page, so not throwing any errors that I can see, but also not displaying the notifications that the person is too young etc. It was working before I started meddling.
Any ideas of why it doesn't work? What am I doing wrong? I'm NOT a php/js guru.
$_GET retrieves the value from a querystring, so when you are posting or some other way going to your PHP page, you need to make sure the url includes "?SingleValues=(YOURVALUEHERE)".
http://php.net/manual/en/reserved.variables.get.php
It sounds to me like you may be a bit confused over the role that both JavaScript and PHP play in web applications.
JavaScript runs in the client (i.e. the browser). The source code lives on your webserver, and then gets downloaded in whole to the browser before it gets executed.
By contrast, PHP runs on the server. Its purpose is to create X/HTML markup as output, which the web server then sends to the browser.
In order to get data from the browser to PHP and then back again you need to generate a request. This can be done on the fly (read: without a new page load) using AJAX. There's lots of questions here on SO about AJAX, so I suggest that you begin exploring those questions/answers.
To help you off, here's a few tutorials:
AJAX Using Native JavaScript
AJAX Using jQuery Framework

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.

passing values from java script to php

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.

Categories