Ajax in Cakephp 2.x - php

I have a problem, i need to use, ajax in a form, in my page i have to change the color of a label after i search if a data is in a data base, if the data exist i must change the color of the label to red, if not i have to changed to green, i know how to use this in pure php, but i don´t know how to do that in cakephp, if i am not wrong in pure php this is the forme to do it:
View
<form action="prueba.php" method="post">
<input type="text" id="txt_prueba" class="validador" />
<submit value="enviar"/>
</form>
View in Cake
<?php
echo $this->Form->create('Prueba', array('url' => 'prueba.php', 'type' => 'post'));
echo $this->Form->input('textoPrueba', array('label' => false,
'class' => 'validador'));
echo $this->Form->end(); ?>
Script
$(".validador").on('keyup keypress blur change', function (tecla) {
$.ajax({
method: "POST",
url: "algun.php",
data: {
name: $("#txt_prueba").val();
}
})
.done(function( msg ) {
if (msg=="Yes"){
$("#txt_prueba").css('background-color', 'red');
} else{
$("#txt_prueba").css('background-color', 'green');
}
});
});
Controller
require('conexion.php');
$consulta = $_POST['name'];
if (isset($consulta)) {
$consulta = mysqli_query($conexion, "SELECT * FROM tabla1
WHERE nombre LIKE '$consulta'");
$filas = mysqli_num_rows($consulta);
if ($filas === 0) {
echo 'Not';
}else {
echo 'Yes';
}
};

Have you read something about CakePHP? You should read some basic tutorial
Download and install CakePHP (https://book.cakephp.org/3.0/en/installation.html)
Build Your first controller with action and view (https://book.cakephp.org/3.0/en/tutorials-and-examples/cms/articles-controller.html)
Add Your JavaScript AJAX code in default.ctp layout file
Build Your first form (https://book.cakephp.org/3.0/en/tutorials-and-examples/cms/articles-controller.html#create-add-template)
Run, if You have some problems, try find solution on stackoverflow.com...

Related

passing javascript variable to php in cakephp 2 view

I am trying to pass a javascript variable into a php code in the view file of the cakephp 2.
for (id in response) {
var book = response[id];
if (typeof(book.thumbnail_url) != "undefined") {
var x= book.thumbnail_url;
<?php
$file11 = WWW_ROOT . 'img' . DS . 'book_images';
define('DIRECTORY', $file11);
$content = file_get_contents($abc);
file_put_contents(DIRECTORY . '/'.$isbn.'.jpg', $content);
?>
}
}
i am trying to pass the value of x in the file_get_contents function in place of $abc so that it could save the image coming from the javascript's URL accordingly.
EDIT::
for (id in response) {
var book = response[id];
if (typeof(book.thumbnail_url) != "undefined") {
var x= book.thumbnail_url;
$.ajax({
type: "POST",
url: '/BookSearchs/test',
data: {'yourX':x}
}).done(function(result) {
alert("yes");
}).fail(function() {
alert("no");
});
}
}
This is what i wrote after implementing the answers i got . But Everytime it pops up "no". Here BookSearchs is my controller and test is my function inside it.
EDIT 2:
function handleResponse(response) {
var target = '';
for (id in response) {
var book = response[id];
if (typeof(book.thumbnail_url) != "undefined") {
var x = book.thumbnail_url;
$.ajax({
type: 'POST',
url: "BookSearchs/test",
data: {
myVal: x
},
success: function() {
alert('AjaX Success')
},
error: function() {
alert('AjaX Failed')
}
})
.done(function() {
alert('AjaX Done!');
});
}
}
return true;
}
Currently this is what i've have done so far , the form method did not work out . It was redirecting me to another page . Anyways this is my current code . And 'test' is the my function inside the controller where i want to access the myVal value using POST . Also i have this question do i need to create a physical file for test in order to make the ajax function work, because if i delete the test.ctp file then the ajax starts giving the fail message . So for now i have created a physical test.file in the BookSearchs folder in the view , although it's empty in order to make the ajax function work . I am having a doubt whether my Url in Ajax is wrong or i am not accessing the values properly in the controller.
I don't think that this is a proper way to do that in theory. But, sometime we might need this.
Before we proceed to this way, you might need to think other technologies such as NodeJs (e.g fs.readFileSync)
Basically, you can't directly do that. Because, JavaScript run on client side and PHP is run on sever side.
Anyway, there might be a few tweak to do that. But, this approach might be slow and it depends on how many loop you making.
for (id in response) {
var book = response[id];
if (typeof(book.thumbnail_url) != "undefined") {
var x= book.thumbnail_url;
$.ajax({
type: "POST",
url: '/yourcontroller/route',
data: {'yourX':x}
}).done(function(result) {
//if success, execute other code
}).fail(function() {
//DO other if fail
});
}
}
Then, read this value in your controller
$xValue = $_POST['yourX'];
$file11 = WWW_ROOT . 'img' . DS . 'book_images';
define('DIRECTORY', $file11);
$content = file_get_contents($xValue);
file_put_contents(DIRECTORY . '/'.$isbn.'.jpg', $content);
//do some checking success or fail
//I will assume success
$status = 'success';
echo json_encode(['status'=>$status]);
Usally I use a Trick to pass JS variable to a CakePhp Controller(php variable). Actionly I create a form that contain a hidden input, I'll also put the link of the page that will receive the php variable.
.ctp
<?=
$this->Html->link('<i class="fa fa-file-pdf-o"></i>' .__('Export'),
'javascript:myFunction();',
array('escape' => false, 'class' => 'btn btn-app dispatch', 'id' => 'dispatch_packages',
'style'=>'margin-right:0px;background: #f39c12;color:white;',
'disabled' => 'false'));
?>
<form id="sampleForm" name="sampleForm" style="display: none" method="post" action="<?= $this->Url->build([
'controller' => 'YourController',
'action' => 'youraction']) ?>">
<input type="hidden" name="variable" id="variable" value="">
</form>
JS
var jsVar=0;
function myFunction()
{
document.sampleForm.variable.value = jsVar;
document.forms["sampleForm"].submit();
}
I used it with the CakePhp 3.x framework & it's working very fine. You have just to write the url with the CakePhp 2.x Syntax.
Don't hesitate to comment my answer if you'll have any difficulties to apply it.
Good Luck !

php - codeigniter ajax form validation

Hi I’m quite new to jquery -ajax and I’d like some help please to join it with CI.
I have followed this tutorial on Submitting a Form with AJAX and I’d like to add this functionality to my CodeIgniter site. What I’d like to do is when the user submits the form, if there are any validation errors to show the individually on each input field (as in native ci process), or if this is not possible via validation_errors() function. If no errors occured to display a success message above the form.
Here's my code so far:
my view
// If validation succeeds then show a message like this, else show errors individually or in validation_errors() in a list
<div class="alert alert-success">Success!</div>
<?php echo validation_errors(); //show all errors that ajax returns here if not individualy ?>
<?php echo form_open('admin/product/add, array('class' => 'ajax-form')); ?>
<p>
<label for="product_name">Product *</label>
<input type="text" name="product_name" value="<?php echo set_value('product_name', $prod->product_name); ?>" />
<?php echo form_error('product_name'); ?>
</p>
<p>
<label for="brand">Brand</label>
<input type="text" name="brand" value="<?php echo set_value('brand', $prod->brand); ?>" />
<?php echo form_error('brand'); ?>
</p>
...
my controller
public function add($id){
// set validation rules in CI native
$rules = $this->product_model->rules;
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() === true) {
// get post data and store them in db
$data = $this->input_posts(array('product_name', 'brand', 'category_id', 'description'));
$this->product_model->save($data, $id);
// no errors - data stored - inform the user with display success-div
} else {
// validation failed - inform the user by showing the errors
}
//load the view
$this->load->view('admin/products/add', $data);
}
and here’s the js script
$(document).ready(function () {
$('form.ajax-form').on('submit', function() {
var obj = $(this), // (*) references the current object/form each time
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
obj.find('[name]').each(function(index, value) {
// console.log(value);
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.ajax({
// see the (*)
url: url,
type: method,
data: data,
success: function(response) {
console.log(response); // how to output success or the errors instead??
}
});
return false; //disable refresh
});
});
How should I pass my validation results (either success or the post errors) throught the ajax request and display them on my view??
From some little research I did I've found that you can use a single controller, that holds both the native proccess and the ajax request (instead of using 2 controllers), but my main difficulty is, I don't understand how the results of the validation will pass through the js script and display them on my view?? Please note that I don't want to display anything on an alert box, instead show the results on a div or the errors individualy(if possible).
EDIT I did some changes to my application, here's the code so far:
the controller
public function manage($id = NULL){
$this->load->library('form_validation');
$data['categ'] = $this->category_model->with_parents();
//fetch a single product or create(initialize inputs empty) a new one
if (isset($id) === true) {
$data['prod'] = $this->product_model->get($id);
$data['attr'] = $this->attribute_model->get_by('product_id', $id, null, true);
} else {
$data['prod'] = $this->product_model->make_new();
$data['attr'] = $this->attribute_model_model->make_new();
}
if (isset($_POST['general_settings'])) {
if ($this->form_validation->run('product_rules') === true) {
// get post inputs and store them in database
$data = $this->product_model->input_posts(array('product_name', 'brand', 'category_id', 'general_description'));
$this->product_model->save($data, $id);
$status = true;
} else {
// validation failed
$status = validation_errors();
}
if ( $this->input->is_ajax_request() ) {
echo json_encode($status);
exit;
}
redirect('admin/product');
}
//if (isset($_POST['attributes_settings'])) { the same thing here }
// load the view
$this->load->view('admin/products/manage', $data);
}
and the js
success: function(response) {
//console.log(response);
if (data.status === true) {
$('#ajaxResults').addClass('alert alert-success').html(response);
} else {
$('#ajaxResults').addClass('alert alert-error').html(response);
};
}
But I'm having some issues
Although I get the error messages from validation_errors() as an alert-error when there are no errors I get the true in an alert-error too, insted of alert-success.
2.how should I return the success message too? eg. a message saying "Saves were done!".
Althought in a non-ajax-request the data are stored in the database, in case fo ajax the don't store. Any ideas What may be wrong???
HTML:
<div id="ajaxResults"></div>
Javascript ajax:
success: function(response) {
$('#ajaxResults').text(response);
}
this script you've wrote is only if the validation succeeds, right?
Wrong. The code in "success" gets executed any time you get a response back from the server (assuming the HTTP header is 200). Does your javascript knows if the server has any error for you? No.
You need your JavaScript to recognize if the validation failed or succeeded. You have many ways to do that. One of these could be sending the message to display followed by a 0 or 1.
So your PHP will looks like:
return "0 " . $errorMessage;
and
return "1 " . $successMessage;
and your javascript should then recognize, with if statement and substring, if the message starts with 0 or with 1.
Use this way i hope this will work for you
<script type='text/javascript'>
var base_url = '<?=base_url()?>';
function ajax_call()
{
var ids = $("#all_users").val();
$.ajax({
type:"POST",
url: base_url+"expense/home/get_expense",
data: "userid=" + ids,
success: function(result){
$("#your_div_id").html(result);
}
});
}
</script>

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 to implement jquery and CodeIgniter validation library together?

I want to create a registration form where I want to use jquery and also the CI validation library.
How can I do this? Upon submitting the form, I want the control to go to the validation library using jquery and return the response. Then, if all is well, I want the "form is submitted" message to be displayed on that page itself.
Edit:
here are my codes.
VIEW
<?php $this->load->view('template/header'); ?>
<div id="add_form">
<h2>Add New Category</h2>
<?php echo form_open('abc/abc_category_controller/add_new_category'); ?>
<?php
$category_data = array(
'name' => 'category_name',
'id' => 'category_name',
'value' => set_value('category_name'),
'maxlength' => '15'
);
$unit_data = array(
'name' => 'unit',
'id' => 'unit',
'value' => set_value('unit'),
'maxlength' => '10'
);
?>
<p><label for="name">Name: </label><?php echo form_input($category_data); ?></p>
<p><label for="unit">Unit: </label><?php echo form_input($unit_data); ?></p>
<p><?php echo form_submit('submit', 'Submit','id="submit"'); ?></p>
<?php echo form_close(); ?>
<?php echo validation_errors('<p class="error">'); ?>
</div><!--end add new category-form-->
<div id="success_msg">
</div>
<?php $this->load->view('template/footer') ?>
Controller- add_new_category
<?php
class Stocks_category_controller extends CI_Controller{
function add_new_category()
{
//$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Add a new category';
$this->form_validation->set_rules('category_name', 'Category Name', 'required');
$this->form_validation->set_rules('unit', 'Unit', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('abc/add_new_category');
}
else
{
$category_name = $this->input->post('category_name');
$unit = $this->input->post('unit');
$this->load->model('abc/abc_category_model');
$insert_id=$this->abc_category_model->add_new_category($category_name
,$unit);
if($insert_id!=NULL)
{
$this->load->view('template/success',$data);
}
else{
$data['error_msg']='Error Occurred';
$this->load->view('template/template',$data);
}
}
}
function success(){
$data['success_msg']='New Category Successfully Created';
$this->load->view('template/success',$data);
}
}
And finally the model.
function add_new_category($category_name,$unit){
$data = array(
'abc_category_name' => $category_name ,
'unit' => $unit
);
$this->db->insert('abc_category', $data);
$insert_id=$this->db->insert_id();
return $insert_id;
}
}
What I want is that when I submit the form, jquery validation should take place. And if, all is well then the SUccessful message be displayed using ajax only and page should not reload.
Also, please tell me is it possible to use jquery validation and CI validation library both and maintaining ajax at the same time?
To implement both client side and server side validations you need to use the jquery validation plugin.
So, you need to include:
jQuery javascript library
jQuery validation plugin
Load the javascript with
<script type="text/javascript" src="<?php echo base_url();?>js/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.validate.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.validate-rules.js"></script>
then setup your form:
$attr = array('id' => 'demo_form');
echo form_open('demo/validation_example', $attributes);
and validate your form like:
$(document).ready(function() {
$("#demo_form").validate({
rules: {
name: {
required: true
},
...
},
messages: {
name: {
required: "Name required",
},
},
errorElement: "span",
errorPlacement: function(error, element) {
error.appendTo(element.parent());
}
});
});
And use the server side validation too, because it is not a good practice to use only client side validation.
For more help, you can find a good tutorial about
how to implement the jquery validation with codeigniter
and working demo
Where you can check jquery validation, and by disabling the javascript of your browser, you can check codeigniter server side validations done with php.
I think you have to use jquery ajax for this.
First you need to post your data. Set your submit button to fire jquery ajax like this.
$.ajax({
type: "GET",
url: "/controller/validate", //your controller action handler
dataType: "json",
data: {name:value, name: value}, //set your post data here
cache:false,
success: function(data){
//handle the callback response
if(data.success)
alert("Success");
else
alert(data.errors);
}
});
Next in your controller action, validate your post data using codeigniter validator.
If it fails the validation, you need to send the errors back to your js callback function using json_encode in your view. Set the data error like this,
In your view (the view you will set for /controller/validate), do something like this
$data['errors'] = validation_errors();
echo json_encode($data);
You will have the errors back to you without refreshing the page.
When the validation is success, just set a $data['success'] and use echo json_encode using if statement so that only success data will be retrieved. I have set the ajax script callback.

Codeigniter dynamic form dropdown, not returning value but the ID

I have this code for my drop down form that worked fine
<?php echo form_label('Model: ', 'model'); ?>
<?php echo form_dropdown('model', $model_dropdown, '', set_value('model', '', 'id="model"')); ?>
<?php echo form_label('Make: ', 'make'); ?>
<?php echo form_dropdown('make', $make_dropdown, '', set_value('make', '', 'id="make"')); ?>
but then I wanted to enhance it with some jquery for a dynamic drop down so I changed it to this
<label for="make">Make: </label>
<?php echo form_dropdown('id', $make_dropdown, '', 'id="make"'); ?><br /></td>
<?php $models['#'] = 'Please Select'; ?>
<label for="model">Model: </label>
<?php echo form_dropdown('model_id', $models, '', 'id="models"'); ?><br /></td>
with this for js
$(document).ready(function(){
$('#make').change(function(){
$("#models > option").remove();
var id = $('#make').val();
$.ajax({
type: "POST",
url: "site/get_models/"+id,
datatype : "json",
success: function(models) {
$.each(models,function(id,model)
{
var opt = $('<option />');
opt.val(id);
opt.text(model);
$('#models').append(opt);
});
}
});
});
});
but now the value is not being submitted but the ID, which makes sense when looking at the code. What needs to be updated to fix this?
Thanks
Edit: The ID of the Make and Model drop down is what is being inserted, I want the value instead, like how it use to work before I added the jquery.
For instance, the make drop down would have HP or Dell and the model would have models, when submitted, those values would be inserted but instead I'm just getting the IDs...
try changing:
opt.val(id);
to
opt.val(model);
update:
ok, so this works for one data structure type. i would suggest defining the return value type where you could do something like this:
-->"successData" from the ajax request = {"type":"model","id":"12345","model":"a cool model"}
and your success handle could do something like:
success: function(successData){
if(successData.type === "model"){
//do your loop to create the models markup
else{
//we have "make" data, handle that here..
}
}

Categories