Hello all I'm new to this whole thing still.
I would like some help figuring out how to do this please. I can pull info out of a database and put stuff in using ajax/javascript but I cant figure out how to complete the problem below. I want to be able to make my php form submit and update with out page refresh.
Example.
Page1. Main page
-Drop down
javascript/Ajax on change of dropdown get info from page 2.
Form from page two now displays without page refresh on change of drop down.
When submit button from page two is pressed inserts form data into Mysql database.
Once new data is submitted into sql data base the form updates and shows data in mysql database for the specific ID in the drop down.
Page2.
form drop down info.
Form is filled with info if there is data in the database for it.
Javascript/Ajax on button submit sends input fields to page 3
Page 3.
insert data into mysql using javascript/ajax so no page refresh is required
Thanks
You need to loop through all the input fields in your form, package them into a query string, and send that to your form processing page.
Something like
var queryString = '';
for(var i = 0; i < document.formName.elements.length; ++i) {
queryString += document.formName.elements[i].name + '=';
queryString += document.formName.elements[i].value + '&';
}
//trim off the last '&' here
If you're using select boxes, you'll have to identify them in the loop above and extract their value a little differently. The query string format I used here is for a POST query; in a GET query, you need to append this to the url of the form processing page with a '?'
Consider the following example using jQuery (though you could adapt this to raw js or a different js library):
function doSubmit(event) {
event.preventDefault();
var $this = $(this);
$.ajax({
url: $this.attr('action'),
type: 'post',
data: $this.serilaize(),
success(responseHtml) {
// assume responseHtml is the next form
var newForm = ajaxifiyForm($('form', responseHtml));
$this.unbind('submit').replaceWith(newForm);
}
});
return false;
}
function ajaxifyForm(form) {
return $(form).submit(doSubmit);
}
$(document).ready(function(){
ajaxifyForm($('#your-form'));
});
Here we rely on the first page load to have the form already included on the server side. When the DOM is ready we attach an event handler to the submit event of the form. This handler overrides the normal submission process and instead uses ajax. It submits to the URL we specified in the action attribute.
When a post is successful it takes the HTML response from that post and replaces the original form with it after applying the same handler we used on the original form. This relies on the assumption that the php script(s) we are posting to always return the next form with all its values filled out.
Keep in mind you can submit file data in this way. Youd need to use an iframe as an intermediary to do that (there are other ways to do this as well that doesnt use an iframe). you can google ajax file upload for solutions to that problem.
Related
I've Googled and searched on SO quite a bit for this unique problem, but not really finding my exact solution.
I have a basic form with X number of inputs. At some point in the form, the user as the freedom to add inputs via button click if needed. When they submit the form, it goes to another page to collect the posted form data, but I want the ability for the user to click "Back" (or send them back programmatically) if the submit fails.
I have error checking setup prior to submit via javascript, but there are other things (such as a PHP mailer) that could fail and I want them to be able to resubmit their data.
The issue of course is when the browser clicks back, it - at best - refreshes the initial form that was in the DOM with input data, but I lose all of the dynamically added inputs.
I want to capture the form/data in a session and have it repopulate the DOM with the submitted version created by the user on click back.
The closest I've come is doing something like this on SUBMIT:
var theForm = $('#myForm');
sessionStorage.setItem('formData', JSON.stringify(theForm.clone(true).html().toString());
And this on postback/click back:
$('#myForm').replaceWith(JSON.parse(sessionStorage.getItem("formData")));
The problem here is I get my form, but not the data! Do I need to iterate over each input to get my data put back in the recreated form?? Why doesn't it grab the data when .clone(true)ed?
Here's the answer I ultimately got to work.
Upon form validation, I set the session to hold the form data like so:
var theForm = $('#MyForm');
sessionStorage.setItem('formHTML', JSON.stringify(theForm.clone(true).html()));
theForm.find('input,select,textarea').each(function(){
sessionStorage.setItem(this.name,this.value);
});
Then, when the DOM loads again, I have this that checks for the session and populates the form with data if it exists:
$(document).ready(function(){
if (sessionStorage.getItem("formHTML")) {
$('#MyForm').html($.parseJSON(sessionStorage.getItem("formHTML")));
}
$('#MyForm').find('input,select,textarea').each(function(i,elem){
var sessItem = elem.name, sessValue = '';
if (sessValue = sessionStorage.getItem(sessItem)) {
if(elem.type=='radio' && elem.value==sessValue){
alert(elem[i].type+' has value of "'+elem[i].value+'"');
$('[name='+sessItem+']')[i].prop('checked',true);
}
else if(elem.type=='textarea'){
alert(elem.type);
$('[name='+sessItem+']').val(sessValue);
}
else
{
$('[name='+sessItem+']').val(sessValue);
}
}
});
});
I've put a set of small images to function as links (around 50 more or less) on a page. In that same page I have a content place holder to display data from the database, and I have a table saved in phpmyadmin that has a set of fields filled with data.
What I want is when the user clicks on a certain image link, the data related to that image gets retrieved into the site. So I want the data to be retrieved to match the image clicked.
I know how to retrieve data from a database using the binding pannel in dreamweaver, and I know this has to do with filtering the data retrieved but I don't know how to do it.. How can I make this process work?
If it helps I'm also using Jquery CSS and javascript in this project.
The project looks like this:
http://i725.photobucket.com/albums/ww256/flower1991a/world_zps26b7083d.png
HTML code:
it doesnt show I took a screenshot of it:
http://i725.photobucket.com/albums/ww256/flower1991a/a_zpsa138aa52.png
jQuery code:
$(document).ready(function() {
// begin Ready
//...................................................
// When the form changes
$('#mapForm').change(function() {
var selectedContinent = $('#mapForm option:selected').val();
if (selectedContinent == 'ALL'){
$('a.dot').slideDown(1000);
}else{
$('a.dot[continent = "'+selectedContinent+'"]').slideDown(1000);
$('a.dot[continent != "'+selectedContinent+'"]').slideUp(1000);
}
});
//...................................................
// When a dot is clicked
$('a.dot').click(function(){
$('a.dot').removeClass('selected');
$(this).addClass('selected');
var city = '.city_detail#' + $(this).attr('city');
var htmlCode = $(city).html();
$('.detail_container').fadeOut(500, function(){
$('.detail_container .city_detail').html(htmlCode);
$('.detail_container').fadeIn(500);
});
});
// end Ready
});
You need to create a PHP script which takes a REQUEST variable parameter depending on the image that has been clicked, and which returns the data for that image.
You can then make a call to that PHP script via AJAX and populate whichever area of the page you want to with the data retrieved.
i am having form with many text inputs in a page
along with them i am providing zend pagination to select results.
but when i use zend paginate the user form inputs are lost as it is not submit
as the page reloads evertime i move to a new page is there any way i can maintain the user input .
Please can any one help me find a solution to this problem ..
Pseudo Code:
With javascript get the values on change and store it in a cooke (use jquery cookie plugin)
jQuery('form').on('change', 'input', function() {
jQuery.cookie(...)
})
And the solution is...
AJAX + Session
Send a ajax request on change event of every input.
Save data to Session.
Every time you load form data check for Session to fill form fields.
You can use sessions:
$form = array();
if (!empty($_POST))
{
$form = $_POST;
}
elseif (!empty($_SESSION['form']))
{
$form = $_SESSION['form'];
}
And then use $form to populate the input fields.
You could use ajax onfocusout of elements and store the value in the session.While loading the page fetch the data from the session and show it.
I want show Loader img with jQuery when you post by PHP Simple action="search.php" Not ajax post or jquery post
and Thanx for all
This problem is not solvable in a meaningful way without the use of AJAX. In other words, you need AJAX to show a "loading" image while the response from a form submission is handled by the server.
If I understand you correctly, then you have a form:
<form action="search.php" method="post">
...
</form>
And it is handled as a regular HTML form. The data is passed by the page to the server that uses PHP to handle it. Without AJAX, you have no good way of finding out when the response of the form, the search results, are ready.
Generally, what is done is that the form is submitted to the server with the use of AJAX. The form is handled by the server (PHP does its stuff). During this time, a "searching" image is shown. Then when the server responds, the image is removed and the search results are shown.
Using jQuery and AJAX on a page this could be done like this:
jsFiddle example
// The form has an id of "theForm".
// This function defines what happens when it is submitted.
$('#theForm').submit(function() {
// Replace the form w the search icon.
$("#theForm").html('Searching...<br/>' +
'<img src="http://i.stack.imgur.com/ZK0sq.gif" />');
// Make the search request to the PHP page.
// The 3 arguments are:
// 1 - The url. 2 - the data sent
// 3 - The function called when data is sent back
$.post("/ajax_html_echo/", $(this).serialize(), function(result){
// Here we replace the search image with the data
$("#page").html(response);
});
// Cancel the regular submission of the form.
// You have to do this, or the page will change and things won't work.
return false;
});
The nice thing about the above is that it degrades nicely if JS is off, since you still have the regular HTML form and its regular submit functionality to fall back on, and if JS is on, then it blocks this regular functionality with the return false and uses the AJAX.
Jquery used:
.submit()
.html()
.post()
.serialize()
I'm using codeigniter for this project. I have a search form and search form results.
Now when I click search in search form I'm being redirected to search form result and I get results.
Is it possible to create div or table in search form which is hidden at first then call the search procedure and which results it returns to get them back in the page without reloading it?
Using jquery/ajax/php ? Thank you
I assume your search result view contains just a block of HTML for the search results (like a TABLE or somesuch, not a full HTML page with BODY)? If not update the view so it just contains the code for the results. Then you can just use the $.post method to submit the form get the view and then inject it into a DIV (or element of your choice):
$(document).ready(function() {
$('#myformid').submit(function() {
var seralizedForm = $(this).serialize();
var url = $(this).attr('action');
$.post(url, serializedForm, function(results) {
$('#resultsDiv').html(results);
}, "html");
return false;
});
});
This should plug into your code with minimal modification. Change the "myformid" to an ID you set on the form tag, and change "resultsDiv" to the ID of an empty DIV you want the results to go into.
What this is going to do is bind this function to be called when the form is submitted (either by pressing enter or clicking a submit button). It will serialize the form (so you can send the values of the inputs to your controller) and get the URL to submit to by the normal "action" attribute that forms have.
It will then submit the form to that URL via a post, and the results will be loaded into a DIV with the ID of resultsDiv.
Yes, it is in fact possible.
for CodeIgniter, I'd write a controller function & view for what you would like to display. then, make an AJAX call to the page, which will be whatever you want to display on the page, and load it onto the current page.
If you are using jQuery, you can look into their Various AJAX Functions to make the ajax call and retrieve the data