1

I tried to adapt a form with ajax, it works perfect, but I don't get the message that the php page teaches, to see if everything has gotten right. Ajax works right, enter the data right but I don't get it to tell me if status is error or success.

Form:

                                <form class="form-horizontal" method="POST" name="Form" onsubmit="return validateForm()" action="javascript:cancelClicked(nombre2.value, menu.value)">
                                <div class="card-body">
                                    <div class="form-group row">
                                        <label for="nombre" class="col-sm-3 text-right control-label col-form-label">Nombre</label>
                                        <div class="col-sm-9">
                                            <input type="text" name='nombre2' class="form-control" id="nombre2" placeholder="Nombre" value="">
                                        </div>
                                    </div>
                                </div>
                                 <input type="hidden" name='menu' readonly class="form-control" id="menu" placeholder="<?php echo $menu;?>" value="<?php echo $menu;?>">

                                <div class="border-top">
                                    <div class="card-body">
                                        <button type="submit" value="Submit" class="btn btn-primary">Actualiza</button>
                                    </div>
                                </div>
                            </form>
<script language="javascript">
        function cancelClicked(txt) {
            // function below will run clear.php?h=michael
            //var txt3 = txt ;
            $.ajax({
                type: "GET",
                url: "insert-linia-almacen.php?empresa=<?php echo $empresa;?>&nombre=" + txt + "&menu=<?php echo $menu;?>" ,
                dataType: "json",
                success: function(data) {
    if(data.status == 'success'){
        alert("Thank you for subscribing!");
    }else if(data.status == 'error'){
        alert("Error on query!");
    }
}
            });
        }
    </script>

php:

/// Create connection
$conn2 = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn2) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql2 = "SELECT * FROM `almacen_linias` WHERE empresa = '$empresa' AND menu='$menu' AND nombre = '$nombre'";
$result2 = mysqli_query($conn2, $sql2);


if (mysqli_num_rows($result2) > 0) {
   // output data of each row
    while($row = mysqli_fetch_assoc($result2)) {
        //echo "existe";
        $response_array['status'] = 'error';  
    } 
}else{
   // echo "no existe";

    // Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO `almacen_linias` (`id`, `empresa`, `nombre`, `menu`) VALUES (NULL, '$empresa', '$nombre', '$menu')";

if ($conn->query($sql) === TRUE) {
    //echo "New record created successfully";
    $response_array['status'] = 'success';  
} else {
    //echo "Error: " . $sql . "<br>" . $conn->error;
    $response_array['status'] = 'error';  
}

$conn->close();
}
$conn2->close();


    echo json_encode($response_array);
halfer
  • 19,824
  • 17
  • 99
  • 186
diaconu liviu
  • 1,032
  • 2
  • 13
  • 30
  • See this answer : https://stackoverflow.com/a/59594761/12232340 –  Jan 28 '20 at 16:32
  • **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Jan 28 '20 at 16:43
  • Anyway, have you checked your Browser's Console for errors? Or checked the Network tool to examine the response from the AJAX request? There are a few places in your PHP code where it might not return valid JSON (e.g. the `die` statements), or if the code crashes it won't either. So that might result in an error where jQuery cannot parse the response. You need to debug it properly. – ADyson Jan 28 '20 at 16:45
  • thanks but i don't understand what's wrong in my code – diaconu liviu Jan 28 '20 at 21:12
  • are you talking about my first comment or my second one? – ADyson Jan 28 '20 at 21:36
  • first comment . – diaconu liviu Jan 29 '20 at 07:20
  • Ok so if you don't understand, then first read the http://bobby-tables.com/ page which I gave you. If you still don't understand, then read https://en.wikipedia.org/wiki/SQL_injection. Basically, if someone sends a HTTP request to your `insert-linia-almacen.php` script and sets the `nombre` parameter to something like `'); DROP TABLE almacen_linias; --` then there is a chance they could delete your table. Or they could try and insert something incorrect, or whatever. This is because you allow the user input value to go into the SQL string raw, without any kind of filtering or sanitisation. – ADyson Jan 30 '20 at 09:52
  • Using parameterised queries means that the database engine takes care of ensuring that the parameter data (intended as the values to query against, or insert into the table rows) are always treated purely as data, and can never be mis-interpreted as executable SQL. See https://bobby-tables.com/php for simple examples of how to do it. – ADyson Jan 30 '20 at 09:53

0 Answers0