Post method not working in Codeigniter - php

I am using HMVC codeigniter. I am trying to use jquery ajax first time. When i use POST then it gives undefined error while it response me the data while using GET.
$.ajax({
type: "POST",
url: filelink+"cart/add_cart_item",
data: {"product_id":id,"quantity":qty,"ajax":"1"},
dataType: "json",
success: function(msg){
alert( "Data Saved: " + msg );
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus + " " + errorThrown);
}
});
What I have tried so far after googling and SO-ing-
my file url location is accessible directly. I checked it. giving response.
Firebug is giving 500 internal server error for the same file.
Using Get is responding me back well
added json in the datatype
controller function
class Cart extends CI_Controller { // Our Cart class extends the Controller class
function __construct()
{
parent::__construct();
$this->template->set('controller', $this);
}
function _remap()
{
$uri2 = $this->uri->segment(2);
if (is_numeric($uri2) OR $uri2 == FALSE) {
$this->index();
} else if ($uri2 == 'add_cart_item') {
$this->add_cart_item();
} else if ($uri2 == 'show_cart') {
$this->show_cart();
}
}
function add_cart_item(){
echo "asdfsadfdsf";
exit;
}
}
can anybody please help me out?

There are possible reasons for your problem
You might be using model which is not loaded.
There might be some code problem in the model.
You may not be returning anything from your model and echo it.
Also if you need the data back use echo json_encode($data)

Sometimes this problem arises when you have loaded the site as https://example.com but the url in your ajax call is http://example.com .

Managed to find the solution. The problem was due to CI_TOKEN which is sent with the FORM. That was absent and due to which POST method was giving 500 Internal server Error. I added following in my view file.
<?php echo form_open_multipart(); ?>
<?php echo form_close(); ?>
and sent ci_token with the ajax post request.
var ci_token = formObj.find('input[name=ci_token]').val();
var qty = 1;
var dataString = 'product_id='+ id + '&quantity=' + qty + '&ajax=' + 1
+'&ci_token=' + ci_token;
This solved the problem. I am not sure but this is called CSRF related some problem
Thanks

you have used _remap function and after getting $uri2 there is an if check which is checking the quantity variable you have passed in your ajax request and it may have integer value as obvious may contain some integer.
there for
$this->uri->segment();
returns you:
product_id=id
quantity=qty
ajax=1
and you take value 2 that is quantity by calling
$uri2 = $this->uri->segment(2);
it will return quantity to you and you have not defined an index() function in your code which gives 500 error
function _remap()
{
$uri2 = $this->uri->segment(2);
if (is_numeric($uri2) OR $uri2 == FALSE) {
$this->index();
} else if ($uri2 == 'add_cart_item') {
$this->add_cart_item();
} else if ($uri2 == 'show_cart') {
$this->show_cart();
}
}

Related

Ajax POST, check PHP $_GET and then $_POST

Using the following Ajax POST function on form submit (simplified here):
$form.on("submit", function (i) {
i.preventDefault();
var sendEmail = 1;
ValidateForm(sendEmail, "goSignup");
});
function ValidateForm(sendEmail, action) {
$.ajax({
type: "POST",
url: window.location.pathname,
dataType: "json",
data: {
ajaxRequest: 1,
sendEmail: sendEmail,
}
}
After I post this I want to use a conditional GET parameter that equals 1 (i.e https://www.example.com?test-parameter=1) and then if it's present in the URL use one or another function from there if the ajaxRequest is received from $_POST in my PHP:
public function __construct() {
$testingParameter = $_GET["test-parameter"] ?? '';
if (trim($testingParameter) == '1') { // if has get parameter equal
if (!empty($_POST['ajaxRequest'])) { // if JS postRequest has been posted
$this->handlePostRequests();
}
echo 'has get parameter';
} else { // else use old logic
if (!empty($_POST['ajaxRequest'])) {
$this->handleOtherRequests();
}
echo 'no get parameter';
}
}
Issue:
I get the correct echo from PHP but when I submit the form with Ajax its still using the handleOtherRequests(); instead of the handlePostRequests(); function if I'm using the url www.example.com?test-parameter=1.
Likely getting some basic PHP logic wrong here, would appreciate if anyone could guide me in the right direction with this.
url: window.location.pathname,
Your Ajax is never going to POST the data to a URL with a query string because you explicitly took only the path name.
Maybe you want location.href instead.

Using Ajax to call a Yii2 function on button click

After trying some possible solutions that I found through internet/other questions here, I can't seem to find the problem with my code. What I need is that, after clicking a button in my view, an action in my Yii2 controller gets called through Ajax and performs some action. However, with my current code, after clicking the button nothing seems to happen.
The relevant code is as follows...
The view:
(...)
Html::button('Eliminar', ['data-confirm' => '¿Eliminar enunciado?', 'onclick' => '
$.ajax({
type: "POST",
url: "/evaluacion/eliminar-enunciado",
data: {
id: '.$enunciado->id.'
}, success: function(result) {
if(result == 1) {
$.pjax.reload({container: "#construccion-evaluacion"});
} else {
}
}, error: function(result) {
console.log(\"server error\");
}
});
'])
(...)
The controller:
(...)
public function actionEliminarEnunciado($id)
{
Enunciado::findOne($id)->delete();
if(Enunciado::findOne($id) != null) {
echo 1;
} else {
echo 0;
}
}
(...)
Some considerations for clarification:
- The controller file is called EvaluacionController.php.
- The $enunciado->id variable is properly defined and has a valid value.
Any advice will be appreciated. Thanks for your time!
You need get value of POST request;
if(isset($_POST['id']))
$id = $_POST['id'];

How to send/return data/value from CI_Controller to AJAX

As the title, i want to CI_Controller return value/data back to AJAX which give request before.
The_Controller.php
class The_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
function postSomething()
{
$isHungry = true;
if(isHunry){
return true;
}else{
return false;
}
}
}
AJAX
$(document).ready(function()
{
$('#form').on('submit', function (e)
{
e.preventDefault(); // prevent page reload
$.ajax ({
type : 'POST', // hide URL
url : '/index.php/The_Controller/postSomething',
data : $('#form').serialize (),
success : function (data)
{
if(data == true)
{
alert ('He is hungry');
}
else
{
alert ('He is not hungry');
}
}
, error: function(xhr, status, error)
{
alert(status+" "+error);
}
});
e.preventDefault();
return true;
});
});
The Problem :
The AJAX code above always get FALSE for variable data. It's not get return value from postSomething function inside CI_Controller.
The Question :
I want to if(data == true) result alert ('He is hungry');. But cause data not fill by return value of postSomething function inside CI_Controller so it always false. How to get return value/data from CI_Controller to AJAX?
Thank you
you need to change your code a little bit. no need to return data, just echo true or echo false from your controller. Hope you will get your desired result.
You have a typo in the PHP code
if(isHunry){
should be
if($isHungry){
Also, returning data to an AJAX request, you really should be sending the correct content type in the header. Ex.
header('Content-Type: application/json');
And print or echo the data, not return it, as well as json_encode it:
echo json_encode($data);
So your postSomething php function should look something like this:
$isHungry = true;
header('Content-Type: application/json');
echo json_encode($isHungry);

CodeIgniter + jQuery Ajax runs successfully but error callback is called

I have a pretty simple CodeIgniter project that does some simple database work. Currently I have a controller method that deletes an item in the database. In my view, the code uses the jQuery ajax object to reference that controller, then displays either success or failure through its callbacks.
The problem is, although the controller works fine (deletes the item in the DB as expected), the ajax "error" callback is being called, instead of "success".
I'm sure I'm missing something super basic here...
Here is my controller method:
public function delete_note()
{
$this->load->helper('url');
$this->load->model('auth/user', 'User');
$this->load->database();
$note_id = $this->input->post('id');
$this->db->delete('admin_notes', array('id' => $note_id));
$this->db->query();
$this->output->set_status_header('200'); // Attempting to force the issue
}
And here is the code within the view:
$('.delete_note').each(function(){
var current = this;
this.onclick = function(event)
{
var note_id = this.title;
$.ajax({
type: "POST",
url: "/admin/delete_note",
data: { id: note_id },
success: function(data) { alert('I never see this!');},
error: function () { alert('I *always* see this!');}
});
}
});
Any answer attempts are appreciated. Any correct answers are doubly appreciated ;)
Thanks!
Just because the database logic is working, you may be receiving issues related to something else (cross-browser perhaps?). To see the error, change your error function to be like this:
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
I'd like to thank WojtekT for reminding me to check my responses in Firebug. I was actually receiving back a 500 status code for PHP errors. My extraneous $this->db->query(); call needed to be removed.
Everything works great now.
Thanks!

Ajax request sent fine but i didnt get the response

I make an AJAX request like this
$.ajax({ type: "POST",url: "<?php echo site_url('home/view_most'); ?>",async: true,data: "view=most_booked", success: function(data)
{
if(data != 0)
{
$("#view_most").html(data);
}
else
alert("Error");
}
});
In controller i get through
public function view_most()
{
$view_most = $this->input->post("view");
}
The response that ajax request is what server echoes so you must echo some value to get the response and handle the response in your success function. In your case does not echo anything thats why you are not getting any response. For example:
public function view_most()
{
$view_most = $this->input->post("view");
echo '0';
}
Try this and you will get 0 as response.
not too familiar with the php codeigniter platform but I think you are not returning any data and that is why you dont see any data.. I am guessing you need to do something like the following at the end of your action code.
$this->load->view(viewName);
Thus your action code should be
public function view_most()
{
$view_most = $this->input->post("view");
$this->load->view($view_most);
}
Here is a quick introduction of AJAX on codeigniter: http://mrforbes.com/blog/2009/01/a-quick-code-igniter-and-jquery-ajax-tutorial/

Categories