Problem with ajax and cURL to receive mysql value and return to html

0

people I'm having a problem using html, ajax, cURL and mysql. the function is simple an html page where will receive a name and will send by ajax to cURL that will access the php that connects to mysql and takes 2 column of the table and returns the value for a table created in html.

html code

    <!DOCTYPE html>
    <html lang="pt-br">
     <head>
    <meta charset="UTF-8"/>
    <title>
    CONSULTA DE CLIENTE
    </title>
    </head>
      body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script><formaction="" id="form1" method="post" name="busca" enctype="multipart/form-data" >
  <input type="text" name="txt_nome" id="nome"/>
  <input type="submit" name="seach" value="BUSCAR" />
</form>
<div class="response">
</div>
<script type="text/javascript">
  $(function(){
      $('#form1').submit(function(e){
          var nome = $('#nome').val();
          e.preventDefault();
          $.ajax({
              url: 'clientes_curl.php',
              type: 'POST',
              datatype: 'JSON',
              data: {
                cliente_nome:$('#nome').val()
              },
              success: function(data){
                alert(data.cliente_nome);
                var html='<table border="1">';
                html+='<thead>';
                html+='<tr>';
                html+='<th>NOME</th>';
                html+='<th>CATEGORIA</th>';
                html+='</tr>';
                html+='</thead>';
                html+='<tbody>';
                html+='<tr>';
                html+='<td>'+data.cliente_nome+'</td>';
                html+='<td>'+data.cat_name+'</td>';
                html+='</tr>';
                html+='</tbody>';
                html+='</table>';
                $('.response').html(html);
              }
            });
        });
    });
</script>

curl code in php

     <?php
    $cURL = curl_init('clientes_db.php');
    $nome = $_POST['cliente_nome'];
    echo $nome;
    curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
    curl_exec($cURL);
    $post = array(
      'cliente_nome'=> $nome
    );
    curl_setopt($cURL, CURLOPT_POST, true);
    curl_setopt($cURL, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($cURL, CURLOPT_POSTFIELDS, $post);
    $resultado = curl_exec($cURL);
    curl_close($cURL);
    ?>

code that accesses the bank in php

    <?php

    $nome = $_POST['cliente_nome'];

    class clientes_db
    {
      public function __construct()
      {
        mysql_connect('localhost','Admin','admin');
        mysql_select_db('avaliacao');
      }

      public function getClientes($nome)
      {
    $select = mysql_query("SELECT * FROM tbl_clientes WHERE cli_nome = '$nome'");
    while ($row = mysql_fetch_array($select)) {
    $i = 0;
    foreach ($row as $key => $value) {
    if (is_string($key))
    $fields[mysql_field_name($select, $i++)] = $value;
    }
    $cat_name = mysql_fetch_array(mysql_query("SELECT cat_nome FROM tbl_categorias WHERE  cat_id = '$row[cli_categoria]'"));
    $fields['cli_categoria'] = $cat_name['cat_nome'];
    $json_result = $fields;
    }
    return json_encode($json_result);
    }
    }

    $clientes = new clientes_db;
    $select   = $clientes->getClientes($_POST['cliente_nome']);

    if ($select) {
      echo$select;
    }

Thanks for the help guys.

    
asked by anonymous 05.05.2016 / 00:39

1 answer

1

First .. It is unnecessary to use cURL being that you are accessing your own script .. With the cURL request your site will make two requests instead of one, thus causing the response to the user. In jQuery, instead of passing a JSON to the date attribute of the ajax () method, you could pass the serialize () which would look cleaner like this:

HTML snippet

$("#form1").submit(function(e) {
    var form = $(this);
    e.preventDefault();
    $.ajax({
        url: "nova_busca.php",
        type: "POST",
        datatype: "JSON",
        data: form.serialize(),
        success:
        // ...

With this, the php file will no longer receive the POST parameter [" client_name "] and POST [" txt_name "] and POST ["seach"]] .. After that, without using cURL, we will connect and request the MySQL data with the new new_busca.php file.

nova_busca.php

<?php

// sua classe para conexão ao MySQL
class clientes_db {
    public function __construct() {
        mysql_connect("localhost", "Admin", "admin");
        mysql_select_db("avaliacao");
    }
    public function getClientes($nome) {
        // seleciona todos os clientes que tem o nome parecido com a pesquisa
        $select = mysql_query("SELECT * FROM tbl_clientes WHERE cli_nome LIKE \"%".$nome."%\"");
        // com o while, instancia todos em uma variável $fields
        while($row = mysql_fetch_array($select)) {
            $i = 0;
            // seleciona o nome da categoria do cliente
            $cat_name = mysql_fetch_array(mysql_query("SELECT cat_nome FROM tbl_categorias WHERE cat_id = "$row[cli_categoria]""));

            // instacia na variável
            $fields[$i]["cliente_nome"] = $row["cli_nome"];
            $fields[$i]["cat_name"] = $cat_name["cat_nome"];

            $i++;
        }
        // retorna string JSON
        return json_encode($fields);
    }
}

$nome = $_POST["txt_nome"];
$clientes = new clientes_db();
$select = $clientes->getClientes($nome);

// informa ao navegador que o conteúdo da página é JSON
header("Content-Type: application/json");
// imprime o JSON na página
echo $select;

?>

and the script looks something like this:

Script in tag

$(function() {
    $("#form1").submit(function(e) {
        var form = $(this);
        e.preventDefault();
        $.ajax({
            url: "nova_busca.php",
            type: "POST",
            datatype: "JSON",
            data: form.serialize(),
            success: function(data) {
            // alert(data.cliente_nome);
            var html = "";
            html+="<table border=\"1\">";
            html+="<thead>";
            html+="<tr>";
            html+="<th>NOME</th>";
            html+="<th>CATEGORIA</th>";
            html+="</tr>";
            html+="</thead>";
            html+="<tbody>";
            if(data.length > 0) {
                for(data as novo_data) {
                    html+="<tr>";
                    html+="<td>"+novo_data.cliente_nome+"</td>";
                    html+="<td>"+novo_data.cat_name+"</td>";
                    html+="</tr>";
                }
            } else {
                html+="<tr>";
                html+="<td colspan=\"2\">Nenhum cliente com este nome.</td>";
                html+="</tr>";
            }
            html+="</tbody>";
            html+="</table>";
            $(".response").html(html);
        }
        });
    });
});

With these functions implemented in this way, the search will return people with similar names, Ex: You have 3 registered customers with the names (Diego, Diego Rodrigues, Diego Teixeira) and in the search box type 'Diego' it will return the 3 registered. Already if you search 'Diego T' it will return only one client.

I hope I have helped and I hope you have understood your doubt .. Anything, ask yourself ..

    
05.05.2016 / 16:36