Ajax is not working in codeigniter 4 when call the controller - html

I just want to make sure this ajax is working to call my controller. But when i click the button nothing happened. Thank you
My view :
<input type="text" id="phonenumber" name="phonenumber" class="form-control" placeholder="Phone number">
<button type="button" id="sendotp" name="sendotp" class="btn btn-primary btn-block">Sign Up</button>
My AJAX :
$(document).ready(function() {
$('#sendotp').click(function(e) {
e.preventDefault();
var phonenumber = $("input[name='phonenumber']").val();
$.ajax({
url: '<?php echo base_url();?>/register',
type:'post',
dataType:'json',
data: {
phonenumber:phonenumber
},
success: function(data) {
}
});
});
});
My Controller :
public function register()
{
if($this->request->getMethod() == 'post'){
$phonenumber = $this->request->getPost('phonenumber');
echo $phonenumber;
}
return view('register/register');
}
My Routes :
$routes->match(['get', 'post'],'/register', 'Home::register');

In your javascript you have you success event empty. So nothing happening is the expected behavior. If you're returning a view in your controller, you must do something with it in your javascript.

marco answer sufficient.
You need also to add
headers: {'X-Requested-With': 'XMLHttpRequest'}
in your ajax call in JQuery
$.ajax({
url: '<?php echo base_url();?>/register',
type:'post',
dataType:'json',
headers: {'X-Requested-With': 'XMLHttpRequest'},
data: {
phonenumber:phonenumber
},
success: function(data) {
}
});
and in your controller check if its ajax call first before processing anything.
if ($this->request->isAJAX())
{
}
Please refer to isAjax and refer to Ajax JQuery
this is the proper way to handle ajax calls in Codeigniter4 .

I had the same issue I fixed it Like this:
in app/Config/Filter.php make this change:
public $globals = [
'before' => [
'csrf' => ['except' => ['your route or api']]
]
];

Related

I want to Pass Data in a Form to Codeignhter controller throught ajax. when I use this below code sometimes pass data and sometime doesn't

I want to Pass my HTML Form Data in to Codeignhter controller throught ajax. when I check that data passed or not using var_dump() then someitmes it passed data and sometimes doesn't this is the code that I used..
**jQuery Ajax Code**
$(document).ready(function () {
$("#btnSubmit").click(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
// Get form
var form = $('#myform')[0];
// Create an FormData object
var data = new FormData(form);
// If you want to add an extra field for the FormData
data.append("CustomField", "This is some extra data, testing");
// disabled the submit button
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: hosturl + "studentDetail",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 800000,
success: function (data) {
$("#output").text(data);
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);
},
error: function (e) {
$("#output").text(e.responseText);
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);
}
});
});
});
CodeIgniter (Controller) file method code
public function studentDetail_post()
{
$stu = $this->input->post();
var_dump($stu);
die();
}
This is my HTML form code
<form method="POST" enctype="multipart/form-data" id="myform">
<input type="text" name="fname" placeholder="First Name"/><br/><br/>
<input type="text" name="lname" placeholder="Last Name"/><br/><br/>
<input type="file" name="files"/><br/><br/>
<input type="button" value="Submit" id="btnSubmit"/>
</form>
pls give me a solution for this
try this
$.ajax({
type: "POST",
url : "name codeigniter controler/ name function of this controler",
dataType: 'text',
data: $('#myform').serialize(),
success : function(text){
console.log("SUCCESS : ", data);
},
});
and url: "/upload.php" is not studentDetail_post()

How to call my ajax function/fetch with a btn

Im learning how to use API's with ajax in jquery.
I fetched "bored api" in my html page, and I want to update it or run the function again, by pressing a button and without refreshing the page.
I know I would write the function name in my onclick method, but I can't see where the function name should be placed or is.
<p id="activity"></p>
<script>
$(function () {
$.ajax({
type: 'GET',
url: "https://www.boredapi.com/api/activity",
success: function (data) {
console.log("Success", data)
document.getElementById("activity").textContent = data.activity;
}
})
})
</script>
</form>
<button onclick="()">Click me</button>
Have a look on this example from W3 Schools:
Example
It should look something like this:
<p id="activity"></p>
<script>
function doApiRequest() {
$.ajax({
type: 'GET',
url: "https://www.boredapi.com/api/activity",
success: function (data) {
console.log("Success", data)
document.getElementById("activity").textContent = data.activity;
}
});
}
</script>
</form>
<button onclick="doApiRequest()">Click me</button>
You do not need to encapsulate the method inside jquery. and this way, we give it a name, that we can call.

How to refresh an html page using ajax in Django?

I know this question has been asked several times, but I cannot find a solution.
I cannot connect the method output in views with html page.
views
def save_form(request):
if request.method == 'POST' and 'save' in request.POST:
lsection = [5]
print("calculate method runs...")
return JsonResponse({'lsection':lsection})
"calculate method runs..." is printed only when I do not use ajax.
html
<form method="post" name="nameForm" id="idForm"
action = "/project/save/" enctype="multipart/form-data">
{% csrf_token %}
...
<input type="submit" name="save" value="Save">
</form>
ajax
var frm = $('#idForm');
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('save_form'),
url: frm.attr('/project/save/'),
//data: frm.serialize(), // I tried this as well
data: {},
success: function (data) {
alert(data)
},
error: function (data) {
alert("ajax fails")
},
});
});
Question:
I do not get lsection list on html, I try alert(data) I get an empty html.
How can I get lsection on html?
You need attribute's values:
type: frm.attr('method'),
url: frm.attr('action'),
Correct code:
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert(data)
},
error: function (data) {
alert("ajax fails")
}
});
.attr
While receiving JSON response in ajax success you used data.
to show the lsection.
alert(data.lsection)
update alert like above

Ajax call delete cakephp

I'm trying to use ajax delete to delete records that, when clicked, confirms before sending the request.
the record is deleted and it work but the problem is after deleting nothing change in the view until after I reload the page manually.
I want to show the result in view just after click "ok" in the dialog
my ajax code :
$(document).ready(function() {
if($('.confirm_delete').length) {
$('.confirm_delete').click(function(){
var result = confirm('Are you sure you want to delete this?');
$('#flashMessage').fadeOut();
if(result) {
$.ajax({
type:"POST",
url:$(this).attr('href'),
data:"ajax=1",
dataType: "json",
success:function(response){
}
});
}
return false;
});
}
});
in view :
echo $this->Js->link('Delete', array('controller' => 'publications', 'action'=>'delete', $publication['Publication']['id']),
array('escape' => false, 'class'=>'confirm_delete'));
$(document).ready(function(){
if($('.confirm_delete').length) {
$id=$(this).attr('id');
$('.confirm_delete').click(function(){
var result = confirm('Are you sure you want to delete this?');
$('#flashMessage').fadeOut();
if(result) {
$.ajax({
type:"POST",
url:$(this).attr('href'),
data:"ajax=1",
dataType: "json",
success:function(response){
}
});
$('#row'+$id).remove();
}
return false;
});
}
});
For some reason the $(this).attr('id') does not work ... how to get id of the element selected to remove it
I have on my view :
<div class="box_detail" id="row<?php echo $publication['Publication']['id']; ?>">
This is not a CakePHP problem but a JS problem only. If yor delete callback was successful without any error returned you have to remove the related content from the DOM tree. Using jquery this can be done by calling remove() on any selector you want to remove.

Data not getting saved using JQuery.ajax

I want to save data from Textbox on Button click. I am using JQuery AJAX for this task like below. Please note that I made this tags inside theme function.
function theme_user_post_block($vars)
{
$themeUserCommentInput ='';
$themeUserCommentInput .= '<textarea id="txt_1"rows="1" cols="50"></textarea>';
$themeUserCommentInput .= '<input type="submit" value="Post Comment" align="center"
class="btnPostComment" id="btn_1" />'
return $themeUserCommentInput;
}
This able to show me Textbox and Button inside the page. Now here is my JS code:-
(function($)
{
Drupal.behaviors.PostComment= {
attach: function (context, settings) {
$('.btnPostComment', context).click(function (event) {
var post = "&newcomment=Comment1&logid=log1";
jQuery.ajax({
url: 'postcomment',
type: 'POST',
dataType: 'json',
data: post,
success: function (data) { alert(data); },
error: function(jqXHR, textStatus, errorThrown){alert(textStatus +
errorThrown);}
});
});
}
}
})(jQuery);
Next I create a Menu Page with URL Name as follows:-
function postcomment_menu(){
$items=array();
$items['postcomment']=array(
'title'=>t(''),
'type'=> MENU_CALLBACK,
'page callback' => 'user_comment_post',
'access arguments' => array('access content'),
);
return $items;
}
function user_comment_post(){
global $user;
$cid = db_insert('user_comment')
->fields(array(
'comment_user_id' => $user->uid,
'reference_id' => $_POST['logid'],
'comment_desc'=>$_POST['newcomment'],
'createdon'=>REQUEST_TIME,
))
->execute();
if($cid!=0)
{
//GetUserComments($i);
drupal_json_output("success");
}
}
So I have done all things that is required for jQuery+Ajax Submit functionality. When I press "Post Comment" button it gives me error in alert says "errorundefined". The alert shows as a result of error inside the jQuery.AJAX function. Also the custom menu callback is also not getting called.
post the data as object...and make sure your post url is correct.. the url doesn't looks correct
var post = {newcomment: 'Comment1',logid:'log1'};
I came to end of this problem. I dont know what might be the resolution or root cause but I end up solving this problem. I meagre add one line(async: false) in my jQuery.ajax function and everything works perfectly. Please see the code below:
jQuery.ajax({
url: 'postcomment',
type: 'POST',
dataType: 'json',
async: false,
data: post,
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + errorThrown);
}
});
If anyone have any knowledge as what this line will do then please share with us.