I was trying to figure out how to check if the value entered in text box is existing in
database or no as soon as it is entered or on tab event using cakePHP and javascripts. I am new so please can someone help?
Thanks,
Create a validation for Unique on the field. It will check the value of the field before it saves it. If it exists, it will tell the user that the value already exists.
assumptions:
table: posts
model:Post
controller:Posts
and the field about which you need notification of pre-existence is post_title
Now do something like this
In view:
let id of text field for post_title is PostPostTitle
$('#PostPostTitle').bind({
blur:function(){
var newTitle = $(this).val();
if(newTitle){
$.ajax({
url:'Posts/checkTitle/',
type:'POST',
data:{title:newValue},
dataType:'JSON',
success:function(data){
if(data.ok==1){
//dont show any error and let the user submit
}else {
//show error notification in desired format
}
}
})
}
}
});
Now in your controller make an action with name checkTitle
controller code will be like this
public function checkTitle(){
//fetch the vlaue of title from appropriate key of the controller class
//variable $this->params (in cake v<2) or from $this->reuest (cake v2.x+)
$this->layout = 'ajax';//or json or null what ever you prefer
$this->autoRender = false;
//assumig that you have fetched value of newTitle in $newTitle from requestVar
//make a database query to post table
$response = array('ok'=>0);
$data = $this->Post->find('count',array('conditions'=>array('post_title'=>$newTitle)));
if($data==0) {
$response['ok']=1;
}
echo json_encode($response);
exit;
}
Related
I m validating a data by clicking the submit button and then again loading the views. I want just to show the errors on the page before loading the controller. Its is not a form validation. it is just a data validiation.
I think you can do the validation using AJAX.
in view page
<script type="text/javascript">
$(document).ready(function() {
/// make loader hidden in start
$('#loading').hide();
$('#email').blur(function(){
var email_val = $("#email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
if(filter.test(email_val)){
// show loader
$('#loading').show();
$.post("<?php echo site_url()?>/user/email_check", {
email: email_val
}, function(response){
$('#loading').hide();
$('#message').html('').html(response.message).show().delay(4000).fadeOut();
});
return false;
}
});
});
</script>
in controller function
public function email_check()
{
// allow only Ajax request
if($this->input->is_ajax_request()) {
// grab the email value from the post variable.
$email = $this->input->post('email');
// check in database - table name : tbl_users , Field name in the table : email
if(!$this->form_validation->is_unique($email, 'tbl_users.email')) {
// set the json object as output
$this->output->set_content_type('application/json')->set_output(json_encode(array('message' => 'The email is already taken, choose another one')));
}
}
}
Basically I have a form in the view with one input enabled, and multiple inputs disabled (only to show information derivated from the unique input).
Now, I need to send this input to the controller to make a query, and send back to the view an array with the fields information but without refresh the site (because I cant loose the progress that I have in this page).
Maybe the solution is to use javascript to send the controller the input field, and in the function return the array of values to refresh the form, but how?
EDIT: Sorry for my bad english.
var input = $('#input').val();
$.ajax({
type:"POST",
url: <?php echo base_url().'controllername/action'?>
data: {input : input},
success: function(data){
// this data should be contain an arra
$('#where_to_insert_array').html();
}
});
In controller action and in action
function action()
{
$data = $this->input->post('input');
get data from database on $data
make its array and then echo it
echo array();
}
Finally I understand how to pass the array from the controller to the view dynamically, this is the code:
The view javascript:
function getClient(){
if($('#cedula_cliente').val()){
$.ajax({
type : "post",
url: "<?php echo base_url().'index.php/clientes/getClienteFactura'?>",
cache: false,
data : {cedula : $('#cedula_cliente').val()},
success : function(json){
var obj=jQuery.parseJSON(json);
if(obj[0]){
$('#nombre_cliente').val(obj[0].nombre);
$('#apellido1_cliente').val(obj[0].apellido1);
$('#apellido2_cliente').val(obj[0].apellido2);
$('#dir_cliente').val(obj[0].dir);
}else{
alert("Usuario no encontrado");
}
},
});
}else{
alert("Debe ingresar una cédula de usuario");
}
}
Im using obj[0] because "cedula" is the primary key and It never will return more than 1 row.
And this is the controller function:
public function getClienteFactura(){
$cedula = $this->input->post('cedula');
$query = $this->Client_model->getClientByCedula($cedula);
echo json_encode($query);
}
Thanks for the answers, maybe I should have looked better on google, the key to solve the problem was Json.
I am new to cake and mysql, and am trying to create a simple job tracking app. I want to have a dropdown box for each job with a list of the status' a job can be at. When a user changes the active item in the box I want to save this into the database.
Any help in how to handle this would be very much appreciated. Below is what I have tried so far:
How I create the set of forms in the view with the options taken from the enums in my database table:
<?php $id = count($jobs)-1; ?>
<?php for ($job = count($jobs)-1; $job >= 0; --$job): ?>
<tr>
<td>
<?php echo $this->Form->input('status'.(string)$id, array('type'=>'select', 'class' => 'statusSelect','label'=>'', 'options'=>$states, 'default'=>$jobs[$job]['Job']['Status'])); ?>
</td>
I am using a jquery script to set an on change listener for each dropdown and call an action in my controller:
$(".statusSelect").change(function(){
//Grab job number from the id of select box
var jobNo = parseInt($(this).attr('id').substring(6));
var value = $(this).val();
$.ajax({
type:"POST",
url:'http://localhost/projectManager/jobs',
data:{ 'id': jobNo,
'status':value},
success : function(data) {
alert(jobNo);// this alert works
},
error : function() {
//alert("false");
}
});
});
And I have this function in my controller:
public function changeState($id = null, $status = null) {
//I don't think the id and status are actually
//being placed as arguments to this function
//from my js script
}
Thank you!!!
You are POSTing to /projectManager/jobs, which corresponds to ProjectManagerController::jobs().
Your function is declared as public function changeState($id = null, $status = null). Assuming changeState(..) is a function within ProjectManagerController, this corresponds to /projectManager/changeState/$id/$status.
You need to switch the URL the AJAX is POSTing to. You can either do something like:
url:'http://localhost/projectManager/changeState/'+jobNo+'/'+value', remove the data {} and leave your function as is, or you can do
url:'http://localhost/projectManager/changeState', leave the data {}, change your function to changeState() and then use $this->request->data within changeState() to access the data.
I am guessing you have another function, jobs(), and that is why the AJAX is working properly and the alert is generating.
I am currently new to the Yii framework, and I was wondering if anyone had good example or experience with Javascript to assist me creating a ajax submit button. The entire purpose of this submit button is to favorite the current page and send the data to the / needed. The label of the button must change depending on the information from the database ( button label -> favorite or un-favorite ).
Here the current functionality from my basic button. I would like to do the next step and start using ajax. If anyone is interested in teaching a newbie. I would be up for the challenge.
<div>
<?php echo CHtml::button('Favorite', array('submit'=>array('user/favoritePage', 'playerId'=>$player->id, 'pageId'=>$page->id, 'bool'=>'FALSE'))); ?>
</div>
$toggle = $model->is_favourite? "false": "true";
$actionUrl = Yii::app()->createUrl('user/favoritePage', array(
'playerId'=>$player->id, 'pageId'=>$page->id
));
//render input type=submit with id=favourite-button
echo CHtml::ajaxSubmitButton(
($model->is_favourite? 'Favourite' : 'Un-Favourite'), //label button
$actionUrl,
array(
'data' => 'js:{bool: $("#favourite-button").attr("toggle")}', //get current status of button (favourite or not) as param to post
'success'=>'js:function(data){
//ajax success, update label and status of button for next time
data = $.parseJSON(data);
$("#favourite-button").val(data["label"]);
$("#favourite-button").attr("toggle", data["toggle"]);
}'
),
array(
'id' => 'favourite-button', // set id for button
'toggle' => $toggle // set attribute to hold favourite status, or you can set it on hidden field instead and then update the selector on ajax success
)
);
On controller User
public function actionfavoritePage(){
if( Yii::app()->request->isAjaxRequest(){ // this check is not necessary if you write this function just for ajax call only
$playerId- = $_GET['playerId']; // get query string
$pageId- = $_GET['pageId']; // get query string
$bool = $_POST['bool']; // get status true OR false
//do your stuff to save status here
...
//then return result as json
echo json_encode(array('label' => '[your new button label]', 'toggle'=>$bool?'false':'true'));
exit();
})
}
You'll want to use CHtml::ajaxButton(): http://www.yiiframework.com/doc/api/1.1/CHtml#ajaxButton-detail
Here's a tutorial on how to use it: http://www.yiiframework.com/wiki/49/update-content-in-ajax-with-renderpartial/
If you want the title of your button to change, place a condition in a view, and make sure your button is returned in the ajax result.
Type a random email address into my form and notice the ajax updates at the top - http://goo.gl/DwvdY
How do I put those updates directly in the input box where you typed your email address? This is driving me crazy
There is an empty div named #response that first gets filled with this JS text update:
$('response').innerHTML = 'Adding email address...';
Then that same div gets the status returned to it and a newer update is echoed with PHP.
<span id="response">
<? require_once('inc/store.php'); if($_GET['submit']){ echo storeAddress(); } ?>
</span>
it should be:
$('#response').html('Adding email address...');
To store it the the textbox directly do this:
$('#email').val('Adding email address...');
This should do it:
$('#signup').submit(function() {
// update user interface
//store the value first to another variable before setting a new one
var email = $("#email").val();
$('#email').val('Adding email address...');
// Prepare query string and send AJAX request
$.ajax({
url: 'inc/store-address.php',
data: 'ajax=true&email=' + escape(email),
success: function(msg) {
$('#email').val(msg);
}
});
return false;
});