Retrieve value from ajax call - php

I have seen many topics like mine but I can't resolve my problem who seems so simple.
I have this function in JS :
function displayFullDesignation(id, select) {
var fullDesignation = $('option:selected', select).data('idacc');
var myId = parseInt(fullDesignation);
$.ajax({
url: '<?php echo $this->url(array('controller' => 'catalog', 'action' => 'fullname'));?>',
type: 'POST',
datatype: 'json',
data: {'id': myId},
success: function(data) {
if(data.success){
console.log(data.success);
}
}
});
return fullDesignation;
}
And in my controller :
/**
* AJAX Action
*/
public function fullnameAction($params) {
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('fullname', 'json')->initContext();
$response = array();
$params = $this->getAllParams();
$listModels = Application_Model_Catalog_Accessory_List::getDesignationComplet($params['id']);
$response['success'] = true;
$response['aaData'] = $listModels;
$this->getHelper('json')->sendJson($response);
}
I don't know why I can't get anything from this ajax call. If I try to do a var_dump inside my function, it does nothing at all so I think that my call isn't good, but I have other calls who work like this.
What am I doing wrong please ?
And if I do a console.log of 'data', it gives me HTML. data.success gives me undefined.
Thanks !!

Related

Ajax on Success redirect URL from controller

Current Page is Add.phtml..when click saves button, it should be redirected to index.phtml..the URL for index page already inside a controller.
but I can't make it..can anyone point me which part is wrong?
JS inside add.phtml
function addMembAndAppDetail(){
var m_register = 0;
if($('input[name="register"]').is(':checked'))
{
m_register = 1;
}
var m_active = 0;
if($('input[name="status"]').is(':checked'))
{
m_active = 1;
}
$.ajax({
url: '/membership/membership-setup/ajax-add-multiple/',
type: 'POST',
async : false,
data: {
'm_owner' : $('#m_owner').val(),
},
dataType: 'json',
success: function(response){
window.location.href = response.url;
}
});
}
Inside Controller
public function ajaxAddMultipleAction(){
$auth = Zend_Auth::getInstance();
$data = array(
'm_owner' => $this->_getParam('m_owner', null)
);
$membershipDb = new Membership_Model_DbTable_TblMembership();
$membershipDb->addData($data);
$this->_helper->flashMessenger->addMessage(array('success' => "Record saved"));
$url = $this->_redirect($this->baseUrl . '/membership/membership-setup/index');
echo json_encode(array('msg'=>"Success.", 'url'=>$url, 'status'=>true));
}
You just returning the url but you never used it. if your url is valid then you can change your success method to redirect the client
success: function(response){
window.location.href = response.url
}
Edit
I tested out your ajax call and it looks like that if you remove dataType: 'json' it works perfectly. I don't know why it cause the issue but after removing it it should work.
anyways dataType default value is Intelligent Guess so it will guess the data type automatically for you

Pass a View Data From Controller to Ajax View File - Laravel 5

From View Page I am calling Ajax to my Controller, from my Controller I want to create a html data so I am passing my array to View file to create a HTML data.
I don't know why when I try to do console nothing gets return, can anyone tell me where I am going wrong
CallingAjaxFromViewFile
function AjaxgetCheckInChekOutUser(status){
var url = "{{ url('admin/events/ajaxData') }}";
var token = $('#token').val();
if(status){
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
url: url,
type: 'POST',
data: {'status': status,'_token':token},
success: function (data) {
alert(data);
data = JSON.parse(data);
console.log(data.html);
$('#gymimages').html(data.html);
}
});
}
}
myControllerFile
public function AjaxCurrentPastFutureData($data, $status){
$title = "HDTuto.com";
$html = view('admin.events.ajaxdataview')->with(compact('title'))->render();
//pr($html);
$response = response()->json(['success' => true, 'html' => $html]);
return $response;
}
NowmyViewFile From Where I append HTML Data
<h1><i>{{ $title }} </i></h1>
Can anyone tell me where I am going wrong?
** Use this**
function AjaxgetCheckInChekOutUser(status){
var url = "{{ url('admin/events/ajaxData') }}";
var token = $('#token').val();
if(status){
$.ajax({
url: url,
type: 'POST',
data: {'status': status,'_token':token},
success: function (data) {
$('#gymimages').html(data.html);
}
});
Also update your Controller function
public function AjaxCurrentPastFutureData(Request $request){
$title = "HDTuto.com";
$html = view('my')->with(compact('title'))->render();
//pr($html);
$response = response()->json(['success' => true, 'html' => $html]);
return $response;
}

Codeigniter Ajax request URL issue

I am using codeigniter version 3+, Jquery version 3+. I am trying to get data through ajax request but it does not return anything. And when I inspect and see its request url is wrong but did not get how i modify that.
Ajax request
var site_url = '<?=base_url()?>';
var id = $(this).find("option:selected").attr('value');
$.ajax({
type : 'POST',
dataType : 'json',
url: '<?=base_url()?>'+'index.php/talika_12/get_data_by_id_ajax',
data: {user_id:id},
success: function(data) {
alert(data);
$('#inst_name').text(data.talika_12_user_name);
$('#inst_account_no').text(data.talika_12_user_account_no);
}
});
Controller
public function get_data_by_id_ajax(){
$user_id = $_POST['user_id'];
$data = $this->talika_12_m->get_data_by_id($user_id);
$ajax_response_data = array(
'talika_12_user_name' => $data[0]->talika_12_user_name ,
'talika_12_user_account_no' => $data[0]->talika_12_user_account_no ,
);
echo json_encode($ajax_response_data);
}
Model
public function get_data_by_id($id){
$where_clause = array('talika_12_user_id' => $id);
$this->db->limit(1);
$val = $this->db->get_where('table_12', $where_clause)->result();
return $val;
}
Get request url is ( Request URL:http://localhost/test/codeIgniter/talika_12/%3C?=base_url()?%3Eindex.php/talika_12/get_data_by_id_ajax
)
Please try this code
var id = $(this).find("option:selected").attr('value');
$.ajax({
type : 'POST',
dataType : 'json',
url: "<?=base_url()?>index.php/talika_12/get_data_by_id_ajax'",
data: {user_id:id},
success: function(data) {
alert(data);
$('#inst_name').text(data.talika_12_user_name);
$('#inst_account_no').text(data.talika_12_user_account_no);
}
});
changed url portion url: "<?=base_url()?>index.php/talika_12/get_data_by_id_ajax'", otherwise you can use url:<?= site_url('talika_12/get_data_by_id_ajax')

cakephp, jquery, .ajax()

I've been stuck with the retrieving of my sent variable trough an ajax POST function. Could you help me out?
My Jquery code:
$.ajaxSetup ({
cache: false
});
var selected = new Array();
$(document).ready(function() {
$('.value').click(function () {
if($(this).hasClass('strong'))
{
selected.splice(selected.indexOf(this.innerHTML), 1);
submitData(selected);
$(this).removeClass('strong');
}
else
{
selected.push(this.innerHTML);
submitData(selected);
$(this).addClass('strong')
}
});
});
function submitData(arDat) {
var arrayData = {"param1" : JSON.stringify(arDat)};
$.ajax({
type: 'POST',
url: 'http://localhost.local/coconut/trunk/challenges/values',
data: arrayData,
dataType: 'json',
success: function(data){
console.log(arrayData);
},
error: function(message){
alert(message);
}
});
}
My CakePHP Controller function:
function values() {
if ($this->RequestHandler->isAjax()) {
$this->autoRender = false;
Configure::write('debug', 0);
$params = json_decode($_POST['param1']);
//$result = json_encode($params);
$this->set('submitValue', $params);
} else {
$this->redirect(array('controller' => 'challenges', 'action' => 'index'));
}
}
And in a view.ctp file:
<?php debug($submitValue); ?>
But I get the following error:
Notice (8): Undefined variable: submitValue
In firebug I see this:
Parametersapplication/x-www-form-urlencoded
param1 ["Business","Life","Health"]
Source
param1=%5B%22Business%22%2C%22Life%22%2C%22Health%22%5D
Does anyone know what I'm doing wrong?
Thanks!
Edit:
A bit more clarification about what I want.. I want to use $this->set('submitValue', $params); (so $submitValue) elsewhere in another view.
The CakePHP function 'isAjax()' checks to see if a request is a Prototype Ajax request.
You aren't using Prototype, you're using jQuery - so presumably it's always returning false, and so submitValue is never set.

Zend and Jquery (Ajax Post)

I'm using zend framework, i would like to get POST data using Jquery ajax post on a to save without refreshing the page.
//submit.js
$(function() {
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
url: 'http://localhost/myproject/public/module/save',
async: false,
data: 'id=' + id + '&details=' + details,
success: function(responseText) {
//alert(responseText)
console.log(responseText);
}
});
});
});
On my controller, I just don't know how to retrieve the POST data from ajax.
public function saveAction()
{
$data = $this->_request->getPost();
echo $id = $data['id'];
echo $details = $data['details'];
//this wont work;
}
Thanks in advance.
Set $.ajax's dataType option to 'json', and modify the success callback to read from the received JSON:
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/myproject/public/module/save',
async: false,
// you can use an object here
data: { id: id, details: details },
success: function(json) {
console.log(json.id + ' ' + json.details);
}
});
// you might need to do this, to prevent anchors from following
// or form controls from submitting
return false;
});
And from your controller, send the data like this:
$data = $this->_request->getPost();
echo Zend_Json::encode(array('id' => $data['id'], 'details' => $data['details']));
As a closing point, make sure that automatic view rendering has been disabled, so the only output going back to the client is the JSON object.
Simplest way for getting this is:
$details=$this->getRequest()->getPost('details');
$id= $this->getRequest()->getPost('id');
Hope this will work for you.

Categories