Nothing happens when calling . php file via Ajax call in pure Javascript

Asked

Viewed 200 times

0

I am creating Mysql server persistence for a web application of mine.

For this I am using the xampp and phpmyadmin. I created a database in phpMyAdmin and in my application, in a javascript I have an Ajax request for a file. php that makes this communication with the server.

What happens is, the Ajaxcall function in my . js is called, but the Php file passed to it with an action is simply ignored. Nothing happens with php. I put Words in . php and nothing appears. I put syntax errors and the browser did not even accuse. It means . php is not being accessed... Only I don’t know why.

My Js:

function abreConta(){
    var cpf = document.getElementById('cpf').value;
    var agencia = document.getElementById('agencia').value;
    var conta = document.getElementById('conta').value;

    //As variáveis acima são preenchidas corretamente.

    parms = "&cpf"+cpf+"&agencia"+agencia+"&conta"+conta;
    ajaxCall("Persistencia.php?action=abreConta" +parms, mudaView);


}

function mudaView(listaParams){
    window.alert("Sua conta foi aberta com sucesso. Você será redirecionado ao menu inicial");
    mudaMenu("formularioDeAbertura", "menu1");
}


function ajaxCall(stringCall, callback){
    var httpRequest = new XMLHttpRequest;

    httpRequest.onreadystatechange = function(){
    if (httpRequest.readyState === 4) {
        if (httpRequest.status === 200) {
            console.log("Requisicao http em curso");
          callback(httpRequest.responseText);
        }
    }
    };
    httpRequest.open('GET', stringCall);
    httpRequest.send();
}

The folder of my application:

inserir a descrição da imagem aqui

My Persistencia.php:

<?php

function conectaDB(){
    $con  =  mysqli_connect("localhost","root","","onbank");

    if(!$con){
        echo "<h2>Erro na conexao com a base dados...</h2>"; 
        echo "<h2> Erro " . mysqli_connect_errno() . ".</h2>";
        die();
    }
    $con->set_charset("utf8");
    return $con;
}


    if(@$_REQUEST['action'] == "abreConta")     //recupera lista de nomes das cidades
    {

        con = ConectaDB();
        $cpf = $con->real_escape_string($REQUEST['cpf']);
        $agencia = $con->real_escape_string($REQUEST['agencia']);
        $conta = $con->real_escape_string($REQUEST['conta']);

        mysqli_query($con,"INSERT INTO contas (agencia,conta,dono) VALUES('$agencia','$conta', '$cpf');");]
        $con->close();

        //abreConta();
    }


    if(@_REQUEST['action'] == 'buscaContasCliente')
    {
        $cpf = buscaCpf();
        inicializaListaContas($cpf);

    }

    function buscaCpf(){
        $con = ConectaDB();
        $nome = $con->real_escape_string($REQUEST['nome']);

        $result = mysqli_query($con, "SELECT cpf FROM clientes WHERE nome='$nome';");
        return $result;
    }

?>

My database in phpMyAdmin: Not being changed, due to Persistencia.php not running.

inserir a descrição da imagem aqui

Note: the balance column has automatic filling with 0.

In the Network tab of F12 the following appears when I open an account: inserir a descrição da imagem aqui

  • why the tag phpmyadmin? What has to do with the problem?

  • 1

    You’re showing it on the console: console.log("Requisicao http em curso");?

  • Yes, it shows

  • @Guilhermecostamilam tag phpMyAdmin? Where? phpmyadmin is where the mysql server I am using

  • The database server is not in phpmyadmin, it is an interface that you use to access the bd. Use the phpmyadmin tag when the problem is related to it and not why you use it to check whether something worked or not

2 answers

1


You have checked what is appearing on the broswer network? to check just click on F12 and check the network tab. Then perform the ajax request. A new field should appear, it will probably show the error in the PHP code.

Or you can also access directly from the broswer and check if there are any errors. In this case your: http://localhost/Persistencia.php? action=abreConta. Errors that are being returned should appear better.

I also recommend changing the form of the request, today in javascript we use a more simplified way to do Ajax on the javascript side, see an example:

<script>

function abreConta(){

    let cpf = "cpf qualquer";
    let agencia = "agencia qualuqer";
    let conta = "conta qualquer";

    let params = "?cpf=" + cpf + "&agencia=" + agencia + "&conta=" + conta;

    ajaxCall(params, function(result) {
        console.log(result);
    });

}

function ajaxCall(params, callback){
    // Faz a requisicao HTTP para o servidor PHP
    fetch("ajax.php" + params)
        .then((response) => {
            alert("-- sucesso --");
        }).catch(() => alert("error"));
}

abreConta();

</script>

Este é o PHP que está testando esse Javascript, fiz só como demostração:

<?php
$dados = [$_GET["cpf"], $_GET["conta"], $_GET["agencia"]];
echo json_encode($dados);

When you find out which error you’re making in PHP you can update the question if you can’t solve it.

  • I found: In the "Response" option of the Network points the error: Parse error: syntax error, Unexpected ']' in C: xampp htdocs Appga Persistencia.php on line 24

  • I managed to do the communication!! lol ; only that the account was added in the table with all zeroed parameters...

  • Now it returns no error in Sponse. I will debug with Snippets to check where the parameters are not coming.

  • It was only on the first try, now Mysql is filling the tables with all values. Thank you!!

1

The error is on this line:

parms = "&cpf"+cpf+"&agencia"+agencia+"&conta"+conta;

The signs of equals are missing = in the parameters:

             ↓               ↓                 ↓
parms = "&cpf="+cpf+"&agencia="+agencia+"&conta="+conta;

Without the =, PHP is not receiving the values.

  • Ah, I get it. But I fixed it and it didn’t help. It didn’t change anything :(

  • But it’s showing the console.log in the Ajax response?

  • 1

    Place console.log(httpRequest.responseText); to see what returns.

  • 1

    Ever tried to put a echo "qualquer coisa"; at the end of PHP, before the ?>?

Browser other questions tagged

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