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)}
Related
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",
Am apology for my bad english. Am new to prestashop. Please anybody help. How to send AJAX request to custom php file in prestashop
//My js file
$.ajax({
url : baseUrl + "modules/<myModule>/ajaxfunc.php",
type: "POST",
cache: false,
data : {form_data: 1 , action:'imageuploadAction'},
beforeSend: function() {
$('body').append('<div class="loading_popup">Loading...</div>');},
success: function(data){
console.log(data);
}
});
// php file
// modules/<myModule>/ajaxfanc.php
<?php
include_once('../../config/config.inc.php');
include_once('../../init.php');
class ajaxfuncAjaxModuleFrontController extends ModuleFrontController
{
public function imageuploadAction() {
die('here');
}
}
?>
I didn't know its be correct or not. please guide me.
You can use an ajax front controller in your module and generate the URL you need for the Ajax request in the module itself with a hook.
See Make an ajax request from a Prestashop module
I have found the solution to get the proper Ajax request in prestashop 1.7
//In tpl file
<script>
var url= {url entity='module' name='<myModuleName>' controller='<MyControllerName>' params = ['var1' => 1,'var2' => 2,action => 'MyControllerAction']}
</script>
//In Js file
$.ajax({
url : url,
type: "POST",
data : 'var3='3,
success : function(response){
console.log(response);
}
});
//In Controller Php file
<?php
require_once(dirname(__FILE__).'../../../../config/config.inc.php');
require_once(dirname(__FILE__).'../../../../init.php');
class <MyModule><MyController>ModuleFrontController extends ModuleFrontController
{
public function initContent()
{
$this->ajax = true;
parent::initContent();
}
// displayAjax for FrontEnd Invoke the ajax action
// ajaxProcess for BackEnd Invoke the ajax action
public function displayAjaxMyControllerAction()
{
$var1 = Tools::getValue('var1');
$var2 = Tools::getValue('var2');
$var3 = Tools::getValue('var3');
header('Content-Type: application/json');
die(Tools::jsonEncode(['var1'=> $var3]);
}
}
I'm learning AJAX and I'm trying to do an AJAX request with parameters, but I'm having problems to send the JSON data:
I'm using Typescript and PHP (with Codeigniter), the idea is to create a Typescript object and send it to the PHP in JSON format. So basically I create an object and use the stringify method that I find on Google to convert this object to JSON (or a string in form of JSON I should say?) and send it to the server with AJAX, but the data is not arriving properly.
I used print_r($_POST); to see what is the server receiving and it shows to me the following:
Array
(
[{"_dificultad_seleccionada":"Normal"}] =>
[0] =>
)
The entire string that I get from stringify is shown as the key and the value is empty.
I don't understand very well what is happening, isn't stringify the way to convert an object to JSON and send it to the server? Why it isn't sending the object properly?
Client code:
Dificultad.ts (class that I want to send to the server)
class Dificultad {
private _dificultad_seleccionada: string;
constructor (dificultad_seleccionada: string) {
this._dificultad_seleccionada = dificultad_seleccionada;
}
get dificultad_seleccionada(): string {
return this._dificultad_seleccionada;
}
set dificultad_seleccionada(dificultad_seleccionada: string) {
this._dificultad_seleccionada = dificultad_seleccionada;
}
}
Lib.ts (where I declare all const, DOM elements, etc.)
const BASE_URL: string = window.location.origin + "/Project_name/";
type CallbackFunction = (arg: any, ...args: any[]) => void;
Main.ts (here is where I send the AJAX)
$(document).ready(function() {
$( "a#boton_seleccion_dificultad" ).click(function(event) {
event.preventDefault();
if (pasapalabra.gameState == GameState.GAME_STARTING) {
let _dificultad: Dificultad = new Dificultad("Normal");
sendAjaxRequest("POST", "get_dificultad_seleccionada", JSON.stringify(_dificultad), function(response) {
console.log(response);
});
}
});
});
function sendAjaxRequest(_type: string, _url: string, _params: string, _callback: CallbackFunction) {
var request = $.ajax({
type: _type,
url: BASE_URL + _url,
data: _params,
contentType: 'json'
});
request.done(function(res) {
_callback(res);
});
request.fail(function(jqXHR, textStatus) {
console.error(jqXHR)
_callback({ err: true, message: "Request failed: " + textStatus });
});
}
Server code:
Welcome.php
class Welcome extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->database();
$this->load->library("grocery_CRUD");
date_default_timezone_set('Europe/Madrid');
$this->load->library('session');
$this->load->helper('url');
$this->load->model("Rol_model");
$this->load->model("Questions_model");
}
public function get_dificultad_seleccionada() {
print_r($_REQUEST); print_r($_POST);
//echo json_encode($dificultad);
}
}
It seems to be a problem with the object conversion that I do with stringify on the client because if I change the ajax call like this, sendind a JSON manually, it works:
Main.ts
sendAjaxRequest("POST", "get_dificultad_seleccionada", {"_dificultad_seleccionada":"Normal"}, function(response) {
console.log(response);
});
It seems that I'm doing something wrong but I have no idea of what could be, how can I send this object to the server in JSON format?
I want to do an universal function for all AJAX request in my program, but I don't know very well if I'm doing it properly, is the type of the callback function ok? or am I wrong with this?
Thank you very much for your help.
I think I have solved the problem, I'm sending the same data like I did before but now I use contentType: 'json' to tell the server that I'm sending a JSON and in the server side (PHP) I use the following to get the json: json_decode(file_get_contents('php://input'), true);
Main.ts
$(document).ready(function() {
$( "a#boton_seleccion_dificultad" ).click(function(event) {
event.preventDefault();
if (pasapalabra.gameState == GameState.GAME_STARTING) {
let _dificultad: Dificultad = new Dificultad("Normal");
sendAjaxRequest("POST", "get_dificultad_seleccionada", JSON.stringify(_dificultad), function(response) {
console.log(response);
});
}
});
});
function sendAjaxRequest(_type: string, _url: string, _params: string, _callback: CallbackFunction) {
var request = $.ajax({
type: _type,
url: BASE_URL + _url,
data: _params,
contentType: 'json'
});
request.done(function(res) {
_callback(res);
});
request.fail(function(jqXHR, textStatus) {
console.error(jqXHR);
_callback({ err: true, message: "Request failed: " + textStatus });
});
}
Welcome.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->database();
$this->load->library("grocery_CRUD");
date_default_timezone_set('Europe/Madrid');
$this->load->library('session');
$this->load->helper('url');
$this->load->model("Rol_model");
$this->load->model("Questions_model");
}
public function get_dificultad_seleccionada() {
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["_dificultad_seleccionada"];
}
}
Now the server gets the value properly and I supose that now it's getting it in JSON format.
I have the following problem happening consistently on my code.
I have a data model with the following function:
data_model.php
public function testFunc(){
return "string";
}
site.php (controller)
public function get_more_data(){
$this->load->model('data_model');
$data['test']=$this->data_model->testFunc();
return $data;
}
home.php (view)
<html>
<body>
<button class="test">test</button>
</body>
<script>
$('.test').click(function(){
$id=1;
$.ajax
({
url: '<?php echo site_url() ?>index/site/get_more_data',
data: $id,
type: 'post',
success: function(result)
{
alert(result);
}
});
});
</html>
However every time I click the button I always get this error:
XMLHttpRequest cannot load http://[::1]/codeignitor/index.phpindex/site/get_more_data. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
What am I doing wrong or not understanding correctly here?
Thanks,
I use ajax in my CodeIgniter projects using the following procedure :
I send data to controllers using queries (like : xxxx.com?id=5)
I receive data using echo in the controller
I am using a class to do some CRUD stuff on a database, this one (http://net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql) I am going to use jquery to check the if the username has been registered already.
I could just create a php file specifically for that task, but would just like to extend the class and create a method callled checkname().
How can I call this in jquery?
You can use jQuery to make ajax call to a php file following:
PHP [suppose, test.php]
<?php
class ABC extends XYZ {
public function checkname() {
if(isset($_POST) && !empty($_POST['name'])) {
echo json_encode(array('status' => 'done'));
}
}
}
$ins = new ABC();
$ins->checkname(); // calling the function checkname
?>
jQuery:
$.ajax({
url: 'test.php', // write the url correctly
type: 'post',
data: "name=XYZ&location=PQR"
}).done(function(response) {
console.log(response.status); // will log done
}).fail(function(jqXHR, textStatus) {
console.log("Failed: " + textStatus);
});
It is just an example.
You'll need to use jQuery's Ajax functionality to access a PHP page that calls that function. You can't directly call a PHP function via Ajax, something on the backend has to be set up.