Json encode error in codeigniter - php

I tried to load a view in my codeigniter controller and also i pass a status to my ajax function. In the ajax function i wrote a sweetalert popup in the sucess function when my status is 1. now my actual problem is when i load a view in the controller the status is not passing to my ajax function.can anyone figureout what the problem is any help is appreciable.
controller
$query = $this->package_view_model->enquiry_history();
if (isset($query))
{
$status = 1;
$this->load->view('packages/enquiry');
}
echo json_encode (array("status"=>$status));
ajax function
function sendMail(package_url)
{
var formData = $("#enqform").serialize();
jQuery.ajax({
type: 'POST',
url: '<?php echo base_url() ?>tour-package/send-mail',
data: formData,
dataType: 'json',
success: function(data){
if(data.status == 1){
swal({
title:'Thankyou for your interest!!!',
text: "Our excecutives will contact you soon.",
html: true,
type: "success",
showCancelButton: false,
showConfirmButton:false
});
window.setTimeout(function() {
window.location.href = '<?php echo base_url() ?>tour-packages';
}, 1000000);
}
}
});
return false;
e.preventDefault();
}

Hope this will help you :
$query = $this->package_view_model->enquiry_history();
$status = 1;
if (! empty($query))
{
$this->load->view('packages/enquiry');
}
echo json_encode(array("status" => $status));
exit;

I think there is a problem with the ending slash in the baseurl. So, change the way you're generating the url.
function sendMail(package_url)
{
var formData = $("#enqform").serialize();
jQuery.ajax({
type: 'POST',
url: '<?php echo base_url("tour-package/send-mail") ?>',
data: formData,
dataType: 'json',
success: function(data){
if(data.status == 1){
swal({
title:'Thankyou for your interest!!!',
text: "Our excecutives will contact you soon.",
html: true,
type: "success",
showCancelButton: false,
showConfirmButton:false
});
window.setTimeout(function() {
window.location.href = '<?php echo base_url() ?>tour-packages';
}, 1000000);
}
}
});
return false;
e.preventDefault();
}

Related

Codeigniter 405 method not allowed AJAX JQuery

I am facing on problem, I have made a CRUD code with AJAX for my CI page, it is working fine on XAMPP server but when I uploaded it to Live Server (Godaddy), it's not fetching data from database and showing 405 Method not Allowed error.
http://www.fenxteksolutions.com/admin/metalinks
Here is my Code.
<script>
$(function(){
showAllEmployee();
//Add New
$('#btnAdd').click(function(){
$('#myModal').modal('show');
$('#myModal').find('.modal-title').text('Add New Meta Detail');
$('#myForm').attr('action', '<?php echo base_url() ?>admin/addEmployee');
});
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var meta_tag = $('input[name=txtMetaTag]');
var meta_desc = $('input[name=txtMetaDesc]');
var result = '';
if(empoyeeName.val()==''){
empoyeeName.parent().parent().addClass('has-error');
}else{
empoyeeName.parent().parent().removeClass('has-error');
result +='1';
}
if(address.val()==''){
address.parent().parent().addClass('has-error');
}else{
address.parent().parent().removeClass('has-error');
result +='2';
}
if(meta_tag.val()==''){
meta_tag.parent().parent().addClass('has-error');
}else{
meta_tag.parent().parent().removeClass('has-error');
result +='3';
}
if(meta_desc.val()==''){
meta_desc.parent().parent().addClass('has-error');
}else{
meta_desc.parent().parent().removeClass('has-error');
result +='4';
}
if(result=='1234'){
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type ="updated"
}
$('.alert-success').html('News '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
}
});
//edit
$('#showdata').on('click', '.item-edit', function(){
var id = $(this).attr('data');
$('#myModal').modal('show');
$('#myModal').find('.modal-title').text('Edit Employee');
$('#myForm').attr('action', '<?php echo base_url() ?>admin/updateEmployee');
$.ajax({
type: 'ajax',
method: 'get',
url: '<?php echo base_url() ?>admin/editEmployee',
data: {id: id},
async: false,
dataType: 'json',
success: function(data){
$('input[name=txtEmployeeName]').val(data.page);
$('textarea[name=txtAddress]').val(data.title);
$('input[name=txtMetaTag]').val(data.meta_tag);
$('input[name=txtMetaDesc]').val(data.meta_desc);
$('input[name=txtId]').val(data.id);
},
error: function(){
alert('Could not Edit Data');
}
});
});
//delete-
$('#showdata').on('click', '.item-delete', function(){
var id = $(this).attr('data');
$('#deleteModal').modal('show');
//prevent previous handler - unbind()
$('#btnDelete').unbind().click(function(){
$.ajax({
type: 'ajax',
method: 'get',
async: false,
url: '<?php echo base_url() ?>admin/deleteEmployee',
data:{id:id},
dataType: 'json',
success: function(response){
if(response.success){
$('#deleteModal').modal('hide');
$('.alert-success').html('Employee Deleted successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function(){
alert('Error deleting');
}
});
});
});
//function
function showAllEmployee(){
$.ajax({
type: 'ajax',
url: '<?php echo base_url() ?>admin/showAllEmployee',
async: false,
dataType: 'json',
success: function(data){
var html = '';
var i;
for(i=0; i<data.length; i++){
html +='<tr class="odd gradeX">'+
// '<td>'+data[i].id+'</td>'+
'<td>'+data[i].page+'</td>'+
'<td>'+data[i].title+'</td>'+
'<td>'+data[i].meta_tag+'</td>'+
'<td>'+data[i].meta_desc+'</td>'+
'<td>'+
'Edit'+
'</td>'+
'<td>'+
'Delete'+
'</td>'+
'</tr>';
}
$('#showdata').html(html);
},
error: function(){
alert('Could not get Data from Database');
}
});
}
});
</script>
This code is working very well in XAMPP Server and giving all data from database and all functions are working very well, but on hosting it is not fetching data and when I inspect the page in console it gave 405 method not allowed error.
Your error is in type parameter in ajax. Remove it or set it to GET. It is actually request method
$.ajax({
type: 'GET',
url: '<?php echo base_url() ?>admin/showAllEmployee',
async: false,
dataType: 'json',
success: function(data){
.......................

Unable to get the response from ajax call in yii2

I have a GirdView which includes checkbox. Now I have a button which i routed to another action controller. Below is my code
<?= GridView::widget([
'dataProvider' => $dataProvider,
/*'filterModel' => $searchModel,*/
'id'=>'grid',
'columns' => [
['class' => 'yii\grid\CheckboxColumn'],
'Meter Serial Number',
'Issued To',
'Store',
],
]); ?>
Set PDF
$(document).ready(function () {
$('#myid').click(function() {
var keys = $('#grid').yiiGridView('getSelectedRows');
// alert(keys);
$.post({
url: 'ogpheader/viewsetpdf',
dataType: 'json',
data:{keylist: keys},
success:function(data) {
alert('Done')
}
});
}) });
Then in my controller
public function actionViewsetpdf()
{
/*$model = $this->findModel($id);
print_r($model);*/
if(isset($_POST['keylist']))
{
$keys = json_decode($_POST['keylist']);
print_r($keys);
}
exit();
}
When I click on the button i get empty view. I followed this tutorialI don't know what is the problem. I am stuck to it.
Update1
While checking it in network
Update 2
As suggested I have tried with $.ajax and below is the result
Update 3
After changing the JS
$('#myid').click(function(e) {
e.preventDefault();
var keys = $('#grid').yiiGridView('getSelectedRows');
// alert(keys);
$.ajax({
url: '<?= URL::toRoute(["ogpheader/viewsetpdf"])?>',
dataType: 'json',
data:{keylist: keys},
type: 'post',
success:function(data) {
alert('Done')
}
});
The result is
Any help would be highly appreciated.
Change the controller and see what return, probably csrf token missing that why you got empty output
public function actionViewsetpdf()
{
if(isset($_POST['keylist']))
{
$keys = json_decode($_POST['keylist']);
print_r($keys);
}
else{
echo 'no data';
}
exit();
}
POST method required csrf token so you have to pass _csrf token as a parameter
$.ajax({
url: 'ogpheader/viewsetpdf',
type: 'post',
dataType: 'json',
data: {
keylist: keys,
_csrf: '<?=Yii::$app->request->getCsrfToken()?>'
},
success: function(data) {
console.log(data);
}
});
Or you can disable csrf valdation by adding this to your controller
public function beforeAction()
{
if ($this->action->id == 'viewsetpdf') {
Yii::$app->controller->enableCsrfValidation = false;
}
return true;
}
Or simplest way just change POST to GET
$.post() has limited parameter to pass. Use $.ajax(). Also you need to add e.preventDefault() to stop redirection from a tag
$(document).ready(function () {
$('#myid').click(function(e) {
e.preventDefault();
var keys = $('#grid').yiiGridView('getSelectedRows');
// alert(keys);
$.ajax({
url: '<?php echo URL::toRoute(["ogpheader/viewsetpdf"]); ?>',
dataType: 'json',
data:{keylist: keys},
type: 'post',
success:function(data) {
alert('Done')
}
});
}) });
Use below js
<?php
$url = Url::toRoute(['ogpheader/viewsetpdf']);
$this->registerJs(<<< JS
$(document).ready(function () {
$('#myid').click(function() {
var keys = $('#grid').yiiGridView('getSelectedRows');
$.ajax({
url: '$url',
data: {keylist: keys},
type: "POST",
dataType: 'json',
success:function(data) {
alert('Done');
}
});
});
});
JS
); ?>

How to upload image file with ajax?

problem when upload image MVC with ajax, i have controls_class.php content function upload_img_admin in class settings calling from page c_ajax_img.php
page c_ajax_img.php
include_once('controls_class.php');
$ajax_up_img = new settings;
$ajax_up_img->upload_img_admin(#$_FILES['file_upload']);
function upload_img_admin in class settings
function upload_img_admin()
{
$dir_name=dirname(__FILE__)."/upload/";
$path=#$_FILES['file_upload']['tmp_name'];
$name=#$_FILES['file_upload']['name'];
$size=#$_FILES['file_upload']['size'];
$type=#$_FILES['file_upload']['type'];
$error=#$_FILES['file_upload']['error'];
...
...
if( isset($_FILES['file_upload']) )
{
move_uploaded_file($path,$dir_name.$name);
...
...
echo "ok";
}
else
{
echo "File not found";
}
}
function ajax get data form and send to function previous for upload image
$(document).ready(function() {
$(".btn_upload_avatar").click(function(e) {
$('.msgerror').hide().fadeIn(1000).html( '<div class="loading"></div>');
e.preventDefault();
$.ajax({
type:"POST",
url: "../controls/c_ajax_img.php",
cache: false,
processData:false,
contentType: false,
data:$("#form_up_img").serialize(),
success: function (data)
{
if(data == 0){
$('.msgerror').addClass('msgerror_in2').html(data);
}else{
$('.msgerror').addClass('msgerror_in2').html(data);
}
}
});
});
});
Something like this might help you mate.. :)
$(document).ready(function () {
$('#UploadForm').on('submit',(function(e) {
$('.msgerror').hide().fadeIn(1000).html('<div class="loading"></div>');
e.preventDefault();
var formData = new FormData(this);
formData.append('file', input.files[0]);
$.ajax({
url: '../controls/c_ajax_img.php',
data: formData,
contentType: false,
type: 'POST',
processData: false,
success: function (data) {
console.log("success");
console.log(data);
},
error: function (data) {
console.log("error");
console.log(data);
}
});
});
});
FYI
FormData
ProcessData is set to false so that it prevents jQuery from automatically transforming the data into a query string

Simple ajax call in wordpress for upvoting post

Here's my ajax call:
$("#yes, #no").click(function(){
var upOrDown = $(this).attr('id');
$.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
action: "updateVote",
data: {upOrDown: upOrDown},
dataType: "json",
success: function(data) {
console.log(data.output);
}
});
return false;
});
Here's the function in functions.php
function updateVote() {
echo json_encode(array(
'output' => 'hello!'
));
die();
}
add_action('wp_ajax_updateVote', 'updateVote');
add_action('wp_ajax_nopriv_updateVote', 'updateVote');
Why does this keep returning "0". It should return "hello!"
Thanks.

Select2 remote source on dropdown field

I have a city field, where on inlinedit call it will load ajax data on dropdown list. Please check my code & let me know where am I wrong. I read the select2 documentation
<script type="text/javascript">
jQuery(function($) {
$('#city_id').editable({
type: 'select2',
name: 'otmp_tx_user_details:city_id',
pk:"userdetailid:<?php if($student_info->userdetailid) echo $student_info->userdetailid; else echo "0";?>",
ajax: {
url: "<?php echo site_url()?>students/get_city_by_country",
dataType: 'json',
data: function () {
return;
},
results: function (data) {
return {results: data};
}
},
url: "<?php echo site_url();?>students/inlineedit",
success: function(data) {
}
});
});
</script>
Here is my ajax data from PHP file:
$array = array(
array("id"=>1,text=>"Dhaka"),
array("id"=>2,text=>"Pabna")
);
echo json_encode($array);
Please help me to solve my problem.
Try wrapping your Ajax object inside a select2 object, like so:
jQuery(function($) {
$('#city_id').editable({
type: 'select2',
name: 'otmp_tx_user_details:city_id',
pk:"userdetailid:<?php if($student_info->userdetailid) echo $student_info->userdetailid; else echo "0";?>",
select2: {
ajax: {
url: "<?php echo site_url()?>students/get_city_by_country",
dataType: 'json',
data: function () {
return;
},
results: function (data) {
return {results: data};
}
}
},
url: "<?php echo site_url();?>students/inlineedit",
success: function(data) {
}
});
});

Categories