How to use ajax in codeigniter 4 - php

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

Related

"Like" system using Laravel, Ajax and jQuery

I don't have the knowledge about Ajax in combination with Laravel. I'm trying to build a like system, its already set up. The problem is; when you click on the like button, the whole page refreshes. But I want it to be dynamic. To do this, I need to use Ajax and jQuery
I have tried building a jQuery function, but I don't know how to parse the {id}
Could you show me where I can learn more about this subject? Maybe a tutorial or could you please explain to me the part I'm missing.
$('.like').on('click', function(event) {
console.log("clicked the button");
$.ajax({
method: 'POST',
url: /{id}/addlike
})
});
This is the like button:
<form action="/{{$new->id}}/addlike" method="post">
#csrf
<button value="{{$new->likes}}" class='like' type="submit"><i class="fas fa-fire"></i></button>
</form>
This is the like route:
Route::post('/{id}/addlike', 'ImageController#like');```
This is the "like" controller
public function like($id)
{
$picture = ImageModel::find($id)->increment('likes');
return back();
}
Remove type='submit' It will redirect your page, just add type="button" and in .like function() ajax should be like this, always apply if and else condition in case you getting some error so it will reflect on your browser console.
$.ajax({
type: "POST",
url: Apiurl,
data: {
"_token": "{{ csrf_token() }}",
"id": id
}
success: function (data)
{
if(data.status == 'success' )
{
//apply your condition
}
else
{
console.log('error');
}
}
});
You can pass data in your ajax functions like data: {id: yourid, name: somename}, and also you can assign laravel variable values to js like this:
var testId = '{{$yourid}}'
So in your case you can make url like testId + '/addlike', also always make id or other dynamic thing go at the end like 'addlike/' + testId.
$('.like').on('click', function(event) {
console.log("clicked the button");
var id = '{{$yourId}}'
$.ajax({
method: 'POST',
url: id + '/addlike'
})
});
Hope it helps
Don't add
return back();
in your controller instead you can use
return response()->json(['success' => 'Liked']);
or anything you want to input there to pass the data in ajax. Don't put action in your post instead you can use hidden input to put your id there and call it (if you're using jquery)
$('input [name=nameofhidden]').val();
then in your ajax add success and what you want to do after updating the data.
var id = $('input[name=nameofhidden]').val();
$.ajax({
method: 'POST',
url: '/'+id+'/addlike',
success: function(ifyouhavedata){
//what you want to do
}
})
JavaScript logic you need to return false, so it'll stop redirecting. see below code.
$('.like').on('click', function(event) {
console.log("clicked the button");
var id = '{{$yourId}}'
$.ajax({
method: 'POST',
url: id + '/addlike'
});
return false;
});
Controller should be return like below
return response()->json(['success' => 'Liked'],200);

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).

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.

Send data through ajax to controller in yii

First of all thanks all for your help, it's very useful. Im starting with yii and Im a bit lost yet.
I have create a jquery script where I validate a form and then I send it to my controller to work with it and save in the db.
But Im doing it wrong I think I cant connect with my controller. Here is the code:
Jquery script(after all the validate stuff, the variables are fine):
$.ajax({
type: "POST",
url: "<?php echo Yii::app()->request->baseUrl; ?>/proceso/guardarproceso",
data:
{
post_nombre: nombre,
post_empresa: empresa,
post_fechaI: fechaI,
post_fechaF: fechaF,
post_descripcion: descripcion
},
success: function(result)
{
alert(result);
}
});
And my controller ProcesoController:
public function actionGuardarProceso(){
$nombre = $_POST['post_nombre'];
$empresa = $_POST['post_empresa'];
$fechaI = $_POST['post_fechaI'];
$fechaF = $_POST['post_fechaF'];
$descripcion = $_POST['post_descripcion'];
echo $nombre;
}
Im not working with the db yet, I only want to see if I have done it well and the alert(result) shows me the content of $nombre, but instead of that the alert shows me all the html code of the view(yes all xD)
I have done it too:
public function accessRules()
{
return array(
array(
'allow',
'actions'=>array('index','guardarproceso'),
'users'=>array('*'),
),
);
}
But nothing...
Anyone cuold help me or give me some idea? Thank you all again
1st error: url: "<?php echo Yii::app()->request->baseUrl; ?>/proceso/guardarproceso",
replace guardarproceso with guardarProceso
2nd error:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
dataType is missing; it should be json
read here http://api.jquery.com/jquery.post/
also, in the controller action actionGuardarProceso, use:
echo json_encode(array('key'=>$nombre));
exit
If a ajax or jquery result prints the html of the page its usually a error in the url.
check your network jumps to see if it goes to the controller action you want.
also baseurl is slower than createUrl. try Yii::app()->createUrl and edit that until it goes to the correct destination.. But the base of my theory is that your url is incorrect.
$.ajax({
type: "POST",
url: "<?php echo Yii::app()->request->baseUrl; ?>/proceso/guardarproceso",
data:
{
post_nombre: nombre,
post_empresa: empresa,
post_fechaI: fechaI,
post_fechaF: fechaF,
post_descripcion: descripcion
},
success: function(result) {
alert(result);
},
error:function(jqXHR, textStatus, errorThrown){
alert('error::'+errorThrown);
}
});
first try this you will get post data or not
public function actionGuardarProceso(){
echo "<pre>";
print_r($_POST);
exit;
}
if not getting any data , try with your model
public function actionGuardarProceso(){
$model = new modelname;
echo $_POST['modelname']['post_nombre'];
exit;
}
else try with the following
public function actionGuardarProceso(){
echo Yii::app()->request->getPost("post_nombre");
exit;
}
i hope you will get now from the above any methods

Unable to retrieve variables from ajax post in codeigniter

I am new to using ajax and I am having trouble with posting variables and accessing those variables in my controllers.
Here is the Controller Code
class autocomplete extends CI_Controller {
// just returns time
function workdammit()
{
$product = $this->input->post('productName');
/* $this->load->model('product_model');
$q = 'SELECT quantity FROM products WHERE productName = "BC20BA"';
$data = $this->product_model->get_record_specific($q);
echo json_encode($data[0]->quantity);
*/
echo $product;
}
function index()
{
$this->load->view('autocomplete_view');
}
}
If I change the echo to a string inside single quotes like this 'Hello World', it will return the hello world back to the view correctly. But it will not do the same if I try it as it currently is. Also if I use echo json_encode($product); it then returns false.
Here is view code with ajax.
$( document ).ready(function () {
// set an on click on the button
$('#button').click(function () {
$.ajax({
type: "POST",
url: "<?php echo site_url('autocomplete/workdammit'); ?>",
dataType: "json",
data: 'productName',
success: function(msg){
alert(msg);
}
});
});
});
</script>
</head>
<body>
<h1> Get Data from Server over Ajax </h1>
<br/>
<button id="button">
Get posted varialbe
</button>
class autocomplete extends CI_Controller {
// just returns time
function workdammit()
{
$product = $this->input->post('productName');
//echo $product;
//in ajax dataType is json -here You have to return json data
echo json_encode($product);
}
...
}
//javascript file
var productName = $('#productName).val();//get value of product name from form
$('#button').click(function () {
$.ajax({
type: "POST",
url: "<?php echo site_url('autocomplete/workdammit'); ?>",
dataType: "json",
data: {productName:productName},//You have to send some data from form
success: function(msg){
alert(msg);
}
});

Categories