Ajax with codeigniter

0

I am trying to perform a function that sends data in a php file with ajax with the following code:

function buscar(){
var texto = $("#search").val(); 
var pagina = $("#pagina").val(); 

var datos_formulario = "texto="+texto+"&pagina="+pagina;
 console.log(datos_formulario);

$.ajax({
    type: 'POST',
    url: 'http://localhost/prestamos-2017/backend/includes/buscar',
    data: datos_formulario,
    dataType: 'json',
    beforeSend: function (objeto) {

    },
    success: function (json) {
        console.log(json)
       //$('.lista').html(json.registros);
        //$(".btp").on("click", function(){
          //  $( "#tareaInput" ).focus();
        //});
        //tarea_completa(fecha_actual);
        //color();


    },
    error: function (e) {
          console.log('No se puede conectar al servidor');
    },
    complete: function (objeto, exito, error) {

    }
});

}

But it gives an error in the console that says:

  

POST link 403 (Forbidden)

In my file routes.php of codeigniter I have the following line:

$route['backend/includes/buscar'] = 'includes/buscar';

Controller:

<?php defined('BASEPATH') OR exit('No direct script access allowed');

   class Buscar extends CI_Controller {

        var $data;
        var $current_user_id;

        function __construct(){
             parent::__construct();
             $this->data->item_slug = 'motherform';
             $this->data->text_item = 'formulario';
             $this->data->text_items = 'formularios';
             $this->data->text_gender = 'f';
        }

        function buscar() {
             $this->load->view('backend/includes/buscar.php');   
        }
    } ?>
    
asked by Cesar 17.04.2018 в 16:50
source

2 answers

0

Review this way to make the request:

$.ajax({
                            // cargamos url a nuestro contralador y método indicado
                            url:"<?php echo site_url();?>/backend/includes/buscar",
                            type:"post",
                            success:function(data){
                                if(data){
                                    alert(data)
                                }
                                else{
                                    alert("error")
                                }
                            }
                        })

And remember that from the controller we are sending json type data for the view. Try removing $this->load->view('backend/includes/buscar.php'); of the find function from the controller and put this echo json_encode(array(‘mensaje’=> 'Hola Mundo')); to pass a view to the view and show it with an alert in the view within the success to see if you still get the error:

    
answered by 17.04.2018 в 17:15
0

Check this link: link In the gives a detailed explanation of the use of ajax with codeigniter

    
answered by 17.04.2018 в 17:23