To show Ajax call value on same controller while using front controller - php

I wanted to send ajax data to controller page and display ajax data on template file in prestashop 1.6 .
I am using this method but not able to get any results -
tpl file :
<input type="button" class="btn btn-primary" id="test" onclick = "testing()" value="test" />
function testing() {
url = '{$link->getModuleLink("hotelapi", "filter")|escape:"html"}';
$.ajax({
url: url,
type : 'GET',
cache : false,
data : {
ajax: 1,
action: 'fetchTPL',
},
success: function(html){
alert("SUCCESS:");
},
error: function() {
alert("ERROR:");
}
});
}
Front Controller file - File name is - filter.php
<?php
/*require (dirname(__FILE__) . '/../../../../config/config.inc.php');
require (dirname(__FILE__) . '/../../../../init.php');*/
class hotelapiFilterModuleFrontController extends ModuleFrontController
{
public function displayAjaxFetchTPL()
{
echo 'hello';
//after processing all data just assign it to smarty of content
/*$this->context->smarty->assign(array(
'youContentData' => $_POST['room'])
);
// to fetch a tpl file use fetch method and use die function to return the response to ajax
die($this->context->smarty->fetch('a1.tpl'));*/
}
}
My ajax url is executing successfully but I am not able to print anything written inside displayAjaxFetchTPL action.
Please anyone help me with this problem.
Thanks and regards,
Ridhi Bhutani

php:
public function displayAjaxFetchTPL()
{
$data = ['mYtxt' => 'hello'];
die(Tools::jsonEncode($data));
}
jquery:
success: function (html) {
alert(html.mYtxt);
},

Instead of using the "onclick" event on your button, why not use a JQuery event lsitener?
Your HTML would be something like this:
<input type="button" class="btn btn-primary" id="test" value="test" />
And your JS like this:
$("#test").on("click", function () {
url = '{$link->getModuleLink("hotelapi", "filter")|escape:"html"}';
$.ajax({
url: url,
type: 'GET',
cache: false,
data: {
ajax: 1,
action: 'fetchTPL',
},
success: function (html) {
alert("SUCCESS:"+html);
},
error: function () {
alert("ERROR:");
}
});
});

Related

How to use ajax in codeigniter 4

I am using codeigniter-4 version and trying to auto search in nav bar. I'm trying to send data in post method into controller using ajax. But its not work. And codeigniter 4 don't described details for ajax. below my code sample
input box is -
<input class="form-control mr-sm-2" type="search" placeholder="<?= lang('nav.search'); ?>" aria-label="Search" name='s' id="seachBox">
ajax code is -
$.ajax({
url:<?= base_url('search'); ?>,
headers:{'X-Requested-With':'XMLHttpRequest'},
data:{query:query},
success:function(data){
alert(data);
}
});
and my controller is -
<?php
class Search extends BaseController
{
public function __construct()
{
helper(['common_helper','aws_helper']);
}
public function index(){
echo 'string';
}
}
?>
route is -
<?php
$routes->get('/search', 'Search::index');
?>
Here is the sample code of ajax. (Make sure that you have defined route/controller method for search url)
$.ajax({
url:<?php echo base_url('search'); ?>,
type: 'post',
dataType:'json',
data:{query:query},
success:function(data){
alert(data);
}
});
CI4 Code to get the request data
if ($this->request->isAJAX()) {
$query = service('request')->getPost('query');
var_dump($this->request->getPost('query'));
}
Also, make sure to update csrf token on every request if you are not reloading a page on success. Also, you need to return csrf token in method.
So in that case your method will look like -
if ($this->request->isAJAX()) {
$query = service('request')->getPost('query');
//var_dump($this->request->getPost('query'));
return json_encode(['success'=> 'success', 'csrf' => csrf_hash(), 'query ' => $query ]);
}
So in that case your ajax code will look like -
$.ajax({
url:<?php echo base_url('search'); ?>,
type: 'post',
dataType:'json',
data:{query:query},
success:function(data){
var result = JSON.parse(data);
$("input[name='csrf_test_name']").val(result['csrf']);
}
});

How to prevent page reload while bookmarking it?

I am making a book library site using laravel. I am trying to add bookmark functionality. I have tried doing something like that on click of bookmark button, page no is being send to database and it is working. Issue is that on return from controller page is getting reload causing book to back on page no 1. Is there is any way that data sends to database without page reload??
I know a bit that ajax do this, but I am using JavaScript in my application and I tried to deploy ajax with it but no luck.
I am showing up my code. Any good suggestions would be highly appreciated.
My javascript function:
function bookmark()
{
book = '<?php echo $book->id ?>';
$.ajax({
type: "post",
url: "save_bookmark",
data: {b_id:book, p_no:count},
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
}
count is defined up in script.
My route:
Route::post("save_bookmark/{b_id}/{p_no}",'BookmarkController#create')->name('save_bookmark');
My controller:
public function create($b_id, $p_no)
{
$b=new bookmark;
$b->u_id=Auth::user()->id;
$b->book_id=$b_id;
$b->p_no=$p_no;
$b->save();
return response()->json([
'status' => 'success']);
}
My html:
<li><a id="bookmark" onclick="bookmark()" >Bookmark</a></li>
Note: There is a navbar of which bookmark is a part. There is no form submission.
try this: use javascript to get the book id
$("#btnClick").change(function(e){
//console.log(e);
var book_id= e.target.value;
//$token = $("input[name='_token']").val();
//ajax
$.get('save_bookmark?book_id='+book_id, function(data){
//console.log(data);
})
});
//route
Route::get("/save_bookmark",'BookmarkController#create');
you need add event to function and add preventDefault
<button class="..." onclick="bookmark(event)">action</button>
in js:
function bookmark(e)
{
e.preventDefault();
book = '<?php echo $book->id ?>';
$.ajax({
type: "post",
url: "save_bookmark",
data: {b_id:book, p_no:count},
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
}
in controller you ned use it:
use Illuminate\Http\Request;
...
...
public function create(Request $request)
{
$b=new bookmark();
$b->u_id=Auth::user()->id;
$b->book_id=$request->get('b_id');
$b->p_no=$request->get('p_no');
$b->save();
return response()->json([
'status' => 'success']);
}
in route use it:
Route::post("save_bookmark/",'BookmarkController#create')->name('save_bookmark');
Well, assuming your bookmark() JavaScript function is being called on a form submit, I guess you only have to prevent the form to be submitted. So your HTML code would looks like this:
<form onsubmit="event.preventDefault(); bookmark();">
Obviously, if you're handling events in your script.js it would rather looks like this:
HTML
<form id="bookmark" method="POST">
<input type="number" hidden="hidden" name="bookmark-input" id="bookmark-input" value="{{ $book->id }}"/>
<input type="submit" value="Bookmark this page" />
</form>
JavaScript
function bookmark(book_id, count) {
$.ajax({
type: "post",
url: "save_bookmark",
data: {
b_id: book_id,
p_no: count
},
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
});
}
let form = document.getElementById('bookmark');
let count = 1;
console.log(form); //I check I got the right element
form.addEventListener('submit', function(event) {
console.log('Form is being submitted');
let book_id = document.getElementById("bookmark-input").value;
bookmark(book_id, count);
event.preventDefault();
});
Also I would recommend you to avoid as much as possible to insert PHP code inside your JavaScript code. It makes it hard to maintain, it does not make it clear to read neither... It can seems to be a good idea at first but it is not. You should always find a better alternative :)
For example you also have the data-* to pass data to an HTML tag via PHP (more about data-* attributes).

Laravel 5: Fetch ajax data in route and pass to controller

I'm using Laravel 5 and want to make ajax call to a controller with some data:
$.ajax({
url : "/getOrgById",
data : JSON.stringify({id:1})
})
The routes.php has:
Route::get('/getOrgById', 'HomeController#getOrgById');
HomeController.php:
public function getOrgById($data) {
//code here fails with message 'Missing argument 1 for HomeController::getOrgById()
}
How can I pass the data from ajax to route and then to controller?
I think the below example is what you're looking for
Route
Route::post('/getOrgById', 'HomeController#getOrgById');
Controller
public function getOrgById(Request $request) {
$id = $request->input('id');
}
JS
var myJsonData = {id: 1}
$.post('/getOrgById', myJsonData, function(response) {
//handle response
})
You should really look into resourceful controller actions. If you are wanting to fetch an organisation by its ID then you have an organisaiton entity, so create a corresponding organisation controller. This controller can then have a method to show an organisation by on its primary key value:
class OrganisationController
{
public function show($id)
{
return Organisation::findOrFail($id);
}
}
The route for this would look like:
Route::get('/organisations/{id}', 'OrganisationController#show');
You can then request this route via AJAX like so:
$.ajax({
method: 'GET',
url: '/organisations/' + id
});
You can use Input to get your variable
public function getOrgById() {
$data = \Input::get('data')
}
You can define paramers in your route:
Route::get('/getOrgById/{id}', 'HomeController#getOrgById');
And call it through:
$.ajax({
url : "/getOrgById" + id
})
You were almost right, but when using $data in your function declaration you're actually requiring a Query String variable, rather than a form request.
You have to add your Form Request in your Controller method, like so:
public function getOrgById(Request $request){
// do something here...
return response()->json(array('foo' => 'bar'));
}
Try with this,
HTML Form
<div id="loadingResponse"></div>
{!!Form::open(array('url'=>'test/submit', 'id'=>'submitForm','method'=>'POST'))!!}
{{Form::token()}}
<input type="text" name="data"/>
<button type="submit" class="btn btn-small btn-info">Send Data</button>
{{Form::close()}}
JS Ajax
$("#submitForm").submit(function(event) {
event.preventDefault();
$.ajax({
url : 'test/submit',
data : new FormData($("#submitForm")[0]),
dataType : 'JSON',
type : 'POST',
beforeSend: function(){
$("#loadingResponse").html("<img src='{{asset('img/loading.gif')}}' />");
},
success: function(response){
console.log(response);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('Error '+xhr.status+' | '+thrownError);
},
});
});
PHP Route
...
Route::post("test/submit","TestController#submit");
...
PHP Controller
class TestController extends Controller
{
...
public function submit(Request $request)
{
response()->json(['msj' => $request->input('data')]);
}
...
}
ajax:
$.ajax({
type:'get',
url:'/getOrgById',
data:{
id:1
},
success:function(res){
}
});
routes.php:
Route::get('/getOrgById', 'HomeController#getOrgById');
HomeController.php:
public function getOrgById(Request $request) {
dd($request);
}

pass the data-id attribute value to a controller method using ajax in codeigniter

I have a button element which has a data-id attribute.I need to to send the data-id to a controller method in codeigniter using jquery ajax post method.I don't have any form .But the ajax request i made can not enter into the controller method .What might be the reason and how i can solve this issue?in my config file i set the base url and rewrite the index.php using htaccess file :
I do get alert('success') after clicking the button
$config['base_url'] = 'http://localhost/mycodeigniter/ci/'
admin controller:
class Admin extends CI_Controller{
public function processReq(){
$this->load->view('admin/processReq');
}
}
button( no form element) :
<button type="button" data-id='approved' class="approved buttons">Approve</button>
ajax method:
$(".buttons").click(function(event){
var status=$(this).data('id');
$.ajax({
url:"<?php echo base_url('admin/processReq') ;?>",
type: "POST",
data: {
status: status
},
success: function(data) {
alert('success');
},
error: function(xhr, status, error) {
var error=xhr.responseText;
alert(error);
}
});
});
You get the alert because the controller sent the browser a reply with a server code of 200. That header response code tells AJAX to call the success function. $this->load->view('admin/processReq'); is where the OK (code 200) came from.
This controller shows another way to handle this so that you can react based on the reply from processReq().
class Admin extends CI_Controller
{
public function index()
{
$this->load->view('admin/processReq'); //if this really is the view file
}
public function processReq()
{
$status = this->input->post('status');
//I am assuming that data('id') is '1' or '0' since you
//don't describe what it actually is I had to make something up.
if($status === '1'){
echo json_encode(array('results' => 'success')) ;
}else{
echo json_encode(array('results' => 'fail')) ;
}
}
}
You need to add one ajax option - dataType: 'json' - for this to work reliably
$.ajax({
url:"<?php echo base_url('admin/processReq') ;?>",
type: "POST",
dataType: 'json',
data: {
status: status
},
Your ajax success function could do this
success: function(data) {
if(data.results === 'success'){
alert('success');
} else {
alert('success');
}
},
An alternative way to indicate a failure would be to output a header with a server code in the 400 or 500 (error) range. If you do that then the ajax error function will be called. SO has lots of examples of how to accomplish that.

prestashop ajax controller call

I am trying to call controller in module using Ajax in prestashop 1.5, and I'm having hard time doing this.
I've created controller in module under the path:
$refresh_url = ($this->_path)."front/blockdiscoversellers.php";
and made instructions for button in js like:
var refresh = {
call: function() {
var $refresh = $("#manufacturer-refresh");
$refresh.click(function(e) {
refresh.ajax();
e.preventDefault();
});
},
ajax: function() {
var url = $("#manufacturer-refresh").data("url");
$.ajax({
url: url,
type: 'get',
data: {
controller : 'BlockDiscoverSellers',
ajax : true
},
dataType: "json",
success: function(data) {
console.log(data);
}
});
}
};
and the body of controller looks like :
class BlockDiscoverSellers {
public function __construct()
{
die(var_dump($this->refreshManufacturers()));
}
public function refreshManufacturers()
{
$result = array("test" => "TESTER");
return Tools::jsonEncode($result);
}
}
I'm getting success in Ajax call but it looks like class and constructor are not initiated, so I am quite stuck with this problem.
It appears that prestashop when you use ajax call uses only structural type of programming. That means in ajax call there can be no class of any sort bootstrap will never initiate it even with controller parameter, and you have to die at the end of file ...

Categories