how to pass parameters using auto redirect droplist in codeigniter - codeigniter

Hi guys Im trying to make a drop-down list of countries and when the user select a country that redirect to a specific page created dynamically actually i manage to make the redirection work using javascript, but i need to take more parameters to the method inside the controler like the county "id" with out exposing it on the uri, so is that possible using $_post also i should not use button submit.
this is my code
view page
<?php echo form_open('site/country');
$options = array();
$js = 'id="country" onChange="window.location.href= this.form.CTRY.options[this.form.CTRY.selectedIndex].value"';
$options['#'] = "(please select a country)" ;
foreach ($list as $row):
$value= site_url()."/site/country/".url_title($row->name);
$options[$value] = $row->name ;
endforeach;
echo form_dropdown('CTRY', $options,'',$js);
//$test =array ('number' => 10)
//echo form_hidden($test);
echo form_close();?>
this is my method in controller
function country($data)
{
echo 'this is taking you to county= '.$data;
}

Why don't you do something like #Joseph Silber described.
Use jQuery to perform an ajax request when the drop-down list is changed, also managing the redirect?
Something like;
$('#my-drop-down').change(function() {
$.ajax({
url: '/site/country',
type: 'post',
data: $("#my-form").serialize(),
success: function( response.redirect ) {
window.location.href = response.redirect;
},
error: function( response ) {
alert('Oops');
}
});
});
By using serilaize(), you can post all data from the form, or just add the parameters you want to pass.
E.g data: 'id='+$('#id').val()+'&country='+$('#country').val()

Related

Ajax data not being sent to controller function (CodeIgniter)

I have an anchor tag and would like its data-id to be sent to a function in the controller which would in turn retrieved data from the database through the model.
However the data is not getting past the controller. The ajax response is showing that the data was sent but controller shows otherwise.
Here is my ajax code:
$(document).on("click",".learn-more",function(){
var sub_item_id = $(this).data("id");
$.ajax({
url:"<?php echo base_url();?>Designs/business_cards",
type:"POST",
data:{sub_item_id:sub_item_id},
success:function(data){
console.log(data);
},
error: function(error){
throw new Error('Did not work');
}
})
});
I had set datatype:"json" but the data was not being sent so I removed the datatype and it worked,the ajax part that is.Or atleast the response showed that data was sent.
My controller code is:
function business_cards(){
$id = $this->input->post('sub_item_id');
$data['quantity'] = $this->subproduct_model->get_quantities($id);
$this->load->view('category/business-cards',$data);
}
My model code is:
public function get_quantities($sub_item_id){
$this->db->select('quantities');
$this->db->where('id',$sub_item_id);
$query = $this->db->get('sub_products');
return $query->result_array();
}
HTML Code which includes the anchor tag
<?php foreach ($results as $object):?>
View Prices
<?php endforeach?>
The data-id is displaying the correct value as per the iteration.
When I check the result array of the model code it is an empty array showing that the $sub_item_id was not passed in the controller. What could be the problem?
I just copied your code and I was able to get the value in the controller.
In your controller function do var_dump($id). Then in your developer tools (F12) check the console. Since you have console.log(data) that var_dump should be in the console. It won't show on the screen.
Some other things to check:
Does your db have records with that ID? Could your db result array be empty because it actually should be?
Are you sure that the data-id actually has a value when you click the tag?
it is not passed to the controller because you forgot to put a parameter inside the function of your controller.
Note: you cannot use input post because you're not using form.
function business_cards($id){ //put a parameter here, serve as container of your passed variable from **ajax**
//$id = $this->input->post('sub_item_id');
$data['quantity'] = $this->subproduct_model->get_quantities($id); //pass the id to your model
$this->load->view('category/business-cards',$data);
}
change your ajax code to this..
$(document).on("click",".learn-more",function(){
var sub_item_id = $(this).data("id");
$.ajax({
url:"<?php echo base_url('Designs/business_cards/"+sub_item_id+"');?>", //pass the id here
type:"POST",
success:function(data){
console.log(data);
},
error: function(error){
throw new Error('Did not work');
}
})
});

Frontend custom post submission results in wp_insert_post() undefined

I've been struggling for a few days with this issue and I really hope you can help me out.
I've created a plugin, which is located in:
'/wp-content/plugins/my-cool-plugin'.
My plugin allows users to post a custom post type via a form on a public page, basically anyone should be able to post something.
Using jQuery, I listen to when my frontend form is submitted and using Ajax I pass the data from the form to a php file to process it into a post.
This file is located at:
'/wp-content/plugins/my-cool-plugin/inc/processor.php'.
Below is the content of my processor file:
$var1= $_POST['some'];
$var2= $_POST['data'];
$new_post = array(
'post_type' => 'my_custom_post',
'post_status' => 'publish',
'mcp_1' => $var1,
'mcp_2' => $var2
);
$post_id = wp_insert_post( $new_post, $wp_error );
if ($wp_error == 'false'){
$post_url = get_permalink( $post_id );
echo $post_url;
}else {
// some sort of error
}
When I test my form, it results in the following error:
Call to undefined function wp_insert_post() on line ... which is the following line:
$post_id = wp_insert_post( $new_post, $wp_error );
Do I need to include something since I'm not in the WordPress 'scope' anymore?
Or is there another (much better) way for inserting custom posts from a front end form?
Why are you running the file out of wordpress scope? That is not the best practive. Instead you could run it in wordpress scope and user wordpress native ajax.
add_action('wp_ajax_yourplugin_create_post', 'yourplugin_create_post');
add_action('wp_ajax_nopriv_yourplugin_create_post', 'yourplugin_create_post');
function yourplugin_create_post() {
// your code here
}
Then you would need your ajax url to be passed from php to js:
function your_plugin_ajaxurl() {
?>
<script type="text/javascript">
var yourPluginAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
<?php
}
add_action('wp_head','your_plugin_ajaxurl');
Then you can use your ajax request but you would need to indicate action:yourplugin_create_post and url = yourPluginAjaxUrl
Try adding
require(dirname(__FILE__) . '/wp-load.php');
It took me some time to process Nick's answer, but I finally got it to work! Like Nick said, I dropped using the process file because is was out of the scope of WordPress. I moved my post creation from my proces file to a new function in the plugin init file (my-cool-plugin.php), as Nick suggested. This resulted in the following new function:
add_action('wp_ajax_coolplugin_create_post', 'coolplugin_create_post');
add_action('wp_ajax_nopriv_coolplugin_create_post', 'coolplugin_create_post');
function coolplugin_create_post() {
$var1 = $_POST['some'];
$var2 = $_POST['data'];
$new_post = array(
'post_type' => 'my_custom_post',
'post_status' => 'publish'
'post_title' => 'Some title'
);
$post_id = wp_insert_post( $new_post, $wp_error );
// check if there is a post id and use it to add custom meta
if ($post_id) {
update_post_meta($post_id, 'mcp_1', $var1);
update_post_meta($post_id, 'mcp_2', $var2);
}
if ($wp_error == false){
$post_url = get_permalink( $post_id );
echo $post_url;
}else {
// some sort of error
}
}
I also had to change the way I inserted my custom values into the newly created post, because the wp_insert_post() function only accepts default post parameters (see the wp_insert_post documentation for these parameters).
Next to my insert/create post function I also had to make some adjustments to my javascript file, which retrieves the filled in data from my form. Therefore (as Nick suggested) I needed to pass my Ajax URL from PHP to JS by adding the following function to my-cool-plugin.php like this:
function your_plugin_ajaxurl() { ?>
<script type="text/javascript">
var coolPluginAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
<?php }
add_action('wp_head','your_plugin_ajaxurl');
By adding the coolPluginAjaxUrl variable to the head I'm able to use the URL in my javascript to post the data to when my form is submitted, like this:
$( '#form' ).on( 'submit', function(e) {
var request;
e.preventDefault();
var val_one = $( '#val-one' ).val();
var val_two = $( '#val-two' ).val();
var formData = {
action: 'coolplugin_create_post',
some: val_one,
data: val_two,
};
request = $.ajax({
type: 'POST',
url: coolPluginAjaxUrl,
data: formData,
});
});
The formData holds the coolplugin_create_post action defined in PHP and the request is posted to the coolPluginAjaxUrl URL, defined in the head.
Thanks Nick for pointing me into the right direction and I hope that my solution will also help others. Please note that I've stripped my code of several security measures for others to easily understand how the code works.

Zend Form: onchange select load another view content

In my application I have a form in controller/index that consists out of 3 select boxes. When all three boxes have a value selected I need to show additional html and extra form options in the same view based on those select values. The obvious solution seems to make an ajax call to another action that handles the database operation and creates a view and loading that view into the controller/index.phtml
I have been able to load a view of another action in the index.phtml by using:
$('#select').change(function() {
event.preventDefault();
var id = $(this).attr('id');
$('#results').show();
$('#results').load('/controller/index/' + $(this).attr('value'));
return false;
});
However I need to pass the variables of all three select boxes and for that I alternatively used:
$('#select1').change(function() {
var select1 = $('#select1').val();
var select2 = $('#select2').val();
var select3 = $('#select3').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: '/controller/index/',
data: { select1: select1, select2: select2, select3: select3},
success: function(result){
var return1 = result.return1;
var return2 = result.return2;
}
});
});
The last method works in as far that I do see the variables passed in the headers and the response contains the view, but I cant fix it that just the content of the ajax view is placed within the index view. (Ofcourse by not using AjaxContent switching, the ajax view will load but that includes the complete layout as well.) Anything that I echo in the ajax action or ajax view do not show in the index view. Any pointer would be more than welcome
EDIT
the ajax action now looks like
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$select1 = $this->_request->getParam('select1');
$select2 = $this->_request->getParam('select2');
$select3 = $this->_request->getParam('select3');
// DO THE OTHER STUFF AND LOGIC HERE
$results = array(
'return1' => 'value1',
'return2' => 'value2'
);
$this->_response->setBody(json_encode($results));
and the controller init
public function init() {
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('ajax', 'json')->initContext();
}
So everything works, I can see the returned values in the response by using developer tool (network) in my browser, however I just do not know how I can use this to "update" the view
You can do two things:
You can enable the layout of the action you are calling via ajax. See you have disabled layout so even if the view phtml file of the ajax action contains something, it won't show. You can enable layout, use text/html dataType instead of json and show the returned HTML somewhere.
Or, in the success event of the ajax call, write javascript codes to update DOM.
Thanks #Salman for your suggestions as they lead me in the right direction and I managed to solve the problem.
I managed to pass multiple parameters with the ajax .load() call by passing them as get parameters.
The results of the ajaxAction could then be formatted in the ajax.ajax.phtml view and were consecutively
shown within the #results div that resides in the index.phtml where the select boxes are.
controller/index.phtml
<div id="results" style="display:block;">Select all three values</div>
IndexController init and ajaxAction
public function init() {
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('ajax', 'html')->initContext('html');
}
public function ajaxAction() {
$select1 = $this->_request->getQuery('select1');
$select2 = $this->_request->getQuery('select2');
$select3 = $this->_request->getQuery('select3');
$form = new Application_Form();
// Database operations and logic
$this->view->form = $form;
$this->view->array = $somearray;
}
}
jquery script in index.phtml
$(document).ready(function(){
$('.selector').change(function() {
var select1 = $('#select1').val();
var select2 = $('#select2').val();
var select3 = $('#select3').val();
if ( select1 && select2 && select3) {
$('#results').show();
$('#results').load('/controller/ajax?select1=' + select1 + '&select2=' + select2 + '&select3=' + select3);
}
});
});
controller/ajax.ajax.phtml
<?php if ( $this->array ) : ?>
<?php echo( $this->form ); ?>
<?php else: ?>
Nothing found for selected values
<?php endif ?>

Populating a dropdown based on the selection of another dropdown using Jquery in Codeigniter

I am using Codeigntier and I have the following dropdown in my view file which populates a list of subjects.
<?php echo form_dropdown('subject1', $dropdown_subjects,'',
'class="required" id="subject1"'); ?>
Now when any one selects any value from the dropdown above, I want to send the value to my controller using jquery and query in the following table( SELECT teacherid from table3 WHERE subjectid=$subjectid) to get the teacherid so that I can populate the teacherid list in another dropdown select. If any user changes his selection from the first dropdown I want to get the values of the second dropdown changed also
Table Name: table3
subjectid teacherid
1 1001
2 1003
So the bottom line is I want to populate a dropdown based on another dropdown. I have found couple of tutorials on this topic but I couldn't really understand those(I know I am stupid).
Would you please kindly show me how my view and controller should look like if I want to achieve this?
Thanks :)
EDit
Hi, this is how my controller and view file looks like :
My Controller
$id= $this->input->post('subject_id'); //receiving the ajax post from view
$this->db->select('teachername,teacherid');
$this->db->from('subject_teacher');
$this->db->join('teacher', 'teacher.teacherid = subject_teacher.teacherid');
$this->db->where('subjectid',$id);
$records = $this->db->get('');
$data=array();
$data[''] = 'Select';
foreach ($records->result() as $row)
{
$data[$row->teacherid] = $row->teachername;
}
return ($data); // I need help here... How to send the data as json?
My view:
<script>
$(function(){
$("#subject").change(function(){
$.ajax({
url: "<?echo base_url();?>mycontroller/function",
data: {subject_id: $(this).val()},
type: "post",
success: function(msg){
$("#teacher").html(); // I need help here...how do I get the value from controller and append to my another dropdown named teacher?
})
})
}); // function ends here
</script>
<?php echo form_dropdown('subject1', $dropdown_subjects,'',
'class="required" id="subject1"'); ?>
<select name="teacher" id="teacher">
<option value="">Select</option>
</select>
Please make the necessary changes in my View and Controller for me.
Thanks in Advance :)
You can do this by using jquery ajax. First you post subject_id to ajax page, ajax page will return the list of teacher in combo box and then the result is populated in the first page.
$("#subject").change(function(){
$.ajax({
url: "your-ajax-page-url",
data: {subject_id: $(this).val()},
type: "post",
success: function(msg){
$("#teacher").html();
})
})
This is the edited controller
$id= $this->input->post('subject_id'); //receiving the ajax post from view
$this->db->select('teachername,teacherid');
$this->db->from('subject_teacher');
$this->db->join('teacher', 'teacher.teacherid = subject_teacher.teacherid');
$this->db->where('subjectid',$id);
$records = $this->db->get('');
$output = null;
foreach ($records->result() as $row)
{
$output .= "<option value='".$row->teacherid."'>".$row->teachername."</option>";
}
echo $output; // HTML example
you may do it like this :
you will have to create a function inside your controller which will populate the data but instead of outputting your view you will have to put it inside a var like this
$outout = $this->load->view('myselect_output',$data,TRUE);
and then in your main view you will have to manipulate the DOM with jquery or any other js library ..

How to refresh content after ajax update?

I have an admin page for a WordPress plugin that, thanks to the stackoverflow community, I've learned how to add ajax calls to all of the functions that add/delete/update questions and answers for the plugin to access.
To help visualize it:
The next step is to refresh the content after a successful ajax call. Of course I don't want to just re-load the page and I assume refreshing the entire page might cause the answer divs to collapse, which would be undesirable. So refreshing only the related content is best.
The list of questions is generated with the following call to the database:
<?php
$qresult = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "ccd_ex_questions ORDER BY sort ASC");
$qcount = $wpdb->num_rows;
foreach( $qresult as $key => $qrow ) {
?>
<div id="question<?php echo $qrow->id; ?>" class="display-questions">
<form id="update-question-<?php echo $qrow->id; ?>" action="" method="post">
//question form and content
</form> {snip...}
and the answers are done similar and within the loop generating the list of questions:
<?php
$aresult = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "ccd_ex_answers WHERE question_id = " . $qrow->id . " ORDER BY sort ASC");
foreach( $aresult as $key => $arow ) {
?>
<form id="update-answer-<?php echo $arow->question_id."-".$arow->id; ?>" action="" method="post">
//answer form and content
</form> {snip...}
The following is one of the jQuery functions using an ajax call to update content:
//Add New Answer
jQuery(document).ready(function($) {
$('.asubmitbutton').live("click", function(){
var thisasubmit = $(this).data('asubmit');
$(thisasubmit).submit(function(){
// Get the proper instance of the form fields for the variables
var answer = $(this).find('.answer').val();
var sort = $(this).find('.sort').val();
var correct = $(this).find('.correct').val();
var question_id = $(this).find('.question_id').val();
$.ajax({
type: 'POST',
url: ajaxurl,
data: {
action: 'ccd_ex_insert_answer',
answer: answer,
sort: sort,
correct: correct,
question_id: question_id
},
success: function(data, textStatus, XMLHttpRequest){
console.log(data);
console.log(answer);
console.log(sort);
console.log(correct);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
return false;
});
});
});
And while we're at it, here's the php function handling this ajax call:
//Add an answer
function ccd_ex_insert_answer() {
global $wpdb;
$wpdb->insert( $wpdb->prefix . 'ccd_ex_answers', array(
'answer' => $_POST['answer'],
'sort' => (int)$_POST['sort'],
'correct' => (bool)$_POST['correct'],
'question_id' => (int)$_POST['question_id']
)
);
}
add_action( 'wp_ajax_ccd_ex_insert_answer', 'ccd_ex_insert_answer' );
As is, everything works except that changes don't show until the next page re-load.
I presume that I need to add the functions to refresh the data into the success: handler, but I couldn't find an example that spoke to updating the content that is pulled from the database.
So my question is: How to refresh only the updated content after ajax call and, if possible, maintain the visibility of expanded divs?
Any help would be greatly appreciated! Note: I am barely an intermediate jQuery user and this is my first ajax attempt, so it's better to assume I know nothing if it prevents something important from shooting over my head. ;)
UPDATE: I think I am making progress, but still missing something. Problem with the proposed solution is that .html(data) was returning '0'. By removing the line: url: ajaxurl, from the ajax call, what is returned now is the entire page content. What I really need to be returned is just the updated content.
First, you want to do a POST to a page/url that will return only the updated content for a certain element (say, with id="id"). For example, you do a call
$.ajax({url:"http://example.com/newcontent.php", ...});
and the PHP page simply returns
<?php echo "thisisnewcontent"; ?>
You can then update the html of any DOM element with
$("css_selector").html(newContent); // newContent will contain "thisisnewcontent"
You should do this update in the ajax success function, where 'data' represents the data that you received from the server.
$.ajax({ ..., success: function(data, textStatus, XMLHttpRequest) {
$("#id").html(data);
});
You can read more about ajax() and html() here http://api.jquery.com/jQuery.ajax and here
http://api.jquery.com/html/
Good luck!

Resources