Using ajax in zend framework - php

My controller is
public function init()
{
/* Initialize action controller here */
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('get-ajax-content', 'html')
->initContext();
}
public function indexAction()
{
// action body
$form = new Zend_Form_Element_Select('menu');
$parent_array=range('1','9');
$form->addMultiOptions(array($parent_array));
$this->view->form = $form;
}
for this form element, i am calling the ajax function,
<script type="text/javascript">
$(document).ready(function(){
$("#menu").change(function(){
$.ajax({
type: "POST",
url: "get-data",
data: "val="+$(this).val(),
success: function(result){
$("#div_sortorder").html(result);
},
error: function(){
//console.log('error');
},
complete: function(){
//console.log('complete');
}
});
});
</script>
and the get-data action is following
public function getDataAction()
{
// action body
$this->view->message = 'This is an ajax message!';
$params = array( 'host' =>'localhost',
'username' =>'root',
'password' =>'',
'dbname' =>'cms'
);
$DB = new Zend_Db_Adapter_Pdo_Mysql($params);
$section_id=$this->getRequest()->getPost('val');
$menu_order='SELECT * FROM `cms_content_mst` WHERE section_id='.$section_id;
$menu_order=$DB->fetchAll($menu_order);
$newContent='<select id="sortorder" name="sortorder">';
if(!empty($section_id) || $section_id != 0){
if (empty($menu_order)) {
$newContent.='<option value="1" selected="selected">1</option>';
}
else
{
for ($i=1; $i <= count($menu_order) ; $i++) {
$newContent.='<option value="'.$i.'"';
if($i==count($menu_order))
{ $newContent.=' selected'; }
$newContent.='>'.$i.'</option>';
}
}
}
$newContent.='</select>';
$this->view->new = $newContent;
}
i have fully worked jquery . i have .get function but on calling .ajax its is not working
i am newbee to zend plz, help

Please! Check in console if you are able to load page.
$.ajax({
type: "POST",
url: "get-data",
data: "val="+$(this).val(),
success: function(result){
$("#div_sortorder").html(result);
}
I think you have given wrong url.

Related

Codegniter - Internal error when acessing database

I'm using CodeIgniter to access the database, but everytime I run the code it gets an internal error. This is my jQuery code:
function showCadeiras() {
$.ajax({
type: "POST",
url: base_url + "api/teacher/getCadeiras",
data: {id: localStorage.user_id},
success: function(data) {
for(var i = 0; i < data.cadeiras_id.length; i++) {
var cadeira_id = data.cadeiras_id[i].cadeira_id;
$.ajax({
type: "POST",
url: base_url + "api/teacher/getCadeiraInfo",
data: {id: cadeira_id},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log("error");
}
})
}
},
error: function(data) {
console.log(data);
}
});
}
Here is the code inside the Controller:
public function getCadeiras() {
$user_id = $this->post('id');
$this->load->model('UserModel');
$data["cadeiras_id"] = $this->UserModel->getCadeiras($user_id);
$this->response($data, parent::HTTP_OK);
}
public function getCadeiraInfo(){
$cadeira_id = $this->post('cadeira_id');
$this->load->model('UserModel');
$data["info"] = $this->UserModel->getCadeiraInfo($cadeira_id);
$this->response($data, parent::HTTP_OK)
}
Lastly, the Model code:
public function getCadeiras($id) {
$this->db->select("cadeira_id");
$this->db->where(array('user_id =' => $id));
$query = $this->db->get('professor_cadeira');
return $query->result_array();
}
public function getCadeiraInfo($id) {
$query = $this->db->get_where('cadeira', array('id =' => $id));
return $query->result_array();
}
Everytime I comment the second function (getCadeiraInfo) the code works without a problem, however it doesn't work with the second function. They are written in a similar way, I don't understand the error.

Making one ajax call when another executes successfully

I'm trying to make another ajax call when one is executed successfully to pass the post variable to another controller action. However, it is returning null when I check the console log message. I'm not sure why.
Here is my code:
jQuery:
$('#modify-store-name').on('change', function() {
$.ajax({
type: "POST",
url: "/user/get-one-store",
dataType: "json",
data: {
store_name: $(this).val()
}
}).done(function (msg) {
$.each(msg, function (i) {
$('#modify-store-label').attr('style', '');
$('#modify-store-desc').attr('style', '');
$('#modify-store-category-label').attr('style', '');
$('#modify-store-category').attr('style', '');
$('.upload-btn-wrapper').attr('style', '');
$('#modify-store-desc').val(msg[i].store_description);
$('#modify-store-category').html($("<option />").val(msg[i].store_category).text(msg[i].store_category));
$('#msubmit').attr('disabled', false);
});
$.ajax({
type: "POST",
url: "/user/modify-store",
dataType: "json",
data: {
store_name2: $('#modify-store-name').val() // why is this sending a null value
}
}).done(function(msg) {
console.log(msg);
}).fail(function(msg) {
console.log(msg);
});
}).fail(function (msg) {
$("#msg").html(msg.failure);
});
});
and my php code:
public function getonestoreAction()
{
$layout = $this->layout();
$layout->setTerminal(true);
$view_model = new ViewModel();
$view_model->setTerminal(true);
try {
$store_name = $this->params()->fromPost('store_name');
echo json_encode($this->getUserService()->getAStore($store_name));
} catch (\Exception $e) {
echo json_encode(array('failure' => $e->getMessage()));
}
return $view_model;
}
public function modifystoreAction()
{
$layout = $this->layout();
$layout->setTerminal(true);
$view_model = new ViewModel();
$view_model->setTerminal(true);
if ($this->getRequest()->isPost()) {
try {
$store_name = $this->params()->fromPost('store-name2');
echo json_encode($store_name); // returning null
$mstore_name = $this->params()->fromPost('modify-store-name');
$mstore_description = $this->params()->fromPost('modify-store-description');
$mstore_category = $this->params()->fromPost('modify-store-category');
$mstore_image = $this->params()->fromFiles('modify-store-image');
if (count($mstore_image) > 0) {
if ($this->getUserService()->modifyStore($store_name, array('store_name' => $mstore_name, 'store_description' => $mstore_description, 'store_category' => $mstore_category, 'store_image' => $mstore_image, 'tmp_name' => $mstore_image['tmp_name']))) {
echo json_encode(array('success' => 'Store was modified successfully.'));
}
}
} catch (\Exception $e) {
echo json_encode(array('failure' => $e->getMessage()));
}
}
return $view_model;
}
I read that you can make two ajax calls like this but I'm not sure why one is not passing the store name via post.
Any help would be appreciated
Thanks!

jquery onSubmit() problems after returning data from php

I am trying to validate my forms by using jQuery and php .. What I am trying to achieve is pass my form inputs to process.php in the background, check if inputs pass my validation code, then return true or false back to my jQuery checkForm() function .. so far the below code is now working ..
function checkForm() {
jQuery.ajax({
url: "process.php",
data: {
reguser: $("#reguser").val(),
regpass: $("#regpass").val(),
regpass2: $("#regpass2").val(),
regemail: $("#regemail").val()
},
type: "POST",
success: function(data) {}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form action="register.php" method="post" onSubmit="return checkForm()">
send all input's in php to validate all the data.
function checkForm() {
$.ajax({
url : "process.php",
type: "POST",
data: $('#yourForm').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status)
{
alert("Success");
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
alert(data.inputerror[i] + "|" + data.error_string[i]);
}
}
}
});
};
validating the data you've sent through Ajax.
public function process()
{
$this->_validate_all_data();
echo json_encode(array("status" => true));
}
private function _validate_all_data()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = true;
if(empty($POST['reguser']))
{
$data['inputerror'][] = 'reguser'; // input name
$data['error_string'][] = 'Reguser is required'; // message for validation
$data['status'] = false;
}
if($data['status'] === false)
{
echo json_encode($data);
exit();
}
}

Bootstrap modal form replace with JSON

I've got a problem with replacing registration form when some errors occur. My form is rendered in bootstrap modal and validated using Zend controller action. When I submit not valid form it should be replaced with the same form but with errors displayed. Below is my code.
Zend action:
public function registerAction(){
$result = array("success" => true);
$view = new Zend_View();
$form = new Application_Form_DesktopUser_Register();
$view->form = $form;
$result["form"] = $form;
if($this->_request->isPost()){
if($form->isValid($this->_request->getPost())){
//Some code
}
else{
$result["success"] = false;
}
}
exit;
$this->_helper->json($result);
}
My JavaScript code:
<script type="text/javascript">
$(document).ready(function(){
$('body').on('submit', '#registerForm', function(event){
event.preventDefault();
$('.alert').remove();
$.ajax({
type: "POST",
url: $('#registerForm').attr('action'),
data: JSON.stringify($('#registerForm').serializeArray()),
dataType: 'json',
contentType: 'application/json',
success: function(data){
if(data["success"] == false){
$('#registerForm').html('error').show();
}
else{
}
},
error: function(data){
$('.formdiv').html($(data.form).html());
}
});
return false;
});
});

How to do a dynamic dropdown using Ajax in Codeigniter

I know this may be the [insertLongNumber]th time someone's ask this question, I did my research but I can't find another answer that fits my problem. So here it is.
I'm working on a dynamic dropdown with php and ajax, in codeigniter. I'm new to CI and I have a basic knowledge of Ajax.
What I have noticed so far is that in the console, it is not recognizing the value coming from the first dropdown, so i get departamento_id : undefined
This makes me thing problem comes from ajax script (i got it of the web)
My view, with the ajax code included
<?php
$this->load->helper('html');
?>
<html>
<head>
<title>Buscador</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#dpto-dropdown select').change(function () {
var selDpto = $(this).attr('value');
console.log(selDpto);
$.ajax({
url: "test/ajax_call",
async: false,
type: "POST",
data: "departamento_id="+selDpto,
dataType: "html",
success: function(data) {
$('#ciudad').html(data);
}
})
});
});
</script>
</head>
<?php echo form_open('test/buscar');?>
<?php
<div id='dpto-dropdown'><?php print form_dropdown('departamentos', $departamento) ?></div>
<div id="ciudad"><select><option value=''>-</option></select></div>
//rest of code...
This is my Controller code:
class Test extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('buscador_model');
}
function index()
{
$departamentos = $this->buscador_model->traerInfoDptos();
$precios = $this->buscador_model->traerPrecioHoteles();
foreach($departamentos as $departamento){
$dpto_final[$departamento->id] = $departamento->nom_departamento;
}
$info = array(
'departamento' => $dpto_final,
'precios' => $precios,
);
$this->load->view('buscador_view', $info);
}
function ajax_call()
{
//check to see people wont go directly
if (isset($_POST) && isset($_POST['departamento_id']))
{
$dpto = $_POST['departamento_id'];
$ciudad = $this->buscador_model->traerCiudadPorDpto($dpto);
foreach ($ciudad as $c)
{
$ciudadfinal[$c->cod_ciudad] = $c->nom_ciudad;
}
//dropdown
echo form_dropdown('Ciudades', $ciudadfinal);
}
else
{
redirect('index');
}
}
}
this is my model:
Class Buscador_model extends CI_Model
{
function traerInfoDptos()
{
$this->db->select('id, nom_departamento');
$this->db->from('departamento');
$query = $this->db->get();
if ($query->num_rows > 0)
{
return $query->result();
}
}
function traerCiudadPorDpto($dpto)
{
$query = $this->db->query("SELECT nom_ciudad, cod_ciudad FROM ciudad WHERE departamento_id = '{$dpto}'");
if ($query->num_rows > 0)
{
return $query->result();
}
}
}// end buscador model class
See this page: http://www.onerutter.com/open-source/jquery/jquery-tips-how-to-get-value-of-selected-option-in-select-box.html
You need to use .val() instead of .attr('value')
<script type="text/javascript">
$(document).ready(function () {
$('#dpto-dropdown select').change(function () {
var selDpto = $(this).val(); // <-- change this line
console.log(selDpto);
$.ajax({
url: "test/ajax_call",
async: false,
type: "POST",
data: "departamento_id="+selDpto,
dataType: "html",
success: function(data) {
$('#ciudad').html(data);
}
})
});
});
</script>

Categories