Problem with ajax and Curl to receive the mysql value and return to html

Asked

Viewed 295 times

0

I’m having a problem using html, ajax, Curl and mysql. the function is simple an html page where it will receive a name and will send by ajax to the 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>
<form action="" 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 php database

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

I appreciate your help, guys.

1 answer

1


First.. It is unnecessary to use Curl when you are accessing your own script.. With the Curl request your site will make two requests instead of one, leading to this in the delay of the response to the user. In jQuery, instead of passing a JSON to the attribute date of the method ajax() , you could pass the return of the method serialize() that would be cleaner, so:

Excerpt from the HTML

$("#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["cliente_name"] and yes POST["txt_name"] and POST["seach"] .. Done this, without using Curl, we will make the connection and request the Mysql data with the new file nova_search.php.

nova_search.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 will look 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 clients with the names (Diego, Diego Rodrigues, Diego Teixeira) and in the search field type 'Diego' it will return the 3 registered. Already if you search 'Diego T' it will return only one customer.

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

Browser other questions tagged

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