How to call controller from another url with post data? - codeigniter

I have a problem with my project using codeigniter.
I want to run some controller from another url(without my project) with post data.
I'm using codeigniter framework?
so have any way to do this?
Please help me resolution this problem...

All I can think of is using ajax , but this is not recommended to use javascript as a part of the controller
in controller A
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class controllerA extends CI_Controller {
function __construct()
{
// you can put the ajax call here if you want it to run each time you call this controller
}
public function ajaxcall()
{
// make sure you didn't call jquery before so you won't have conflicting scripts
echo '<script src="https://code.jquery.com/jquery-1.11.3.min.js"> </script>';
// now we use ajax to post to the controller B
echo
'<script>
var target_url = "http://www.example.com/projectB/controllerB"
var Data = {user_id:542,name:"Baci"};
$.ajax(
{
url : target_url,
type: "POST",
data : Data,
success: function(data)
{
alert("all right request was sent via Ajax ");
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("request failed ! ");
}
});
</script>
' ;
// continue your code on your controller while the ajax call is being sent
}
}

Related

Send data per Ajax to Controller in Laravel 5.8

I have the Ajax request
Here is the code of script
<script>
$('#variant_model').change(function(){
var value = $('select#variant_model').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type:"POST",
url: "showVariantModel",
data: value,
success: function(data){
alert(data);
}
})
});
</script>
When I put in my web.php the code
Route::post('/showVariantModel', function(){
if(Request::ajax()){
return var_dump(Response::json(Request::all()));
}
});
Everything looks fine and I receive the response in my alert.
But when I want to put everything into controller I receive the error 500 in the console
Below I will add my code from my web.php and Controller.
Framework is Laravel 5.8
//web.php
Route::post('/showVariantModel', 'VariantsController#checkAttribute');
//VariantsController.php
public function checkAttribute()
{
if(Request::ajax()){
return var_dump(Response::json(Request::all()));
}
Who knows what am I doing incorrect, please give an advice...
Updating the error
https://i.stack.imgur.com/iDvvG.jpg
Thank's Md.Sukel Ali I updated my controller. Not it looks
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Variants;
class VariantsController extends Controller
{
public function checkAttribute(Request $request)
{
if($request->ajax()){
return response()->json($request->all());
}
}
}
Everything works fine now.
Thank you.
The closing tag is missing
public function checkAttribute()
{
if(Request::ajax()){
return Response::json(Request::all());
}
}
Instead of blinding guess what happening under the hood of ajax call. I suggest you to learn how to debug ajax request.
Go to your browser right click and Inspect then go to Network tab then you can see your request. Click on your request then look for response tab. There you can find exactly what happened.
public function checkAttribute(Request $request)
{
if($request->ajax())
{
return response()->json($request->all());
}
}
You need to add imports in your controller:
use Illuminate/Http/Request;
use Illuminate/Http/Response;

ajax post to controller and display into custom element file

i need to fetch data from database from controller file and display into element file and ajax value showing in inspect element and also when i alert in ajax it is showing that value is going to controller.
but problem is that how can i echo or print ajax value in controller to fetch data from database and display it into element file?
how can i render custom element file in controller function?
ajax script
<script>
$('#categories .accordion .tablist .tablistitem').on('click', function () {
event.preventDefault();
$(".accordion li").removeClass("active");
var $li = $(this);
$liid = $li.attr('id');
$slug = $li.data('slug');
$li.addClass("active");
$('#wrapper').append('<span id="load">LOADING...</span>');
$('#categories_info').show();
$.ajax({
type: 'POST',
url: '/reviews/getsubcategories',
data: {"selectid":$liid },
dataType:"text",
success: function(data, textStatus, xhr) {
alert(data);
},
error: function(xhr, textStatus, error) {
alert(textStatus);
}
});
});
</script>
controller function
function getsubcategories()
{
echo $selectid= $_POST['selectid'];
return $selectid;
}
element file
$SubCategoryObj = cri('Reviews');
$selectid = $SubCategoryObj->getMainCategories();
echo $selectid;
What you have done so far is mostly right, however in the past I have just created the view as normal in the View/Reviews folder.
In the controller set your data:
/app/Controller/ReviewsController.php
public function getsubcategories()
{
$this->layout = 'ajax';
$data = /**code to get data**/
$this->set('data', $data);
}
/app/View/Reviews/getsubcategories.ctp
<?php echo json_encode($data); ?>
another option is to create the same view above but put it in file app/View/Ajax/json.ctp
And then inside the controller the last thing you call in the getsubcategories action is.
$this->render('Ajax/json');
In my experience elements are used inside views and not as replacements of views

Cakephp Ajax post data not working in set method

I am trying sent one data from one view to another controller and set the data for another view. Here is ajax code working fine
$.ajax({
url: "<?php echo Router::url(array('controller'=>'users','action'=>'exchange_process'));?>",
type: "POST",
data: {"point_origin": point_origin },
success: function(){
alert("success");
}
});
In controller I have received this data by bellow code
public function exchange_process()
{
if($this->request->is(array('post', 'ajax'))) {
$point_origin=$_POST['point_origin'];
}
$this->set("pointorg",$point_origin);
}
In another view I have tried
<?php echo $pointorg ?>
It's not working.
if I try
public function exchange_process()
{
if($this->request->is(array('post', 'ajax'))) {
// $point_origin=$_POST['point_origin'];
}
$point_origin=123;
$this->set("pointorg",$point_origin);
}
It's working,but if I try
public function exchange_process()
{
if($this->request->is(array('post', 'ajax'))) {
// $point_origin=$_POST['point_origin'];
$point_origin=123;
}
$this->set("pointorg",$point_origin);
}
It's not working.
change your if clause to:
if($this->request->is('post') || $this->request->is('ajax')) {
and it should be working fine
CakePHP 2.3 doesnot support array of type headers, please check
http://book.cakephp.org/2.0/en/appendices/2-4-migration-guide.html#cakerequest
you will need to check individually or use Ajax only if request is to be sent using Ajax only.

Ajax request to override controller in prestashop 1.6

outside the conventional methods of ajax requests from a prestashop module, I would like to use a ajax method from product.js and retrieve data from an override controller.
my function in product.js :
function attrReference(ref){
$.ajax({
url: baseUri,
async: true,
cache: false,
type:'GET',
dataType : "json",
headers: { "cache-control": "no-cache" },
data: {
controller :'product',
action :'attrReference',
token : token,
ajax: 1,
ref : ref
},
success: function(data){
}
});
}
My override controller product :
class ProductController extends ProductControllerCore{
public function displayAjaxAttrReference(){
echo '<pre style="background:yellow">';
print_r($_GET);
echo '</pre>';
exit;
}
}
From the documentation, i use displayAjax to recover data, unless this is not the right method, I tried many attempts but none are correct.
Do you have any idea?
If you need to retrieve data, or little piece of html i suggest to avoid the displayAjax function since it's called only at the end of the controller routine, and thus you will get everything processed (retrieving of template, database query and so on).
normally the controller function are called with the following list:
init();
setMedia();
// postProcess handles ajaxProcess
postProcess();
initHeader();
initContent();
initFooter();
displayAjax() || display();
as you can see displayAjax should be avoided if you don't want to retrieve the whole page/a template the require all the information of the product page.
To correctly route your request you should override also the postProcess function of your product controller such that:
public function postProcess(){
if(Tools::isSubmit('action') && Tools::getValue('action') == 'attrReference')
$this->AjaxGetReference();
parent::postProcess();
}
and then
public function AjaxGetReference(){
echo '<pre style="background:yellow">';
print_r($_GET);
echo '</pre>';
die();
}
Also, always remember to pass the id_product with your ajax function if you are interacting with the ProductController, else any action will fail becouse of the init function:
public function init()
{
parent::init();
if ($id_product = (int)Tools::getValue('id_product'))
$this->product = new Product($id_product, true, $this->context->language->id, $this->context->shop->id);
if (!Validate::isLoadedObject($this->product))
{
header('HTTP/1.1 404 Not Found');
header('Status: 404 Not Found');
$this->errors[] = Tools::displayError('Product not found');
}
}

how to access a controller function from outside of controller in codeigniter

I have a folder (suppose it's name is "test") outside of controller folder which contains a file name "error404.php" and my controller name is "test_controller.php" which has a method name "tst()". error404.php is a view page in where i want to access data from test_controller.php via ajax.
<script>
$(document).ready(function(e) {
$('#search_items_err').keyup(function(e) {
if($('#search_items_err').val().trim()==''){$('#sugglist').html(''); return false;}
search_key=$(this).val().trim();
var data = {
search_key: search_key
};
alert(search_key);
$.ajax({
data: data,
type: "post",
url: "test_controller/tst",
success: function(response) {
var options = JSON.parse(response);
alert(options);
}
});
});
});
</script>
My tst function is:
public function tst(){
$search_key = $_POST['search_key'];
echo "success";
}
But my ajax doesn't work. I suspect that it may contain some problems in the (url: "test_controller/tst",). So how can i solve it? What is the syntax of accessing test_controller's method from error404.php page?How do i access base url?
Take a look at this ajax concept
in your ajax function :
url : baseURL+'test_controller/search', //Make sure this url is working properly
data : {'search_key' : search_key},
in you test_controller/search
public function search()
{
//generate data and load your view
$data = "Generated Data array";
$this->load->view('test_folder/search', $data); //Load your view from application/view/ not from outside the controller
}

Resources