jQuery, AJAX and Codeigniter - form submit does not work - ajax

I'm new to all this AJAX thing so I thought that good learning will be to build simple TODO list. Below is index.php and corresponding controller. Index gets loaded without errors, but when I submit my task nothing is happening. Only page gets reloaded. Database is still empty.
index.php
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<h1>Todo</h1>
<form id="add" >
<input type="input" name="task" />
<input type="submit" value="Add" /><br />
</form>
<script>
$("form").submit(function() {
var value = $("input:first").val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>todo/add/" + $("input:first").val(),
dataType: 'text',
success: function()
{
var newP = $('<p />').text(value);
$(".todos").append(newP).fadeIn(1000);
}
});
return true;
});
</script>
<div class="todos"></div>
<p>ZaƂadowano w <strong>{elapsed_time}</strong></p>
</body>
controller/todo.php
<?php
class Todo extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('todo_model');
}
public function index($type = NULL)
{
$this->load->view('todo/index');
}
public function add($data)
{
$this->Todo_model->add($this->input->xss_clean($data));
}
}
?>
Update:
todo_model.php:
<?php
class Todo_model extends CI_Model {
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function add($data)
{
$this->db->insert('todo', $data);
}
public function get()
{
return $this->db->get('todo')->result();
}
}
?>

Try using this:
public function add($data)
{
$this->Todo_model->add($data);
}
instead of:
public function add($data)
{
$this->Todo_model->add($this->input->xss_clean($data));
}
UPDATE:
JAVASCRIPT:
$.ajax({
method: 'POST',
url: '<?php echo base_url(); ?>todo/add/',
data: 'data=' + $("input:first").val(),
success: function(resp) {
//rest processing
}
});
CONTROLLER:
public function add()
{
$this->Todo_model->add($this->input->post('data'));
}

You'll need to use a debugger like Firebug console to see what the reply of the server is to your request.
In your script section
$(function(){}
is missing, which should be wrapped around your jQuery
use something like this to stop the form from submitting:
if (evt.preventDefault()) {
evt.preventDefault();
}else{
evt.returnValue = false;
}

Try this one then debug with firebug by clicking on firebug icon then clicking on Console to see what you submit and how the response is
var id = 1;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>todo/add/",
data: {id : id},
success: function()
{
var newP = $('<p />').text(value);
$(".todos").append(newP).fadeIn(1000);
}
});

Related

Prestashop 1.7.6.2 ajax call backoffice module

I have problem with ajax from select2 in prestashop 1.7. When I try writte something the calling is 200 but I got error "The Controller Psb2BAjaxModuleAdmin is missing or invalid."
I create Controller for test in my module
modules/psb2b/src/Controller/Psb2BAjaxModuleAdminController.php
<?php
namespace Scenario\PSB2B\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
class Psb2BAjaxModuleAdminController extends FrameworkBundleAdminController
{
public function __construct()
{
parent::__construct();
}
public function initContent()
{
parent::initContent();
return $this->ajaxDie(json_encode("test"));
}
public function postProcess()
{
PrestaShopLogger::addLog("MODULE CONTROLLER OK ", 1);
}
public function displayAjax()
{
$usb_search_token = $this->generateUrl("psb2bAjaxAdmin");
return $this->ajaxDie(json_encode("test"));
}
}
and in admin directory admin*********/themes/default/js
$(document).ready(function(){
$('#category_features').select2({
width: 'resolve',
ajax: {
type: 'POST',
url: usb_search_token,
dataType:'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
success: function (result) {
console.log(result);
}
} });
});
In my module i used hook
public function hookActionAdminControllerSetMedia()
{
MediaCore::addJsDefL('usb_search_token', $this->context->link->getAdminLink('Psb2BAjaxModuleAdmin'));
$this->context->controller->addCSS(_PS_BO_ALL_THEMES_DIR_ . 'default/js/select2-full/dist/css/select2.min.css','all');
$this->context->controller->addJS(_PS_BO_ALL_THEMES_DIR_ . 'default/js/select2-full/dist/js/select2.min.js');
$this->context->controller->addJS(_PS_BO_ALL_THEMES_DIR_ . 'default/js/tree.js');
}
It seems your controller looks more like a 1.6+ one rather than a 1.7 with Symfony one.
I usually have an indexAction method in the controllers/Admin/my_controller.php.
In this method I use a
Media::addJsDef(array(
'usb_search_token' => admin_link));
));
Then as this method returns a
return $this->render('#Modules/rmvcolorgrid/views/admin/my_file.html.twig', [])
the URL is available for the js file in views/js/back.js.
You should have a look at PS docs for the recommended way to build this.

paypal_lib form not working in codeigniter

I have loaded the paypal library in my controller and written the code as well for paypal integration.
class Register extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->library('session');
$this->load->library('email');
$this->load->helper('url');
$this->load->library('paypal_lib');
}
public function signup()
{
$this->paypal_lib->add_field('return', $returnURL);
$this->paypal_lib->add_field('rm','2');
$this->paypal_lib->add_field('cancel_return', $cancelURL);
$this->paypal_lib->add_field('notify_url', $notifyURL);
$this->paypal_lib->add_field('item_number', $pkgid);
$this->paypal_lib->paypal_auto_form();
}
}
On my template file:
jQuery.ajax({
url : '<?php echo $base_url; ?>register/signup',
type: 'POST',
data: jQuery(form).serialize(),
success:function(response){
console.log(response);
}
});
I could not move to paypal website store. still on same page without any redirection. How to solve this?
Finally i analyzed the issue. we shouldn't use paypal_lib on ajax. because of codeigniter ignoring the redirect concept on ajax.
You don't return anything. Change your function "signup" to this:
class Register extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->library('session');
$this->load->library('email');
$this->load->helper('url');
$this->load->library('paypal_lib');
}
public function signup()
{
$this->paypal_lib->add_field('return', $returnURL);
$this->paypal_lib->add_field('rm','2');
$this->paypal_lib->add_field('cancel_return', $cancelURL);
$this->paypal_lib->add_field('notify_url', $notifyURL);
$this->paypal_lib->add_field('item_number', $pkgid);
echo json_encode($this->paypal_lib->paypal_auto_form(), JSON_UNESCAPED_UNICODE);
}
}
And better in your JS code change your dataType to JSON:
jQuery.ajax({
url : '<?php echo base_url(); ?>index.php/register/signup',
type: 'POST',
dataType: "JSON",
data: jQuery(form).serialize(),
success:function(response){
console.log(response);
}
});

Is it possible to post from custom js to .module/custom.php/controller file and get response in custom js while developing custom module in drupal8?

i have this in custom.js file in drupal modules/mymodule/js/ folder
(function ($) {
Drupal.behaviors.coorrency = {
attach: function (context, settings) {
jQuery.ajax({
url: 'modules/mymodule/custom.php',
type: "POST",
success: function(data){
console.log(data);
}
});
}
}
})(jQuery);
and i have to post to modules/mymodule/custom.php
<?php
echo "test";
?>
and return data from custom.php
You can do that by creating a controller for listening that ajax call
my_module.routing.yml
my_module.call_back:
path: '/my_module/call_back'
defaults:
_controller: '\Drupal\my_module\Controller\DefaultController::callBack'
_title: 'Call Back'
Controller
<?php
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
/**
* Class DefaultController.
*/
class DefaultController extends ControllerBase {
/**
* Your Callback
*
*/
public function callBack() {
return ["This is a test" ];
}
custom.js
(function ($) {
Drupal.behaviors.coorrency = {
attach: function (context, settings) {
jQuery.ajax({
url: '/my_module/call_back',
type: "POST",
success: function(data){
console.log(data);
}
});
}
}
})(jQuery);

Ajax calling Area Controller

I am trying to call a Controller from Ajax, but I'm getting:
Failed to load resource: the server responded with a status of 404 ()
The Ajax is calling from the Admin View to the Admin Controller. I can view the Admin Page, but I'm unable to call GetAll() and GetAllUsers() from Ajax or any other method.
In Startup
app.UseMvc(routes =>
{
routes.MapRoute("areaRoute",template:"{area:exists}/{controller=Admin}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
In AdminController
namespace Project.Areas.Admin.Controllers
{
[Area("Admin")]
[Authorize(Policy = "AdminOnly")]
public class AdminController : Controller
{
public IActionResult Index()
{
return View();
}
public AdminController()
{
}
[HttpGet("GetAll/{page}")]
public IActionResult GetAll(int? page)
{
}
[HttpGet("GetAllUsers/{page}")]
public IActionResult GetAllUsers(int? page)
{
}
}
}
Ajax:
#section Scripts{
#await Html.PartialAsync("_ValidationScriptsPartial")
<script>
$(function () {
$.ajax({
type: "GET",
url: "/Admin/GetAll",
traditional: true,
success: function (view) {
$("Result").html(view)
}
});
$.ajax({
type: "GET",
url: "/Admin/GetAllUsers",
traditional: true,
success: function (view) {
$("userResult").html(view)
}
});
});
</script>
}
in the url you need to user /{areaName}/{controllerName}/{ActionMethod}
$.ajax({
type: "GET",
url: "/Admin/Admin/GetAllUsers",
traditional: true,
success: function (view) {
$("userResult").html(view)
}
});

Codeigniter AutoComplete Stop working when i put the code under login conditions

The Code Runs Fine when i run the code without login Conditions, When i put code under login condition it gets stop. if a login into application even that time code is not under login conditions but the search gets stop until i restart my computer
My Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class autocomplete extends CI_Controller {
public function __construct(){
parent::__construct();
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
}
else
{
redirect('login', 'refresh');
}
}
public function index(){
$this->load->view('view_demo');
}
public function start()
{
$json = [];
$this->load->database();
if(!empty($this->input->get("q"))){
$this->db->like('name', $this->input->get("q"));
$query = $this->db->select('drugs_id as id,name as text')
->limit(10)
->get("drugs");
$json = $query->result();
}
echo json_encode($json);
}
}
Here is My View
<div style="width:520px;margin:0px auto;margin-top:30px;height:500px;">
<h2>Select Box with Search Option Jquery Select2.js</h2>
<select class="itemName form-control" style="width:500px" name="itemName">
</select>
</div>
Here is Script
$('.itemName').select2({
placeholder: '--- Select Item ---',
ajax: {
url: 'http://localhost/dcms/autocomplete/start',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});

Resources