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
Related
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 !!
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')
I'm trying to pass a long Html string from a view to a controller using an ajax call, so I can pass it further to another view.
Markup:
<a id="openPDF">Save as PDF</a>
JS:
$('#openPDF').click(function(){
var htmlText = $( "div.modal" ).html(); //grab the html
var dataToSend = JSON.stringify("{strData : '" + htmlText + "' }");
console.log(dataToSend ); // contains the json
$.ajax({
url: "/dashboard/pdf",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: dataToSend
success: function (msg) { alert(msg.d); },
error: function (type) { alert("ERROR!" + type.responseText); }
});
});
Controller:
public function pdf(){
$data['htmlString'] = json_decode($this->input->post('strData'));
$this->load->view('pdf', $data);
}
My ajax call doesn't work because when a click the #openPDF button i get the alert error:
ERROR! NULL
What am I doing wrong?
Are you setting your headers properly before writing the output?
Controller:
public function pdf() {
$data['htmlString'] = json_decode($this->input->post('strData'));
$viewString = $this->load->view('pdf', $data, true); // this returns view as string rather than outputting it
header('Content-Type: application/json');
echo json_encode(['viewString' => $viewString]);
}
In client-side js, you can pass this success function to $.ajax()
success: function (response) {
if ('undefined' !== typeof response.viewString) {
// append view to concerned element
$('#viewTarget').append(response.viewString);
} else {
console.log('response did not contain viewString');
}
},
I hope this helps.
Also:
Navigate directly to the url (the one you are sending an ajax request for) in your browser and see if you get a valid json output.
I've build a small CMS in Codeigniter for a website with a couple of forms.
The forms are all submitted with the ajax method in jQuery and passed to the controller. All works fine but I figured it out that I always get a success, no matter if the data is saved in the database or not. The method only checks if the data is passed to the controller properly, i guess. On success there is a message for the user (Saved), this will fire everytime, no matter what happens behind the scenes. How I can force success (or done, or some other callback) to get the "Saved" message only if the data is saved?
Here is the code:
//javascript
$("#save_club").click(function(){
var club_name = $('input[name="club_name"]').val();
var location = $('input[name="location"]').val();
var phone = $('input[name="phone"]').val();
$.ajax({
type: "post",
url: base_url + "/clubs/save_club/",
data: {club_name:club_name,location:location,phone1:phone1},
success:function(data)
{
$('input[type="submit"]').attr("value", "Saved!");
$('input[type="submit"]').css("background-color", "#32c310");
$('input[type="submit"]').css("cursor", "default");
$(".dynamic_content").load(base_url + "/clubs/clubs_list");
}
});
});
//controller
public function save_club(){
$newdata = array();
$newdata['club_name'] = $this->input->post("club_name");
$newdata['location'] = $this->input->post("location");
$newdata['phone'] = $this->input->post("phone");
$this->load->model("model_save");
$this->model_save->save_club_to_db($newdata);
}
You first would need to validate the inputs with PHP. For example:
<?php
$success = 'true';
foreach($_POST as $input) {
if ($input == '') {
$success = 'false';
break;
}
}
echo $success;
?>
Next, check the return with the data var you passed in the success function:
$.ajax({
type: "post",
url: base_url + "/clubs/save_club/",
data: {club_name:club_name,location:location,phone1:phone1},
success:function(data)
//Whatever PHP echoes in the script gets put into the variable data
{
var result = (data ? 'saved!' : 'error!'); //data should either be true or false
$('input[type="submit"]').attr("value", result);
$('input[type="submit"]').css("background-color", "#32c310");
$('input[type="submit"]').css("cursor", "default");
$(".dynamic_content").load(base_url + "/clubs/clubs_list");
}
});
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.