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
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 would like to use ajax to retrieve information from a php page that will update "onchange" of a select drop down menu. (<select>). i used jquery to check if it is changed
$('#names').change(function() {
//code to get the info into the div comes here
})
all id like to do is work the page "check.php" with "?v=valueOfNamesGoesHere"
and return the information into the div names "output"
I have tried
$('#names').change(function() {
$('#output').load('check.php?v=' + $('#names').val());
});
without success. I have checked the "check.php" itself with the information that is supposed to get passed into it. for example "check.php?v=john" and i got the information needed in the page itself. (when i go directly to mysite.com/check.php?v=john).
what am i doing wrong?
Thanks!
use
$('#names').find(":selected").text()
instead of $('#names').val() as it is a dropdown..
I know I could use a php include to read the html from a file on the server but how do I write a file to the server once the user clicks to navigate to the next page?
I have a div that is changed by jquery on the 1rst page. I want to read the changed div when the user clicks to go to the 2nd page and write the html from the 1rst page to the 2nd page.
You can use combination of javascript and php code.
jquery
get the value of changed div and place it into a hidden field, wrapped within a form tag and submit the form to the next page
php
and on next page, get your hidden field value from $_post array and display it.
So you have a div that is changed via jQuery:
<div id="something">something here</div>
To access the HTML inside your div,
var myHTML = $('#something').html();
Then Use AJAX to send the value to the second page:
$.ajax({
url: 'secondpage.php',
data: {
'key' : myHTML
}
type: 'post'
});
In secondpage.php, check for $_POST['key'] as follows
if( isset($_POST['key']) ) {
// myHTML was sent successfully
}
Not sure if it's a good idea to do this as users are clicking because it would take a while for the document to get updated, and what if multiple users were trying to access the same page? You can use something called a cronjob, which basically executes PHP from your site's server at a specified time interval. I did this to update my website with my Twitter feed every 10 minutes, but doing it on every click would be too slow. What exactly are you trying to do?
When the user clicks on "go to next page" link, send AJAX request to
some PHP file.
The AJAX request should contain the div html (use
jQuery: $(this).html())
In the php file write the html, and return
information to AJAX (true/false).
When AJAX success go to the next page.
I am using CodeIgniter's pagination API. I found some issues when I click on particular page: it shows controller and pages in URL. I dont want to show all the details in URL.
I have large number of search criteria.
e.g.
http://localhost/myapp/search/pages/2&fromAge=25...... so on
Is there any way to handle it using POST method rather than GET?
Please help.
If you want to use the pagination with POST, there is a simple way to do that with the standard CI pagination and without Ajax. You can perform a POST instead of the GET
when one click on the pagination links.
For this you need an hidden field in the form (named page in my example) which contains the page number and you need to set the action attribute of the form with the link before submitting it (it is necessary for the pagination class to compute the current page). Find below a sample code in jquery :
// bind onclick event to the pagination links
$('.pagination a').click(function () {
var link = $(this).get(0).href; // get the link from the DOM object
var form = $('#form1'); // get the form you want to submit
var segments = link.split('/');
// assume the page number is the fifth parameter of the link
$('#page').val(segments[4]); // set a hidden field with the page number
form.attr('action', link); // set the action attribute of the form
form.submit(); // submit the form
return false; // avoid the default behaviour of the link
});
On the server side, you read the page number from the
POST field named page to perform the db query with pagination and you build the pagination links with the usual function
What about using AJAX?
http://tohin.wordpress.com/2008/08/12/codeigniter-ajax-pagination/
http://codeigniter.com/wiki/AJAX_Pagination_with_CI_Pagination_Library/
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.