Javascript connection to the bank does not work

1

Hello, I'm trying to connect to the MySQL database with a Phonegap / Cordova project and I'm trying to troubleshoot. First I created the Cordova project and the only change I made was to import JQuery. So I followed a tutorial to make an ajax call from a php file that should insert the data in the database, all in the rough, but it still does not work. Someone, please help me!

index.html

<!DOCTYPE html>

             https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src * ">                                             Hello world          

    <form id="formUsuario">
        <input id="nomeUsuario" type="text" placeholder="Nome"></input> <br>
        <input id="sobrenomeUsuario" type="text" placeholder="Sobrenome"></input> <br>
        <input id="idadeUsuario" type="text" placeholder="Idade"></input> <br>

        <button id="enviar" type="submit" onclick="salvar()">Enviar</button>
    </form>

    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
    <script type="text/javascript" src="js/jquery-3.1.0.min.js"></script>
    <script type="text/javascript">
        function salvar(){
            alert('Botão salvar clicado!');

            var formula = $('#formUsuario').serialize();

            $.ajax({
                type: 'POST',
                dados: formula,
                url: 'http://localhost/projetos/wstest/cadastrar.php',
                success: function(data){
                    if (data == 0) {
                        alert('Erro ao se comunicar com o banco de dados!');
                        window.location = "";
                    }
                    else if (data == 1) {
                        alert('Registro salvo com sucesso!');
                    }
                    else{
                        alert('Algo de errado aconteceu!');
                    }
                }
            });
        }
    </script>
</body>

index.js

var app = {
// Application Constructor
initialize: function() {
    this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
    document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
    app.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
    var parentElement = document.getElementById(id);
    var listeningElement = parentElement.querySelector('.listening');
    var receivedElement = parentElement.querySelector('.received');

    listeningElement.setAttribute('style', 'display:none;');
    receivedElement.setAttribute('style', 'display:block;');

    console.log('Received Event: ' + id);
}
};

    app.initialize();

connection.php

    <?php

    //Conecta ao banco de dados usando MySQLi
    function conectar()
    {
        try
        {
            //Localhost
            $host = "localhost";
            $user = "root";
            $password = "";
            $database = "webservice";

            $conn = mysqli_connect($host, $user, $password, $database);
//            mysqli_autocommit($conn, FALSE);
            echo 'Conexão bem sucedida!';

        } catch (Exception $ex) {
            die("Erro de conexão: " . mysqli_connect_error());
        }

        return $conn;
    }

cadastrar.php

<?php

include './conexao.php';

header("Access-Control-Allow-Origin: *");

$link = conectar();

$nome       = mysqli_real_escape_string($_REQUEST['nomeUsuario']);
$sobrenome  = mysqli_real_escape_string($_REQUEST['sobrenomeUsuario']);
$idade      = mysqli_real_escape_string($_REQUEST['idadeUsuario']);

$query = "INSERT INTO 'usuario'('nome', 'sobrenome', 'idade') "
        ."VALUES ('$nome','$sobrenome','$idade')";

$res = mysqli_query($link, $query);

if($res == true){
    $resultado = 1;
}else{
    $resultado = 0;
}

echo (json_encode($resultado));

I run this in the browser using Ripple and it does not work. Nor the error alert I get. Much less debugging on the phone. If anyone can help me thank you immensely.

    
asked by anonymous 27.09.2016 / 15:46

2 answers

1

In the procedural style of MySQL, almost all functions call the connection argument as the first argument, mysqli_real_escape_string () is not the exception.

Change and the other lines of:

$nome       = mysqli_real_escape_string($_REQUEST['nomeUsuario']);

To:

$nome       = mysqli_real_escape_string($link, $_REQUEST['nomeUsuario']);
    
27.09.2016 / 15:53
0

I was getting the following error in the console:

  

Security Policy directive: "default-src 'self' data: gap: ssl.gstatic.com 'unsafe-eval'". Either the 'unsafe-inline' keyword, the hash ('sha256-vEvqxevWs9eHGtUlhoHXpL4h80s + E4s8 / 84jnjsED6E ='), or a nonce ('nonce -...') is required to enable inline execution. Note also that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.

It seems that this error happens because of a javascript code structuring policy that is defined by the following html tag:

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">

When removing the tag, JQuery started working.

    
27.09.2016 / 17:01