How do I receive and submit data without refreshing the page?

Asked

Viewed 429 times

0

Good, I’m creating a notification system in my app where I want to retrieve data from the database and inform the user accordingly through notifications. I happen to be a little lost in how do I update notifications without me requesting a form or something like that.

Can someone give me some 'lights' on how I should proceed? I’m a little lost

UPDATE: I’m trying to use AJAX to do it and I’m trying the following code but nothing happens:

$.ajax({
        url: '<?=base_url("notificacoes")?>',
        type: 'POST',
        data: {
            key: 'olá'
        },
        dataType: 'json',
        success: function(data) {
            console.log(data);
        }
    });

Controller:

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

class Notificacoes extends CI_Controller {
    public function index(){
        echo $this->input->post('key');
    }
}

The idea is to print the key variable when the page loads

  • 3

    Use and study a little about ajax requests

  • I already started to see some ajax, however, I got a doubt and updated the post. If you can help me thank

  • Served, just arose me a new doubt that is connected with the answer they gave me and, not to be creating another post, I reissued this

  • Your ajax function is not being called!

2 answers

1


In principle in the protocol HTTP the client makes the request and the server responds, so somehow you have to make a request. But there are some solutions, such as:

  • Ajax - Ajax allows you to communicate with the server without having to refresh the page and for that you would have to request x in x time, but that would flood your server of requests which is not a good implementation.
  • React- With React you can choose what to update in Dom via reactive components that allows you to interact with elements Specific HTML. And codeIgniter already has a package (Codeigniter with React) that allows you to use React.

I hope I’ve helped.

  • I already started to see some ajax, however, I got a doubt and updated the post. If you can help me thank

  • Nothing happens because maybe Ajax is not called. Try putting Ajax inside the window.onload(()=>{ $.ajax({&#xA; url: '<?=base_url("notificacoes")?>',&#xA; type: 'POST',&#xA; data: {&#xA; key: 'olá'&#xA; },&#xA; dataType: 'json',&#xA; success: function(data) {&#xA; console.log(data);&#xA; }&#xA; }); })

0

To be clear: This is not a tutorial. You need to be familiar with the framework methodology.

The code proposed in this answer basically makes a request $_POST pro method json/index passing the data of form and treats the answer to show everything in one alert. OBS: where you said you don’t want to wear a form, you’ll have to make the request one way or another, so I used a form to organize the data. Deepening further in JQuery you will learn to extract the data from any type of element to send.

Considering the structure of CodeIgniter in the documentation, I suggest creating a Controller responsible only for the responses of objects JSON. It will serve for any type of data that you want to recover, including database data:

Controller 'Json.php':

<?php

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

class Json extends CI_Controller {

    /**
    * Returns a JSON object
    **/
    function index() {
        $alert = $this->input->post();
        $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode($alert));
    }
}

Created the controller that will respond with the objects JSON, create the ones that will use them:

Controller 'Pages.php':

<?php

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

class Pages extends CI_Controller {

    public function index() {
        $this->load->view('pages/index');
    }
}

View 'pages/index:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
        <title>Example</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
        <script>
            $(function () {
                //Comportamento do botao de envio
                $('#submit').click(function () {
                    submit();
                });
                //Alteracao do comportamento do formulario de envio
                $("#form").submit(function (e) {
                    e.preventDefault();
                });
            });
            //Funcao que faz o request
            function submit() {
                //Envia um request POST para o method 'json/index';
                $.post(
                    $("#form").attr("action"),//Captura a action do FORM
                    $("#form").serialize(),//Captura os dados do FORM
                    //Captura a resposta do PHP
                    function (resp) {
                        //Alterando os valores em elementos especificos
                        $('#alert-msg').html('Classe invocada: '+resp.class);
                        $('#alert-title').html('Mostrando a classe para o elemento #alert');
                        //Muda a classe do elemento #alert
                        $("#alert").attr('class', resp.class);
                    }
                );              
                //Mostra o elemento #alert
                $('#alert').css('display', 'block');
            }
        </script>
        <style type="text/css"> 
            /* Por padrao, oculta elementos com id = 'alert' */
            #alert{
                display:none;
            }
        </style>
    </head>
    <body>
        <nav class="navbar"></nav>
        <div class="container">
            <p><b>Altere a classe do elemento #alert:</b></p>
            <div id="alert" role="alert">
                <strong id="alert-title">
                </strong> <div id="alert-msg"></div>
            </div>
            <div class="col-lg-3">
                <form action="json/index" id="form">
                    <select class="form-control" name="class">
                        <option value="alert alert-success">Success</option>
                        <option value="alert alert-info">Info</option>
                        <option value="alert alert-warning">Warning</option>
                        <option value="alert alert-danger">Danger</option>
                    </select>
                    <br>
                    <button class="btn btn-primary" type="button" id="submit">Alterar</button>
                </form>
            </div>
        </div>
    </body>
</html>

Observing the code in the view you will realize that what matters, in this case, is the JavaScript/JQuery. He’ll be handling the behavior of form, and the response obtained from method json/index and change the data shown.

The code is commented, and should not be difficult to implement or change to suit your needs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.