Yii validate dropdown onchange - php

I am trying to validate the dropdownlist as the value of dropdownlist changes. I want to check is there an in the the table already of the selected job status.
Below is my code:
<script>
function validate_dropdown(id)
{
alert("Selected id = "+id);
//var msg = <?php echo NotificationRules::model()->validate_job($_POST['id']);?>
//alert("Message from model func = "+msg);
}
</script>
<?php
echo $form->dropDownList($model, 'job_status_id', $jobstatuslist ,
array('empty'=>'Please Select job status (required)', 'onchange'=>'js:validate_dropdown(this.value)')
);
?>
I am trying to pass js variable id to php function and send back a message if there is already an entry for the selected job status. I am able to get selected value in js function validate_dropdown(), but not able to proceed further.Anybody pls help.......

Check this bellow example. In this i'm displaying all the users in a drop down list. I'm keeping user id as option value and username as option label.
User Table:
id username
------------------
1 Heraman
2 Dileep
3 Rakesh
4 Kumar
<?php
$list=CHtml::listData(User::model()->findAll(), 'id', 'username');
echo CHtml::dropDownList('username', $models->username, $list, array('empty' => '---Select User---','onchange'=>'alert(this.value)'));
?>
In you case, you can use
'onchange'=>'validate_dropdown(this.value)
//Your script
<script>
function validate_dropdown(id)
{
alert("Selected id = "+id);
}
</script>

I solved the problem by making an AJAX call...
Final working code:
Code of dropdown in view
<?php
echo $form->dropDownList($model, 'job_status_id', $jobstatuslist ,
array(//AJAX CALL.
'prompt' => 'Please Select job status (required)',
'value' => '0',
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('NotificationRules/notificationPresent/'),
'data' => array("job_id" => "js:this.value"),
'success'=> 'function(data) {
if(data == 1)
{
alert("Rule is already present for this status, Please update existing rule.");
}
}',
'error'=> 'function(){alert("AJAX call error..!!!!!!!!!!");}',
)//end of ajax array().
));
?>
Code in controller(action)
<?php
public function actionNotificationPresent()
{
if (Yii::app()->request->isAjaxRequest)
{
//pick off the parameter value
$job_id = Yii::app()->request->getParam( 'job_id' );
if($job_id != '')
{
//echo "Id is received is ".$job_id;
$rulesModel = NotificationRules::model()->findAllByAttributes(array('job_status_id'=>$job_id));
if(count($rulesModel))
echo 1;
else
echo 0;
}//end of if(job_id)
else
{
//echo "Id id not received";
echo 0;
}
}//end of if(AjaxRequest).
}//end of NotificationPresent().
?>
Now i am getting an alert if there is any rule already with selected job status.

Related

Codeigniter cascading dropdown with data from database

I'm need help in making a cascading dropdown that contains data from the database
I found a tutorial about this
and
I've tried this
Controller:
function ajax_call() {
if(!empty($_POST['table'])){
if ($_POST) {
$table = $_POST['table'];
$arrYear = $this->my_model->get_categories($table);
foreach ($arrYear as $years) {
$arrFinal[$years->category2 = $years->category2;
}
echo "<p>2nd Category:<br>";
echo form_dropdown('year',$arrFinal);
echo "</p><br>";
}
else
{
echo "<p>2nd Category:<br>";
echo form_dropdown('year','');
echo "</p><br>";
}
}
}
My view:
$options = array(
'' => 'Select',
'category_one' => 'Category 1',
'category_two' => 'Category 2',
);
echo form_error('table');
echo "<p>Category:<br> ";
echo form_dropdown('table', $options, $this->input->post('table'), 'id="table"');
echo "</p><br>";
Script inside my view:
<script type="text/javascript">
$(document).ready(function(){
$('#table').change(function(){
var selTable = $(this).val(); // selected name from dropdown #table
$.ajax({
url: "ajax_call", // or "resources/ajax_call" - url to fetch the next dropdown
async: false,
type: "POST", // post
data: "table="+selTable, // variable send
dataType: "html", // return type
success: function(data) { // callback function
$('#year').html(data);
}
})
});
});
</script>
My Model:
function get_categories($table) {
$this->db->select('category2')->from($table);
$query = $this->db->get();
return $query->result();
}
My only problem with this is that the 2nd dropdown isn't visible on the page when loaded, and it would only appear when I select on the 1st dropdown.
How can i make set it to appear on the page without selecting on the 1st dropdown?
Can anyone help?
Ok I couldn't figure out how to do what i wanted. So instead i searched around the deep parts of the internet and found this little tutorial that was actually what i needed.
http://supundharmarathne.wordpress.com/2013/03/13/simple-ajax-drop-down-filtering-with-codeigniter/
This is happening because the ajax call to populate your table is only being triggered after the table changes $('#table').change(function(){...}). Try populating the table without waiting for such change; maybe inside $(document).ready(function(){...})
you added a completely obsolete if ($_POST) to your code. You are already checking if a variable in $_POST exists, hence it can never be empty after that. That caused your ELSE statement to relate to the second IF, not the first.
function ajax_call() {
if(!empty($_POST['table'])){
$table = $_POST['table'];
$arrYear = $this->my_model->get_categories($table);
foreach ($arrYear as $years) {
$arrFinal[$years->category2 = $years->category2;
}
echo "<p>2nd Category:<br>";
echo form_dropdown('year',$arrFinal);
echo "</p><br>";
}
else
{
echo "<p>2nd Category:<br>";
echo form_dropdown('year','');
echo "</p><br>";
}
}
and that is why you should always indent your code correctly.

Yii Create a like button using controller action

I'm building a website with Yii framework 1.1 and i'm implementing a portion wherein i have a like button associated with each post.i want to update the content of the like buttons text everytime i click on it without refreshing the page?please help?
EDIT
i did this
`id;
$foo = $data->likes;
echo CHtml::ajaxbutton($foo.' '.'Likes',
array('post/like/'.$id),
array(
'type'=>'POST',
'success'=>'js:function(data){ $.fn.yiiAjaxButton.update("label");}')
);
?>`
still doesnt work
Your View should be like bellow
<?php
$postId = 1; //Your post id
echo CHtml::Button('SUBMIT', array('onclick' => 'getComments(this);', 'data-value' => $postId, 'value' => 'Get Comments'));
?>
And Write your Ajax call some thing like
<script type="text/javascript">
function getComments(obj)
{
$PostID = $(obj).data('value');
$.get('Controller/YourMethod', {id:$PostID}, function(dataJSON)
{
//Get data in JSON formate
},'JSON');
}
</script>
EDIT
If you want to add Ajax call directly to your button, you can do as
<?php
$postId = 1;
echo CHtml::Button('SUBMIT', array('value' => 'Get Comments','onclick' => ''
. '$.get("Controller/YourMethod", {id:'.$postId.'}, function(dataJSON)
{
//Do what ever you want here
},"JSON");'));
?>

load data by ajax disappeared when validation return error

I had form content first name, last name .....etc. And tow drowpdownlist countries and cities, I loaded cities when Country drowpdownlist changed by ajax, and everything is cool.
My problems:
1- when clicked submit and had error in validation, city value will replaced with empty value
How to fix it?
2- How to use $form-> with it I mean city drowpdownlist .
Form work if no error in validation
Form after clicked on submit and return error in validation like username is empty ..etc
View:
<div class="row">
<?php echo $form->labelEx($model,'البلد'); ?>
<?php
/*
echo chtml::activeDropDownList($model,'country',$model->getcountry(),array('prompt'=>'اختر بلدك ') ,
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('current/dynamiccities'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#city', //selector to update
//'data'=>'js:javascript statement'
//leave out the data key to pass all form values through
))
);
*/
echo CHtml::activedropDownList($model,'country',$model->getcountry(),
array(
'prompt'=>'اختر البلد أو المنطقة ',
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('register/dynamiccities'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#city', //selector to update
//'data'=>'js:javascript statement'
//leave out the data key to pass all form values through
))
);
///
////
?>
<?php echo $form->error($model,'country'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'المدينة'); ?>
<?php
echo CHtml::dropDownList('city','', array());
?>
<?php echo $form->error($model,'city'); ?>
</div>
controller for cities load:
public function actionDynamiccities() /// Call Ajax
{
$country=intval($_POST['Users']['country']);
$data=Cities::model()->findAll('country_id=:country_id',
array(':country_id'=>$country));
$data=CHtml::listData($data,'id','city_name_e');
echo CHtml::tag('option',
array('value'=>''),CHtml::encode('Select Your City '),true);
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
};
}
If you look at this line
echo CHtml::dropDownList('city','', array());
It is obvious that the list is empty, and it would also be empty if you wanted to edit the content later.
I would suggest using something like
echo CHtml::dropDownList('city', $model->city, empty($model->country) ? array() : CHtml::listData(Cities::model()->findAllByAttributes(array('country_id' => $model->country)),'id','city_name_e'));
Here i don't know if you should use $model->country or $model->country_id, depends on your model.

AJAX form in Codeigniter responds with error when valid [half working]

From further developments, I have a AJAX and CI email form that works perfectly with javascript disabled (using Codeigniter code) and when on using AJAX there are a few bugs.
When there are missing boxes and press submit it pops up with the error mmessage-great, but when filled in correctly and on submit it still posts the error even though its right and the email i still receive in my inbox.This is really bugging me as its something in my AJAX code and i think i am missing something in my controller.
Another question:On the AJAX form it is posting personal error/success messages- is there a way of echoing CI $success and echo validation_errors(); in this so they are the same?
The code is what i have so far:
TO see my controller follow this link: Codeigniter AJAX email validation
VIEW
<h1>Contact</h1>
<div id="contact">
<?php
//This is loaded in the view as it wont be used in the other pages
$this->load->helper('form');
echo form_open('contact/send_email');
//success message if passed validation checks
echo '<div id="success">';
echo $success;
echo '</div>';
// empty div for error messages (ajax)
echo '<div id="errors">';
// empty div for error messages (php)
if(validation_errors() != ""){
echo '<h3>Please correct the following errors:</h3>';
echo validation_errors();
}
echo '</div>';
echo form_label('Name: ', 'name');
$data = array (
'name' => 'name',
'id' => 'name',
'value' => set_value('name')
);
echo form_input($data);
echo form_label('Email: ', 'email');
$data = array (
'name' => 'email',
'id' => 'email',
'value' =>set_value('email')
);
echo form_input($data);
echo form_label('Message: ', 'message');
$data = array (
'name' => 'message',
'id' => 'message',
'value' =>set_value('message')
);
echo form_textarea($data);
?>
<br />
<?php
echo form_submit('submit', 'Send');
echo form_close();
?>
AJAX
<script type="text/javascript">
$(function() {
$('form').submit(function() {
// get the form values
var form_data = {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
};
// send the form data to the controller
$.ajax({
url: "<?php echo site_url('contact/send_email'); ?>",
type: "POST",
data: $(form_data).serialize(),
success: function(msg) {
if(msg.validate)
{
$('form').prepend('<div id ="success">Success</div>');
$('#success').fadeOut(5000);
}else
$('form').prepend('<div id ="errors">Error</div>');
$('#errors').fadeOut(5000);
}
});
// prevents from refreshing the page
return false;
});
});
</script>
Looks to me like this line (in your javascript)
if(msg.validate)
is looking for an object, where your script isn't actually parsing any JSON or returning any JSON.
What I can only assume would be a good idea here (after looking at your controller too) would be to check if the <div id="errors"> has anything inside it in the response
Then in you javascript you would need to make a few changes
success: function(msg) {
if(msg.validate)
{
$('form').prepend('<div id ="success">Success</div>');
$('#success').fadeOut(5000);
}
else
{
$('form').prepend('<div id ="errors">Error</div>');
$('#errors').fadeOut(5000);
}
});
will become
success: function(msg) {
$msg = $(msg);
// check to see if the div with id="errors" contains a h3 tag
if($msg.filter('#errors').find('h3').length < 1)
{
$('form').prepend('<div id ="success">Success</div>');
$('#success').fadeOut(5000);
}
else
{
$('form').prepend('<div id ="errors">Error</div>');
$('#errors').fadeOut(5000);
}
});
Note: I've written this off the cuff so I haven't actually tested it but it should point you in the right direction.
Edited to use id selectors and not class selectors (habit of mine)

How can I update my cart with Ajax?

I would really need some help from to AJAX Guru master overthere to help me building my update cart function on my website in AJAX.
So basically, what I would like to do is, when I modify one of my product in one input_dropdown, my 'update_cart' function is automaticaly called and my prices are updated as well as my input
EDIT : I rewrite my question since I made some progress thanks to Matei
Here is my view :
<?php
$options = array(
'0' => '0',
'1' => '1',
'2' => '2',
'3' => '3',
'4' => '4',
'5' => '5',
'6' => '6',
'7' => '7',
);
if($product['quantity']==0){
$value[$product['title']] = set_value('quantity'.$product['title']);
}else{
$value[$product['title']] = $product['quantity'];
}
$data0 = 'class="quantSelect" value="'.$value[$product['title']].'" id="quant'.$product['title'].'"';
echo form_dropdown('quantity'.$product['title'], $options, $value[$product['title']],$data0);
?>
</td>
<td>
<?php echo $product['price'] ?>
</td>
<td id="<?php echo 'price'.$product['title']?>">
$<?php echo $total[$product['title']] ?>
</td>[/code]
Well, everything is in a foreach loop but I think that here, it doesn't matter.
Then I tried to set up the Matei AJAX function :
$(".quantSelect").click(function(){
$.POST("<?php echo base_url().'main/update_cart';?>",
{product_id:$('<?php echo $product['quantity']; ?>').val(),quantity:$('<?php echo 'quantity'.$product['title'] ?>').val()},
function(data){
if(data.success) {
$("<?php echo 'price'.$product['title']?>").val(data.some_returned_value); // update value of an text input or textarea (view more info about jQuery selectors)
$("#totalPriceWithTaxes").html(data.some_other_returned_value); // update value of a paragraph
}
}, 'json');
});
And at last the update cart function :
function update_cart(){
$success = false;
if(!empty($_POST['product_id']) && !empty($_POST['quantity']) && is_numeric($_POST['quantity'])) {
// I get all the information i need here in order to calcul the final price
//We calcul the final price with taxes, shipping and everything.
$data['totalPriceWithTaxes'] = $data['tax'] + $data['totalPrice'] + $data['Shipping']->shipping;
$this->session->set_userdata('totalPriceWithTaxes', $data ['totalPriceWithTaxes']);
$success = true;
$some_returned_value = 69;
$some_other_returned_value = $data['totalPriceWithTaxes']; // the final price
}
echo json_encode(array("success" => $success,
"some_returned_value" => $some_returned_value,
"some_other_returned_value" => $some_other_returned_value));
}
Here we are, so I can't see any update. If someone could help me to figure out how to set up that AJAX Function, I would deeply appreciate :)
I recommend you to take a look at jQuery.post() method of jQuery library.
Let's see the following example:
Javascript code:
$("#submit-button").click(function(){
$.POST("/PATH_TO/update_cart.php",
{product_id:$('#product-id').val(),quantity:$('#quntity').val()},
function(data){
if(data.success) {
$("#form-field-id").val(data.some_returned_value); // update value of an text input or textarea (view more info about jQuery selectors)
$("p#form-p-id").html(data.some_other_returned_value); // update value of a paragraph
}
}, 'json');
});
For more info about jQuery Selectors please check this
PHP code:
<?php
$success = false;
if(loged()) { // verify if the user is loged (if it's needed)
if(!empty($_POST['product_id']) && is_numeric($_POST['product_id']) && !empty($_POST['quantity']) && is_numeric($_POST['quantity'])) {
// use here your additional code
// update database
// if every condition is applied then confirm that the fields are updated
$success = true;
$some_returned_value = "data has been successfully updated";
$some_other_returned_value = 45.3; // the final price
}
}
echo json_encode(array("success" => $success,
"some_returned_value" => $some_returned_value,
"some_other_returned_value" => $some_other_returned_value));
?>
This is a simple example about how you can use jQuery POST method and PHP for updating data you want. I didn't use any of your code, but you can try to update your cart like this. jQuery is a powerfull library, so I'll recommend you to take a look at it.

Categories