Problem with POST and AJAX

1

The problem is that I send a form with AJAX in POST. Everything goes well in the FIRST SENDING, now if I make the second shipment, it keeps double of itself, and the third shipment, triple of itself, and so on. So, could you tell me some way to clean the POST or whatever needs to be cleaned to avoid this problem? When there is more than one insertion, multiply ... The truth is that I'm really confused.

Code of the file "polling.js" that activates the loading of the page "test.php" where each of the inserts are shown from MySQL.

$(document).ready(function(){
	$.ajaxSetup({ cache: false });
	$('#message').load('test.php');
	setInterval(function() {
		$('#message').load('test.php');
	}, 1000);
});

Code of the main page - "test-inside.php"

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
	<title></title>
	<script src="js/jq-1.11.3.js"></script>
	<script src="js/bst.min.js"></script>
	<script src="post-form.js"></script>
	<link rel="stylesheet" href="css/main.css">
	<link rel="stylesheet" href="css/bst.min.css">
</head>
<body style="background:none;font-family:Trebuchet MS;">
<div class="container">
	<div style="width:100%;height:300px;">
		<h1 style="margin:0;padding:0;width:100%;text-align:center;">NuevaRed Development Testing</h1>
		<form method="POST" id="form">
		<table>
			<tr>
				<td>
					<input type="text" class="form-control" style="border-radius:15px;" id="texto" name="texto" placeholder="Escribe tu mensaje" autocomplete="off" autofocus>
					<button type="submit" onclick="quebueno();" class="form-control btn btn-primary" style="border-radius:15px;" name="send">Enviar</button>
				</td>
			</tr>
		</table>
		</form>
		<div id="message" style="height:350px;overflow-y:scroll;padding:5px;margin:0;"></div>
	</div>
	
</div>
<script src="polling.js"></script>
</body>
</html>

MySQL insertion code - "sendmessage.php" the page that makes the process of saving in MySQL and then it is shown in "test.php"

<?php
require 'conec.php';
if($link){
	if(!empty($_POST['texto'])){
		require 'class.php';
		$inputText = $_POST['texto'];
	    $inputKey = "MaximaPuertaServiceReina17Milena";
	    $blockSize = 256;
	    $aes = new AES($inputText, $inputKey, $blockSize);
	    if($enc = $aes->encrypt()){
	    	$sql=mysqli_query($link,"INSERT INTO testing(e,Location) VALUES ('$enc','Here')");
	    }else{
	    	echo "Nope!";
	    }
	}else{
		echo "Escribe algo antes de enviar, plox.";
	}
}
?>

Code "test.php" where the data stored in MySQL is displayed.

<?php
require 'conec.php';
require 'class.php';
$inputKey = "MaximaPuertaServiceReina17Milena";
$blockSize = 256;
?>
<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<div class="mensajes">
<?php
if($sql=mysqli_query($link,"SELECT * FROM testing ORDER BY id_test DESC")){
	if(mysqli_num_rows($sql)>0){
		while ($filas = mysqli_fetch_array($sql)) {
			$us = $filas['e'];
			$inputText = $us;
		    $aes = new AES($inputText, $inputKey, $blockSize);
		    if($enc = $aes->decrypt()){
		    	if($filas['Location']=="Here"){
		    	?>
			    	<div class="s-pred" style="text-align:left;position:relative;width:75%;padding:5px 10px;">
			    		<table>
			    			<tr>
			    				<td>
			    					<h2 style="font-size:16px;text-align:left;margin:0;padding:0;"><?php echo $enc ?></h2>
			    				</td>
			    			</tr>
			    			<tr>
			    				<td>
			    					<h2 style="margin:0;padding:0;font-size:12px;text-align:left;"><b><?php echo $filas['Location'] ?></b></h2>
			    				</td>
			    			</tr>
			    		</table>
			    	</div>
		    	<?php
		    	}elseif($filas['Location']=="There"){
		    	?>
			    	<div class="s-pred" style="text-align:right;width:75%;position:relative;left:25%;padding:5px 10px;">
			    		<table>
			    			<tr>
			    				<td>
			    					<h2 style="font-size:16px;text-align:right;margin:0;padding:0;"><?php echo $enc ?></h2>
			    				</td>
			    			</tr>
			    			<tr>
			    				<td>
			    					<h2 style="margin:0;padding:0;font-size:12px;text-align:right;"><b><?php echo $filas['Location'] ?></b></h2>
			    				</td>
			    			</tr>
			    		</table>
			    	</div>
		    	<?php
		    	}
		    }
		}
	}else{
		?>
		<h4 style="width:100%;text-align:center;">No hay mensajes, ¿Dónde está la amistad? :v</h4>
		<?php
	}
}else{
	echo "HEY!!";
}
?>
</div>
</body>
</html>

Code of "post-form.js" which is responsible for making the registration to MySQL.

function quebueno(){
    $('#form').submit(function(e) {
        e.preventDefault()//evitas hacer el submit
        $.ajax({
            type: 'POST',
            url: 'sendmessage.php',
            data: $('#form').serialize(),
            success: function(data) {
                console.log("Sended!");
            }
        });
    });
}
    
asked by Mattew Janeey 26.06.2016 в 21:35
source

2 answers

3

The problem is in the JavaScript and it is quite interesting (or at least it seems to me). This is the code for the quebueno function:

function quebueno(){
    $('#form').submit(function(e) {
        e.preventDefault()//evitas hacer el submit
        $.ajax({
            type: 'POST',
            url: 'sendmessage.php',
            data: $('#form').serialize(),
            success: function(data) {
                console.log("Sended!");
            }
        });
    });
}

Each time quebueno is executed, an event handler submit is associated with the form with id form . Now let's see how to call quebueno :

<form method="POST" id="form">
    <table>
        <tr>
            <td>
                <input type="text" class="form-control" style="border-radius:15px;" id="texto" name="texto" placeholder="Escribe tu mensaje" autocomplete="off" autofocus>
                <button type="submit" onclick="quebueno();" class="form-control btn btn-primary" style="border-radius:15px;" name="send">Enviar</button>
            </td>
        </tr>
    </table>
</form>

It is called when you click on the button that sends the form. What does this mean? That each time the button is pressed, the submit's driver is being associated to the form, and the controller makes the AJAX call. Therefore with each pulse of the button a new controller and a new call are added. That's why the first data is saved once, the second twice, the third three times ...

For example, these would be the steps that the current code follows:

  • The user clicks on the button that calls quebueno
  • that the controller (which I will call controller 1) associates with the submit event of the form
  • The submit event of the form is called and the data will be saved once
  • Controller 1 runs and an AJAX call is made that stores the value.
  • The user clicks on the button that calls quebueno
  • that you associate the controller (which I will call controller 2) with the submit event of the form
  • The submit event of the form is called (and the data will be saved 2 times)
  • Controller 1 runs and an AJAX call is made that stores the value.
  • Controller 2 runs and an AJAX call is made that stores the value.
  • The user clicks on the button that calls quebueno
  • that the controller (which I will call controller 3) associates with the submit event of the form
  • The submit event of the form is called (and the data will be saved 3 times)
  • Controller 1 runs and an AJAX call is made that stores the value.
  • Controller 2 runs and an AJAX call is made that stores the value.
  • Controller 3 runs and an AJAX call is made that stores the value.
  • ...
  • The solution is simple:

  • Remove the call to quebueno of the button that submits the form

    <button type="submit" class="form-control btn btn-primary" style="border-radius:15px;" name="send">Enviar</button>
    
  • Move the content of quebueno to run when the page loads:

    $("document").ready(function() {
        $('#form').submit(function(e) {
            e.preventDefault()//evitas hacer el submit
            $.ajax({
                type: 'POST',
                url: 'sendmessage.php',
                data: $('#form').serialize(),
                success: function(data) {
                    console.log("Sended!");
                }
            });
        });
    });
    
  • As only a single controller is now associated (when the page is loaded), the data will only be saved once and not repeatedly.

        
    answered by 28.07.2016 в 04:35
    1

    You should paste a review to javascript go by parts, so you do not lose easy, likewise, it would be something like this:

    html

    <div id="lista_mensajes"></div>
    

    js

    var lista;
    lista = $('#lista_mensajes');
    lista.empty();
    lista.append(objeto, string, etc);
    

    In the js I'm using jquery, I do not know if you use it

        
    answered by 27.06.2016 в 20:12