$this->request->is('ajax') always false - javascript

I have the code in my view but on sending to my controller action via ajax(as shown in the last part of the add.ctp)
//add.ctp
<?php
echo $this->Form->create('Poll',array('action' => 'index'));
echo $this->Form->input('one', array('id'=>'name'));
echo $this->Form->input('two', array('id'=>'email'));
echo $this->Form->input('three', array('id'=>'message'));
echo $this->Form->input('four', array('id'=>'four'));
echo $this->Js->submit('Send', array('id' => 'btn'), array(
'before'=>$this->Js->get('#sending')->effect('fadeIn'),
'success'=>$this->Js->get('#sending')->effect('fadeOut'),
'update'=>'#success'
));
echo $this->Form->end();
?>
<div id="sending" style="display: none; background-color: lightgreen;">Sending...</div>
<script>
$('#btn').click(function(event) {
form = $("#PollIndexForm").serialize();
// console.log(form);
$.ajax({
type: "POST",
url: 'pollsController/index';,
data: form,
success: function(data){
//
}
});
event.preventDefault();
// return false; //stop the actual form post !important!
});
</script>
on getting to my controller, I made an isAjax request test and if failed
public $components = array('RequestHandler');
public function index(){
$this->autoRender = false;
if($this->RequestHandler->isAjax()){
echo debug('Ajax call');
}
if(!empty($this->data)){
echo debug('not empty');
}
}
I get 'not empty' every time i tried to run this and $this->request->is('ajax') is always false
My version of cakephp is 2.3 and I have tried $this->request->is('ajax') and all that.
I'll appreciate if someone can point out what I am missing out

In your code, you have
if($this->RequestHandler->isAjax()){
Try to make the condition this way:
if ($this->request->is('ajax')) {
}
http://book.cakephp.org/2.0/en/appendices/2-0-migration-guide.html?highlight=isajax#requesthandlercomponent
RequestHandlerComponent: Many of RequestHandlerComponent’s methods are
just proxies for CakeRequest methods. The following methods have been
deprecated and will be removed in future versions: isSsl() isAjax()
isPost() isPut() isFlash() isDelete() getReferer()getClientIp()

Are you sending with your AJAX call the right headers?
{ 'X-Requested-With': 'XMLHttpRequest'}
If you are using jQuery, you can use:
$.ajaxSetup({
headers: { 'X-Requested-With': 'XMLHttpRequest' }
})
You can check it in Chrome developer tools under the network tab, where you must select your request.
and here is the documentation for ajaxSetup()
EDIT:
You can put it here:
<script>
$('#btn').click(function(event) {
form = $("#PollIndexForm").serialize();
$.ajaxSetup({
headers: { 'X-Requested-With': 'XMLHttpRequest' }
})
$.ajax({
type: "POST",
url: 'pollsController/index';,
data: form,
success: function(data){
}
});
event.preventDefault();
// return false; //stop the actual form post !important!
});
</script>

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

Jquery throws an 'Illegal invocation' error

I'm trying to create a forum and jquery throws an 'illegal invocation' error.
Here is my jquery code:
$('#formSumbit').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'data-get.php',
type: 'POST',
data: new FormData(this),
contentType: false,
dataType: 'json',
success: function(value) {
var serialize = $.parseJSON(value);
if (serialize.success == 'false') {
$('.alert').fadeIn().delay(3000).fadeOut();
$('.alert-msgText').html(serialize.datamsg);
}
}
});
});
And here is my PHP code:
<?php
$user = $_POST['user'];
$msg = $_POST['message'];
if(empty($user)&&empty($message)) {
$data = array(
'success' => 'false',
'datamsg' => 'Please fill the textboxes'
);
echo json_encode($data);
} else {
mysqli_query($con,"INSERT INTO forums(name,message) VALUES ('$user','$msg')");
$data = array(
'success' => 'true',
'datamsg' => 'Done!'
);
echo json_encode($data);
}
exit();
?>
When the textboxes are empty and i click the submit button, nothing seems to work and jquery throws an illegal invocation error. I don't understand what the problem is. Can you please help?
And thanks in advance!
1) You have a typo mismatch between your form and your JavaScript:
<form id="formSubmit" and $('#formSumbit') - it should be $('#formSubmit') to match the spellings.
2) Unless you are trying to upload files via this AJAX request, then you can simplify things by replacing data: new FormData(this), contentType: false, with just data: $(this).serialize(). This will get rid of the illegal invocation error.
3) Writing dataType: 'json' means that jQuery will automatically try to parse the data coming from the server as JSON, and convert it. Therefore, in your "success" function, value will already be parsed and converted to an object. In turn therefore, using $.parseJSON is not necessary. You can just access value.success directly, for instance.
Here's a fixed version:
$('#formSubmit').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'data-get.php',
type: 'POST',
data: $(this).serialize(),
dataType: 'json',
success: function(value) {
if (value.success == 'false') {
$('.alert').fadeIn().delay(3000).fadeOut();
$('.alert-msgText').html(value.datamsg);
}
}
});
});
Working demo: https://jsfiddle.net/khp5rs9m/2/ (In the demo I changed your URL for a fake one, just so it would get a response, but you can see where I have altered it and left your settings in the commented-out part).

Retrieve JSON return from PHP called from AJAX

I'm trying to call an PHP file via POST and retrieve its result back in the calling AJAX code. But unfortunately it doesn't seem to work. After fiddling around with my code I either get "undefined", "a page reload" or "an error in the console that my parameter used in the success function isn't defined"
Here's the ajax code:
function postComment(formdata) {
if (formdata.comment != '') {
$.ajax({
type: 'POST',
url: '../../includes/post_comment.php',
data: formdata,
headers: {
'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'
},
success: postSuccess(data), // function to handle the return
error: postError // function to handle errors
});
} else {
alert('Empty please write something!');
}
}
function postSuccess(data) {
console.log(data);
$('#commentform').get(0).reset();
displayComment(data);
}
and here is my PHP handler:
$ajax = ($_SERVER['REQUESTED_WITH'] === 'XMLHttpRequest');
$added = add_comment($mysqli, $_POST); // contains an array
if ($ajax) {
sendAjaxResponse($added);
} else {
sendStandardResponse($added);
}
function sendAjaxResponse($added)
{
header("Content-Type: application/x-javascript");
if ($added) {
header('Status: 201');
echo(json_encode($added));
} else {
header('Status: 400');
}
}
this is what added looks like in PHP:
$added = array(
'id' => $id,//integer example: 90
'comment_post_ID' => $story_ID, //integer example: 21
'comment_author' => $author, //String example: Dominic
'comment' => $comment, //String example: This is a comment
'comment_date' => $date); //DateTime/String example: 08/02/2016 1970-01-01 00:00:00
UPDATES
I changed the ajax code to the following:
$.ajax({
type: 'POST',
url: '../../includes/post_comment.php',
success: postSuccess,
data: formdata,
headers: {
'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'
},
error: postError,
});
Now I get the full HTML-Code of the page calling this ajax function
I tried to set aysnc: false in the ajax request but it didn't help, always getting the html code of the source (calling the ajax function).
As for now I´m moving to a different approach which doesn´t need the return data. But thanks for the help
The browser tries execute server response because of
header("Content-Type: application/x-javascript");
change to
header("Content-Type: application/json");

Getting Alert from ajax request

I have editable html table of user Information. There are some columns such as user_ID, branch_ID etc. when I am going to change the branch_ID of the user I want to check the particular user has tasked assigned to him or not. If he has tasks then update is not allowed. for that I am using the following java script part.
if(field=='branch_ID'){
$.ajax({
type: 'post',
url: 'check_user.php',
data: {udata: user_id},
success: function (data) {
// message_status.text(data);
}
})
}
In check_user.php
$user_id= $_POST['udata'];
$sql1="SELECT * FROM assign_task WHERE user_ID=$user_id";
$query1=mysqli_query($con,$sql1);
if(mysqli_num_rows($query1)>0){
echo"you can't update";
return false;
}
else{
echo"ok with it".$sql1;
}
The thing is I want the respond from check_user.php as an alert and return false to stop updating the content. As I am new to jQuery please help me.
You can use JSON to pass more complex data:
PHP :
if(mysqli_num_rows($query1)>0){
echo json_encode(array("success" => false));
}
else{
echo json_encode(array("success" => true,
"message" => "ok with it".$sql1));
}
Javascript:
success: function (data) {
var jsonData = JSON.parse(data);
if(jsonData.success){
alert(jsonData.message);
}
}
Remember to do more advanced checking on your variables and types first!

How to return success in a ajax call

I have an ajax call to delete a page from my database, but I'm not quite sure how to return success and use it:
My ajax call looks like this:
$('.delete_button').click(function() {
$.ajax({
url: 'delete_page.php',
dataType: 'json',
async: false,
type: 'post',
data: {
page_id: id
},
succes:function() {
alert('something');
if (s.Err == false) {
window.location.reload(true);
}
}, error:function(e){
}
});
});
And in my delete_page.php I have this:
<?php
require 'core/init.php';
$id = $_POST['page_id'];
$page_id = $id[0];
$delete_page = DB::getInstance()->delete('pages', array('id', '=', $page_id));
if ($delete_page) {
$output['Err'] = false;
} else {
$output['Err'] = true;
}
return json_encode($output);
It does delete the page, but it doesn't run the if statement and it is not alerting anything. How do I fix this?
Dont use return, actually output the data, with the correct header:
//return json_encode($output);
header('Content-Type: application/json');
echo json_encode($output);
In your PHP script, you need to output the data instead of returning it:
header('Content-Type: application/json');
echo json_encode($output);
Then in your javascript file you need to retrieve the data:
success: function (data) { // It's success not succes, and you need the parameter
alert('something');
if (data.Err == false) {
window.location.reload(true);
}
}
If that's the entire delete_page.php, it needs to echo the output, not just return it.
Here's a slightly more elegant way of handling this.
Update your delete_page.php script like this:
<?php
require 'core/init.php';
$id = $_POST['page_id'];
$page_id = $id[0];
// Init
$output = array(
'IsDeleted' = false,
'LastError' = ''
);
// Delete
try {
$output['IsDeleted'] = DB::getInstance()
->delete('pages', array('id', '=', $page_id));
}
catch (Exception $ex) {
$output['LastError'] = $ex->getMessage();
}
// Finished
echo json_encode($output);
?>
Then update your ajax code like this:
$.ajax({
url: 'delete_page.php',
dataType: 'json',
async: false,
type: 'post',
data: {
page_id: id
},
dataType: 'json',
succes: function(result) {
if (result.IsDeleted) {
window.location.reload(true);
} else {
alert('Failed to delete. Last error: ' + result.LastError)
}
},
error:function(e) {
}
});

Categories

Resources