Ajax + Controller Action in Yii2 - javascript

I'm new to programming, and I'm trying to call a function when the user inputs data and clicks submit button. I'm using Yii2 and I'm not familiar with Ajax. I tried developing a function, but my controller action isn't called.
Here is the example code I'm trying:
views/index.php:
<script>
function myFunction()
{
$.ajax({
url: '<?php echo Yii::$app->request->baseUrl. '/supermarkets/sample' ?>',
type: 'post',
data: {searchname: $("#searchname").val() , searchby:$("#searchby").val()},
success: function (data) {
alert(data);
}
});
}
</script>
<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<h1>Supermarkets</h1>
<ul>
<select id="searchby">
<option value="" disabled="disabled" selected="selected">Search by</option>
<option value="Name">Name</option>
<option value="Location">Location</option>
</select>
<input type="text" value ="" name="searchname", id="searchname">
<button onclick="myFunction()">Search</button>
<h3> </h3>
Controller:
public function actionSample(){
echo "ok";
}
My problem is that when I click on the Search button nothing happens, and when I try to debug it, the debugger runs no code!

This is sample you can modify according your need
public function actionSample()
{
if (Yii::$app->request->isAjax) {
$data = Yii::$app->request->post();
$searchname= explode(":", $data['searchname']);
$searchby= explode(":", $data['searchby']);
$searchname= $searchname[0];
$searchby= $searchby[0];
$search = // your logic;
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return [
'search' => $search,
'code' => 100,
];
}
}
If this will success you will get data in Ajax success block. See browser console.
$.ajax({
url: '<?php echo Yii::$app->request->baseUrl. '/supermarkets/sample' ?>',
type: 'post',
data: {
searchname: $("#searchname").val() ,
searchby:$("#searchby").val() ,
_csrf : '<?=Yii::$app->request->getCsrfToken()?>'
},
success: function (data) {
console.log(data.search);
}
});

you have to pass _csrf tokin as a parameter
_csrf: yii.getCsrfToken()
or you can disable csrf valdation

The correct way to get the CSRF param is this:
data[yii.getCsrfParam()] = yii.getCsrfToken()

Related

Ajax request not running used in codeigniter 4 [duplicate]

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']);
}
});

calling function in codeigniter controller using ajax not working

I have a codeigniter website, where I have done an add to cart function, on button click the product is added to cart after page reloads which is working fine, I did the following code in controller:
public function buy($id)
{
$color= $this->input->post('color');
$size=$this->input->post('size');
$product = $this->product->find($id);
$item = array(
'id' => $product->id,
'name' => $product->pname,
'quantity' => 1
);
if(!$this->session->has_userdata('cart')) {
$cart = array($item);
$this->session->set_userdata('cart', serialize($cart));
} else {
$index = $this->exists($id);
$cart = array_values(unserialize($this->session->userdata('cart')));
if($index == -1) {
array_push($cart, $item);
$this->session->set_userdata('cart', serialize($cart));
} else {
// $cart[$index]['quantity']++;
// $this->session->set_userdata('cart', serialize($cart));
$this->session->set_flashdata("Error","Product Already In Cart !");
redirect($_SERVER['HTTP_REFERER']);
}
}
$this->session->set_flashdata("Success","Product Added To Cart Successfully !");
redirect($_SERVER['HTTP_REFERER']);
}
Now I am trying to call this function using ajax so that the product is added to cart without page reload. I did the following code:
$("#change").submit(function() {
alert("Change");
var id = $('#prod').val();
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>" + "index.php/homecontroller/buy/" + id,
data: {
'id': id
},
success: function(data) {
$('#resultdiv').html(data);
}
});
});
<form action="" method="post" id="change">
<input type="hidden" value="<?php echo $product->id; ?>" id="prod">
<input type="submit" value="switch">
</form>
<div class="resultdiv">
<?php echo $data; ?>
</div>
However it's not adding to cart, it simply reloads the page. Can anyone please tell me what is wrong in here?
Because the form is still submitting, you can use preventDefault();
$("#change").submit(function(e) {
e.preventDefault();
alert("Change");
var id = $('#prod').val();
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>" + "index.php/homecontroller/buy/" + id,
data: {
'id': id
},
success: function(data) {
$('#resultdiv').html(data);
}
});
});

Laravel - AJAX Search works for Input but not Select

I have been having a little problem. I am trying to create a filter for my database. So far I have come up with this:
Blade File:
<input type="text" class="form-control" id="search" name="search" placeholder="Name, NORAD or ID"></input>
<select name="filtername" id="filtername">
<option value="none"></option>
<option value="Falcon">Falcon</option>
<option value="rb">R/B</option>
</select>
Javascript AJAX Call:
$(document).ready(function() {
$('#search').on('keyup', function() {
$value = $(this).val();
delay(function() {
if ('#search'.length > 3) {
$.ajax({
type: 'get',
url: '{{$launchsitename->site_code}}',
data: {
'search': $value
},
success: function(data) {
$('#launchsatdisplay').html(data);
}
});
}
}, 300);
});
$("#filtername").change(function() {
var filtername = $(this).val();
var dataString = "filtername=" + filtername;
$.ajax({
type: "get",
url: "{{$launchsitename->site_code}}",
data: {
'search': dataString
},
success: function(data) {
$('#launchsatdisplay').html(data);
}
});
});
});
Controller:
if ($request->ajax())
{
$output="";
$launchsitesatellite = DB::table('satellites')
->where(function($q) use ($request) {
$q->orWhere('satname','LIKE','%'.$request->search.'%')
->orWhere('norad_cat_id','LIKE','%'.$request->search.'%')
->orWhere('object_id','LIKE','%'.$request->search.'%');
})
->where('site', $site_code)->get();
if ($launchsitesatellite)
{
$output .='<tr>'.
'<th>'.'Satellite Name'.'</th>'.
'<th>'.'NORAD ID'.'</th>'.
'<th>'.'Object Type'.'</th>'.
'<th>'.'Launch Date'.'</th>'.
'<th>'.'Country'.'</th>'.
'<th>'.'Object ID'.'</th>'.
'<tr>';
foreach ($launchsitesatellite as $key => $launchsitesatellites) {
$output .='<tr>'.
'<td>'.$launchsitesatellites->satname.'</td>'.
'<td>'.$launchsitesatellites->norad_cat_id.'</td>'.
'<td>'.$launchsitesatellites->object_type.'</td>'.
'<td>'.$launchsitesatellites->launch.'</td>'.
'<td>'.$launchsitesatellites->country.'</td>'.
'<td>'.$launchsitesatellites->object_id.'</td>'.
'</tr>';
}
}
return $output;
}
else {
$launchsitesatellite = DB::table('satellites')->where('site', $site_code)->Paginate(40);
return view('pages/launchsite-filter', compact('launchsites', 'launchsitesatellite'));
}
This code is for making an AJAX call to my controller and getting the results from the database. The code posted above works perfectly for the input. I am able to search the database with ease. The only problem is with the select. Whenever I select an option, it returns no results. I am guessing there is something wrong with the way I programmed the select in my controller, as I don't think the Javascript would be causing the problem.
The select should be reading the satname column in my database called satellites and returning the filtered results.
Would somebody be able to shed some light on why the select is not working or where the error in my code is?
modify your ajax call code for select box as below
$("#filtername").change(function() {
var dataString = $(this).val();
$.ajax({
type: "get",
url: "{{$launchsitename->site_code}}",
data: {
'search': dataString
},
success: function(data) {
$('#launchsatdisplay').html(data);
}
});
});

use Ajax to call function while using another ajax with preventDefault to submit

I am making two AJAX calls in the form. The first is to change the second select based on the first select which calling a PHP page to process the data. The second is to prevent the default post and post the data in another PHP page.
Both Functions are working if I delete the other one. I also have another problem which is the redirect to a new page (using CleanURL). Where should I redirect in the posting page, or once return to the form page?
$('#brand').change(function() {
var brandID2 = $(this).val();
$.ajax({
url: "Calling the models after selecting the brand",
method: "POST",
data: {
brandID: brandID2
},
dataType: "text",
success: function(data) {
$('#model').html(data);
}
});
});
$("#testform").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "Calling the post page",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
//window.location.href = "<?php echo $_SESSION['toRedirectToAfterFilters']; ?>";
}
});
}));
<form name="testform" action="" method="POST">
<select name="brand" id="brand">
<option value=''>Select a Brand</option>
//function to load all the brands
</select>
<select name="model" id="model">
<option value="">Please Select Brand First</option>
</select>
<button type="submit" name="submit" class="">FILTER</button>
</form>
You are missing the id on testform
<form id="testform">...
I would remove the CleanURL dependency and try out each AJAX request one at a time. Then you will immediately see the point of failure. If not, throw a debugger; inside each event handler and step through.
Personally, I would redirect from the server after a successful database write, to simplify the logic and not have to store the success callback URL inside the $_SESSION array.

Error JS send post data to controller -CodeIgniter

I'm developing a web application which is based on CodeIgniter. I'm new to javascript and JS development. I'm sending post data to a method which is located in a controlle r(homepage/questionview). The data I'm sending to the controller doesn't get posted to the controller. Attached you can see the code I am using. Every attempt I made triggers the AJAX error function.
Html code inside the code I'm calling JS method called viewQuestion(id)
<div class="col-md-7 column list-group">
<a href="" id="list" class="list-group-item active" onclick="viewQuestion(<?php echo $question['questionid']; ?>)">
<h4 class="list-group-item-heading"><?php echo $question['questionid'];echo". "; echo $question['questionTitle']; ?></h4>
<p class="list-group-item-text"><?php echo "Vote Count :"; echo $question['votecount']; ?></p>
<p class="list-group-item-text"><?php echo "Asked user :"; echo $question['username']; ?></p>
</a>
</div>
My JS code
I double-checked the URL used and it's accessible.
<script type="text/javascript">
function viewQuestion(id)
{
$.ajax({
url: '<?php echo base_url(); ?>homepage/questionview',
type: 'POST',
data: { listid: id },
success: function () {
alert('suc');
},
error: function (error) {
// alert('error');
console.log(error);
}
});
}
</script>
homepage/questionview (controller)
public function questionview()
{
//echo $listid;
echo $this->input->post('listid');
}
Few options:
-make sure the onclick event is working, add a alert("test") before the ajax call to make sure you are getting there
-on your controller, try echo "test" to make sure you get the response
-use Chrome console to debug your ajax call and make sure its getting to the controller
Put return false; at the end of the ajax code segment and see. Your code will be like this then.
<script type="text/javascript">
function viewQuestion(id)
{
$.ajax({
url: '<?php echo base_url(); ?>homepage/questionview',
type: 'POST',
data: { listid: id },
success: function () {
alert('suc');
},
error: function (error) {
// alert('error');
console.log(error);
}
});
return false;
}
</script>

Categories

Resources