ajax json working on local but not on remote server codeigniter - php

Visit here and the search bar in front is the autocomplete
it is working fine when I use on localhost and appends results in the li under but when I have uploaded on live server it shows 404.
This is the link to custom.js on which browser shows 404();
Main: Custom.js:
$(document).ready(function () {
$("#CompanyName").keyup(function () {
$.ajax({
type: "POST",
url: "http://www.sonnify.de/reviewotter/autocomplete/GetCompanyName",
data: {
keyword: $("#CompanyName").val()
},
dataType: "json",
success: function (data) {
if (data.length > 0) {
$('#Dropdowncompany').empty();
$('#CompanyName').attr("data-toggle", "dropdown");
$('#Dropdowncompany').dropdown('toggle');
alert("i am here");
}
else if (data.length == 0) {
$('#CompanyName').attr("data-toggle", "");
}
$.each(data, function (key,value) {
if (data.length >= 0)
$('#Dropdowncompany').append('<li role="displayCompanies"
id="displayCompanies" ><a role="menuitem
dropdowncompanyli" class="dropdownlivalue">' +
value['CompanyName'] + '</a></li>');
});
}
});
});
$('ul.txtcompany').on('click', 'li a', function () {
$('#CompanyName').val($(this).text());
var CompanyName = $(this).text();
alert(CompanyName);
window.location.href = "http://localhost/reviewotter/company2?
company="+CompanyName+"";
//window.location.href = "http://localhost/reviewotter/company2?
lat="+elemA+"&lon="+elemB+"&setLatLon=Set";
});});
Model: datacomplete.php:
<?php
class Datacomplete extends CI_Model{
public function GetRow($keyword) {
$this->db->order_by('Id', 'DESC');
$this->db->like("CountryName", $keyword);
return $this->db->get('company')->result_array();
}}
Controller: autocomplete.php
<?php
class Autocomplete extends CI_Controller{
function __construct() {
parent::__construct();
$this->load->model('datacomplete');
}
public function index(){
//$this->load->view('view_demo');
$this->load->view('home');
}
public function GetCompanyName(){
$keyword=$this->input->post('keyword');
$data=$this->datacomplete->GetRow($keyword);
echo json_encode($data);
}
}
?>

Let me guess, localhost is on a Windows machine but the live server is Linux? Then it is probably a case sensitivity problem. Linux is a case-sensitive OS.
The model file datacomplete.php should be Datacomplete.php (Notice the uppercase first character?) and the controller autocomplete.php should be Autocomplete.php.

You will be able to get this resolved by adding a custom route. Please add below line to application/config/routes.php file.
$route['autocomplete/get-company-name'] = 'Autocomplete/GetCompanyName';
You will have to adjust your JQuery AJAX function according to the new URL. Also can remove the index.php from the URL. Please refer below link.
https://www.codeigniter.com/userguide3/general/urls.html#removing-the-index-php-file

Related

Ajax pagination not works properly and returns failure

I'm working with Laravel 9 and I wanted to make an infinite loader pagination with ajax for my blade.
So at the Controller:
public function index(Request $request)
{
$ques = Question::orderBy('created_at', 'DESC')->where('que_private',0)->paginate(10);
if($request->ajax()){
$view = view('frontend.layouts.partials.infinite',compact('ques'))->render();
return response()->json(['html' => $view]);
}
return view('frontend.index', compact('ques'));
}
And in the index.blade.php:
function loadMoreData(page){
$.ajax({
url: '?page=' + page,
type:'get',
beforeSend: function ()
{
$(".ajax-load").show();
}
})
.done(function(data){
if(data.html == ""){
$('.ajax-load').html("");
return;
}
$('.ajax-load').hide();
$("#post-data").append(data.html);
})
.fail(function(jqXHR,ajaxOptions,thrownError){
alert("Server is not responding");
});
}
And this is infinite.blade.php which ajax loads:
<div id="post-data">
#foreach($ques as $que)
...
#endforeach
</div>
When I test this, the image comes up properly but it returns Server is not responding error alert meaning that .fail(function(jqXHR,ajaxOptions,thrownError){ runs instead.
So what's going wrong here?
How can I solve this issue?

I'm making an dependent drop-down of countries states and cities in Laravel 9 using jQuery and Ajax but getting an 500 internal server

I'm making an dependent drop-downn of countries states and cities in laravel using jQuery and Ajax. I'm doing it on localhost Xampp. First i use jQuery for country. when country change jQuery get value and send to Controller. But when i send value from RegistrationFormComponent to CountryStateCity Controller and try to show what value i get. I got an error ( POST http://127.0.0.1:8000/getstate 500 (Internal Server Error) ). i don't know why im getting this error.
Route:
Route::get('/register', [CountryStateCityController::class, 'getcountry']);
Route::POST('/getstate ', [CountryStateCityController::class, 'getstate']);
JQuery and Ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$('#country').change(function () {
var cid = this.value; //$(this).val(); we cal also write this.
$.ajax({
url: "getstate",
type: "POST",
datatype: "json",
data: {
country_id: cid,
},
success: function(result) {
// if(cid == "success")
// alert(response);
console.log(result);
},
errror: function(xhr) {
console.log(xhr.responseText);
}
});
});
});
Controller
class CountryStateCityController extends Controller
{
public function getcountry() {
$country = DB::table('countries')->get();
$data = compact('country');
return view('RegistrationForm')->with($data);
}
public function getstate(Request $request) {
$state = State::where('countryid'->$cid)->get();
return response()->json($state);
}
public function getcity() {
}
}
I think i tryed every possible thing. But didn't work. Please tell me how can i get rid of this problem. And please also tell me how can i send data from component to controller using jquery and ajax and get value form controller and take data from database and send back to component.
This is written incorrectly.
public function getstate(Request $request) {
$state = State::where('countryid'->$cid)->get();
return response()->json($state);
}
It should look like this.
public function getstate(Request $request) {
$state = State::where('countryid', '=', $request->country_id)->get();
return response()->json($state);
}
please check controller function
public function getstate(Request $request) {
$state = State::where('countryid' `=` ,request->$countryid)->get();
return response()->json($state);
}

CodeIgniter ajax link not found

I'm having an issue with getting data from Controller, I have tried all the solutions here but it's the same..
when I click on the button it says 404 not found, if I change the URL to completed URL included the controller class name + function name, it says 403
Here is my view code :
<h2>Quiz</h2>
<script type="text/javascript">
$(document).ready(function(){
var BASE_URL = '<?php echo base_url(); ?>';
$('#show').click(function(e){
console.log(BASE_URL);
$.ajax({
url: BASE_URL + "Quiz/get_item",
dataType:'text',
type:"POST",
success: function(result){
var obj = $.parseJSON(result);
console.log(obj);
}
})
})
});
</script>
<button id="show">Show Cutomers</button>
<div id="customers-list"></div>
<p>Our first multi-page CodeIgniter application! Each page has its own controller and view!</p>
Here is my Controller code :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Quiz extends CI_Controller {
var $TPL;
public function __construct()
{
parent::__construct();
$this->load->model('Quiz_data');
// Your own constructor code
}
function show_customers()
{
$query = $this->db-> query("SELECT * FROM quiz ORDER BY id;");
$this->TPL['listing'] = $query->result_array();
$this->template->show('quiz', $this->TPL);
}
public function index()
{
$this->template->show('quiz', $this->TPL);
}
public function get_item(){
$data = $this ->Quiz_data->get_data();
echo json_encode($data);
}
}
Here is my Model code :
<?php
class Quiz_data extends CI_Model {
public function get_data()
{
$query = $this->db->get('quiz');
return $query -> result_array();
}
}
What is the output of
console.log(BASE_URL);
Didnt mess with CI for quite a while, but it used to need /index.php/ in the URL. Try:
url: BASE_URL + "/index.php/quiz/get_item",
Although the controller-name needs to start with a capital, it doesnt need to be called that way in the URL.
Make sure url: BASE_URL + "Quiz/get_item" provides the correct URL.
var BASE_URL = '<?php echo base_url(); ?>'; May not provide trailing slash and you won't get correct url.
Try updating your call with following:
url: BASE_URL + "/Quiz/get_item",

Export CSV using Laravel via Ajax

I have a export csv function, it worked fine with laravel. But now I want to call export function via ajax and use method post, but I there is no respone. I can send a variable from laravel controller to response, but can not send a file download.
Here is my code :
route.php
Route::get('/title/show', 'TitleController#show');
Route::post('/title/show', 'TitleController#exportFromDB');
show.blade.php
<script>
$(document).ready(function () {
$('#exportFromDB').click(function () {
$.ajax({
url: "",
type: "post",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {},
success: function (response) {
var a = document.createElement("a");
a.href = response.file;
a.download = response.name;
}
})
})
})
TitleController.php:
$dataExport['Oversea'] = $dataOversea;
$this->titleRepository->export('csv', $properties, $dataExport);
TitleRepository.php
public function export($type, $properties, $data)
{
if (in_array($type, self::EXPORT_TYPE)) {
try {
return Excel::create($properties['_title'], function ($excel) use ($data, $properties) {
$excel->setTitle($properties['_title']);
$excel->setCreator($properties['_creator'])
->setCompany($properties['_company']);
$excel->setDescription($properties['_description']);
$excel->sheet('Sheet', function ($sheet) use ($data) {
foreach ($data as $item) {
$sheet->fromArray($item);
}
});
})->export($type);
} catch (Exception $error) {
throw $error;
}
}
}
How can I fix them ? Thank !
Try this -
Don't write the code for export in your controller method, instead just save the excel file in your public folder.
Your controller method should return the filename.
On your ajax success do this -
location.href = path/to/file/property_title.xls
So replace your this line
->export($type);
with
->store($type, 'public/reports/', true);
I see your ajax url null value
Change it to
url : "{{ action('TitleController#exportFromDB') }}"
After that, response is data you return in controller
success: function (response) {}
I installed the maatwebsite/excel package and was able to do it without writing any javascript. All you need to do is setup a link (or typical form post if you prefer) to an action like so:
public downloadItemsExcel() {
$items = Item::all();
Excel::create('items', function($excel) use($items) {
$excel->sheet('ExportFile', function($sheet) use($items) {
$sheet->fromArray($items);
});
})->export('xls');
}
This works for csv/excel files alike. There is no reload of a page in the browser.
First you have to change POST method to GET.
For ajax you can do it like this:
$(document).ready(function () {
$('#exportFromDB').click(function () {
$.get('/title/show, function(data){
window.location = '/title/show=' + data;
});
})
})

How to switch called php page using AJAX in wordpress

I have an several online application forms built into a (they differ per country) and I need to switch from one to the other with a users button click.
The code I have does this however it also produces a 500 error which breaks any other scripts.
Can anyone give me an idea of what I am doing wrong?
//Update appURL
if (jQuery('button[id="ukApp"]').hasClass( "checked" )) {
appURL = "wp-content/plugins/GoMarkets_application/uk/uk-application.php";
} else if (jQuery('button[id="itlApp"]').hasClass( "checked" )) {
appURL = "wp-content/plugins/GoMarkets_application/itl/it-application.php";
}
//Get URL path
function getContextPath() {
var ctx = window.location.pathname,
path = '/' !== ctx ? ctx.substring(0, ctx.indexOf('/', 1) + 1) : ctx;
return path + (/\/$/.test(path) ? '' : '/');
}
//Country Application URL
function getOutput() {
jQuery.ajax({
url: getContextPath() + appURL,
complete: function (response) {
jQuery('#output').html(response.responseText);
},
error: function () {
jQuery('#output').html('Bummer: there was an error!');
}
});
return false;
}
here is your ajax function
$.ajax({
url: ajax.url,
...
dataType: "json",
success: function(response) {
$('#myDiv').html(response.html);
},
})
and the php function
function my_ajax_load() {
$post_id = $_POST['post_id'];
ob_start();
include(locate_template('my-template-file.php',false,false));
$page_template = ob_get_contents();
ob_end_clean();
$response['html'] = $page_template;
wp_send_json($response);
}
in your template file you can use your variables declared in the function, in this example you can you $post_id inside the my-template-file.php
For example:
<?php /* Template name: My template */
if($post_id) {
echo get_the_title($post_id);
}
?>
500 error is caused by php error not ajax or jquery, check out your template file for a php errors
There was a missing image being called by the page I was trying to load, the error only showed up in the logs. Thanks all :)

Categories