Javascript connection to the database does not work

Asked

Viewed 180 times

1

Hello, I am trying to connect to Mysql database with a Phonegap/Cordova project and am experiencing problems. First I created the Cordova project and the only change I made was importing Jquery. Then I followed a tutorial to make an ajax call of a php file that should insert the data in the database, all roughly but still does not work. Somebody 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();

php connection.

    <?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;
    }

register.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 doesn’t work. Neither does error Alert I get. Let alone debugging on phone. If anyone can help me, I’d really appreciate it.

  • 1

    In mysqli_real_escape_string need to pass the connection as first argument, if the problem is php, test it isolated.

  • 1

    Note that you have an error sending js, dados: 'formula',, must be data: formula,

  • I’ve corrected that part, thank you.

  • 1

    @Guillermo You set with dados or data? remember that you are English.

2 answers

1

In the procedural style of Mysqli almost all functions ask as the first argument the connection, 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']);
  • @Guilhermeramalho vc can run this page by browser (desktop)? see the javascript error console there must be some clue.

  • I’m getting the following console error: GET http://localhost/projects/Cordova/testapp/www/Cordova.js 404 (Not Found)

  • @Guilhermeramalho if u put the relative url works? in place of localhost/projetos ... / demais pastas as ../php/arquivo.php

0

I was getting the following error on 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.

Apparently this error happens due to a Code structuring policy javascript which 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 *">

Removing the Jquery tag now works.

Browser other questions tagged

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