AJAX response with fatal error - php

I'm making the following ajax request.
$.ajax({
url: '../app/Models/UserFiles.php',
data:'data',
dataType: 'json',
success: function(data)
{
var id = data[0];
var name = data[1];
$('#results').append("id: " +id+ "name: "+name);
}
});
After checking the response with FireBug I noticed this response:
Fatal error: Class 'Illuminate\Database\Eloquent\Model' not found in C:\xampp\htdocs\bluedrive
\drive\app\Models\UserFiles.php on line 6
I can't find anything wrong with UserFiles.php. This actually is the file:
<?php
namespace App\Models;
use \Illuminate\Database\Eloquent\Model;
use Auth;
use App\Models\Filecontent;
class UserFiles extends Model{
protected $table = 'files';
public function getUserFiles(){
$userid = Auth::id();
$getFiles = Filecontent::where('userid', $userid)->get();
foreach($getFiles as $getFile) {
$result = $getFile;
echo json_encode($result);
}
}
} ?>
What am I doing wrong?

The url in ajax call should be something like this:
...
url: <?php echo URL::route('route_to_handle_posted_data.post') ?>
...
Or, if the ajax call is in a js file you can define a
var route_to_post = <?php echo URL::route('route_to_handle_posted_data.post') ?>;
somewhere in templates.

Related

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",

Codeigniter Ajax JSON return not working

I have a view inside which I have a button on which after a click I would like to retrieve some data from the controller.
This is inside the view:
<script>
$('.ajaxBtn').click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '/ajaxController',
data: "",
dataType:'json',
success : function(response){ console.log(response); alert(response)}
});
});
</script>
My controller looks like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class ajaxController extends MY_Controller
{
function __construct()
{
parent::__construct();
}
function index()
{
echo json_encode("datafromajax");
}
}
And I have a route defined like this:
$route['ajaxControl'] = "ajaxController/index";
However I have no response data even though the response is 200.
Thanks for any help
EDIT2// Loading a JSON from for an online source works fine
EDIT// Response:
XHR Loaded (index - 200 OK - 39.48300000047311ms - 35.38KB) VM3852:3
http://davids-macbook-pro.local:5757/ajaxController/index VM3853:3
Object {startedDateTime: "2016-04-09T08:45:16.133Z", time:
39.48300000047311, request: Object, response: Object, cache: Object…}cache: Object__proto__: Object__defineGetter__:
defineGetter()defineSetter: defineSetter()lookupGetter: lookupGetter()lookupSetter: lookupSetter()constructor: Object()hasOwnProperty: hasOwnProperty()isPrototypeOf:
isPrototypeOf()propertyIsEnumerable:
propertyIsEnumerable()toLocaleString: toLocaleString()toString:
toString()valueOf: valueOf()get proto: get proto()set
proto: set proto()connection: "122019"pageref: "page_7"request: ObjectbodySize: 0cookies: Array[2]headers:
Array[11]headersSize: 1099httpVersion: "HTTP/1.1"method:
"POST"queryString: Array[0]url:
"http://davids-macbook-pro.local:5757/ajaxController/index"proto:
Objectresponse: Object_transferSize: 35380bodySize: 34973content:
Objectcookies: Array[0]headers: Array[10]headersSize: 407httpVersion:
"HTTP/1.1"redirectURL: ""status: 200statusText: "OK"proto:
ObjectstartedDateTime: "2016-04-09T08:45:16.133Z"time:
39.48300000047311timings: Object__proto__: Object
Chnage the string to array in json_encode()
From echo json_encode("datafromajax"); To echo json_encode(['data'=>"datafromajax"]);
You need to define base_url()
eg.
$arr = array("str"=>"datafromajax");
echo json_encode($arr);
And in the ajax function
url: <?php echo base_url();?> +'ajaxController'
success : function(response){ console.log(response.str); alert(response.str)}

jquery Ajax url point to php functions

hi is it possible to retrieve data from a PHP function using Ajax?.
i want my url in ajax to point in one of my functions. please see my code below.
like this:
<?php
class employee{
public function __construct(){
}
public function fName($fName){
echo $fName;
}
public function lName($lName){
echo $lName;
}
}
?>
<div id="fName"></div>
<script type="text/javascript">
$.ajax({
type: 'POST',
url: "classes.php", <!-- HERE I want to target the fname function-->
success: function(result){
fname.html(result);}
});
</script>
what im doing so far is create a new php page which contain code like this.
<?php
$employee = new employee();
$employee->fName();
then ill point the ajax url to that new php page.
Assuming this code works as written in your question
<?php
$employee = new employee();
$employee->fName();
you can pass a parameter to your PHP script then decided which function is to be called like so:
jQuery:
$.ajax({
type: 'GET',
url: "classes.php?func=fname",
success: function(result) {
$("fname").html(result);
}
});
PHP - classes.php:
<?php
$employee = new employee();
$func = #$_GET["func"];
switch($func) {
case "fname":
echo $employee->fName();
break;
case "lname":
echo $employee->lName();
break;
default:
break;
}
The url property has to be a url .. in your case it perhaps will point to "/classes.php" , assuming the file is on document root of the webserver
The function fName needs to be called by the code present in that url.
so your file "/classes.php" should look like this
<?php
class Employee {
protected fName;
protected lName;
function __construct($f, $l) {
$this->fName = $f;
$this->lName = $l;
}
public function getFName(){
return $this->fName ;
}
public function getLName(){
return $this->lName ;
}
}
$employee = new Employee("John" , "Doe");
echo $employee ->fName();

Ajax call in Core PHP,

in one of my front end PHP files im doing this in my Jquery :
var name = $('#core_name').val();
var param = {};
param['name'] = name;
$.ajax({
url:'../back_end/user.php/verify_name',
data:param,
type:'POST',
success:function(result){
alert(result);
}
});
In my back_end/user.php im doing this :
<?php
class User{
function index(){
//for now do nothing
}
function verify_name(){
echo "here";
}
}
?>
Why cant i alert "here", what is it that iam doing wrong ?
Firebug detects no error , so the file user.php has correct path (no 404 error) why cant i reach the function verify_name ?
You need to instantiate the User class and call verify_name() on back_end/user.php.
You can do this adding the following to back_end/user.php:
$user = new User;
$user->verify_name();

AJAX and Codeigniter Controller

I want to dynamically parse RSS feeds.
I have a select list and I would like to send a value (id) to the controller with ajax.
and after, I want to parse RSS feeds corresponding to the id
My Controller home.php :
function view($type = NULL)
{
$data = array();
$this->load->model('flux_model');
if ($type == "ajax") {// load ajax view
$flux = $this->flux_model->get_one_flux($this->input->post('id'));// ajax id
$flux2 = $flux[0]->url_flux;
$xml = new SimpleXMLElement($flux2, NULL, TRUE);
//my foreach
$this->load->view('messages_list', $data);
}
else{ // load the default view
$nb_min = 0;
$nb_max = 7;
$nombre = mt_rand($nb_min,$nb_max);
$flux = $this->flux_model->get_one_flux($nombre);
$flux2 = $flux[0]->url_flux;
$xml = new SimpleXMLElement($flux2, NULL, TRUE);
//my foreach
$this->load->view('default', $data);
}
}
Ajax script :
$("#myform1 #rss").change(function(){
var msg = $('#myform1 #rss').val();
$.post("<?= site_url('home/view/ajax') ?>", {id: msg}, function() {
$('#main').load("<?= site_url('home/view/ajax') ?>");
$('##myform1 #country').val('');
});
});
view default works, I parse an RSS feed randomly
but with the ajax view, I have this error:
Message: SimpleXMLElement::__construct(): I/O warning : failed to load external entity ""
it looks like I do not get the id?! ajax problem?
I think your issue is with
$.post("<?= site_url('home/view/ajax') ?>" [etc.]
Because many sites' configurations will prevent cross-site Ajax requests (See XSS), your $.post will be prevented. Instead, try something like:
$.post("controller/method/parameters" [etc.]
Example:
In your JavaScript:
$.post("ajax/myajax/myparam",{},function(data) { alert(data); });
And in your controllers/ajax.php file:
class Ajax extends CI_Controller
public function __construct()
{
parent::__construct();
}
public function myAjax(parameter='')
{
/**
* Load models, or whatever. Then echo the results, so that
* $.post gets its "data" var.
*/
}
}
I hope this helps!
I just replace :
$.post("<?= site_url('home/view/ajax') ?>", {id: msg}, function() {
$('#main').load("<?= site_url('home/view/ajax') ?>");
$('##myform1 #country').val('');
});
by
$.post('<?= site_url('home/view/ajax') ?>', options, function(data) {
$('#content').html(data);
})

Categories