Execute javascript code inside a script called with ajax

1

I need to show an alert and stop the execution of the script when the user clicks on the accept button when he does not select any week to pay, this is the ajax function:

$('#sub').click( function() {         
  $("#update").submit(function(e){
  var formData = new FormData(this);
  e.preventDefault();
  $.ajax({
    url: "files/hoursToPay.php",
          type: "POST",
          data:  formData,
          contentType: false,
          cache: false,
          processData: false,
          success: function(data){
              alert("Horas pagadas");
          },
          error: function(data){
              console.log(data)
          }
        });
      });
    });

Inside the hoursToPay script:

<?php

// Si seleccionó al menos una semana
if (isset($_POST['hours'])):
    //Codigo para pagar semanas
else:
    echo '<script>alert("Selecciona al menos una semana"); 
    return false;</script>';
endif;
?>

The problem is that the javascript code that is inside the script does not work, is there any way to make it work ?, thanks.

    
asked by Fernando Garcia 04.10.2018 в 00:52
source

2 answers

0

And why let the user click on the button if the form is not properly filled out?

The solution I propose is very simple:

  • The send button will be disabled while the required input has no data
  • To control that we will hear the events change , paste and keyup in that input:

$(function() {
  /*Creamos referencias a los elementos*/
  var $btnEnviar = $("#btnEnviar");
  var $ibxSemana = $("#ibxSemana");

  /*Variable que se posteará*/
  var $postVal = "";

  /*De entrada desactivamos el botón*/
  $btnEnviar.prop("disabled", true);

  /*Aquí escuchamos los cambios en el input*/
  $ibxSemana.on("change paste keyup", function() {
    /*Recogemos el valor del input*/
    $postVal = $.trim($(this).val());
    
    /*Determinamos si está o no vacío para activar o no el botón*/
    var btnDisabled = ($postVal == "") ? true : false;

    /*Cambiamos o  no  el estado del botón según el valor de btnDisabled*/
    $btnEnviar.prop("disabled", btnDisabled);

  });

  /*
   *Se ejecutará al hacer clic en el botón
   *aquí pones tu llamada Ajax
   */
  $btnEnviar.click(function(event) {
    event.preventDefault();
    console.log('Aquí la petición Ajax, usando la variable $postVal cuyo valor actual es ${$postVal}');
  });


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="tuarchivo.php" method="post">
  <p>
    <label for="usuario">Semana:
<input id="ibxSemana" type="text" name="semana" required /></label>
  </p>
  <p>
    <button id="btnEnviar" type="submit" name="enviar">Enviar</button>
  </p>
</form>
    
answered by 04.10.2018 / 02:20
source
0

To be able to execute the alert with AJAX it is not necessary to summon a PHP file, you can try

$('#sub').click( function() {         
  $("#update").submit(function(e){
  var formData = new FormData(this);
  var horasPagadas = variableHTML //-----
  e.preventDefault();
  $.ajax({
   url: "files/hoursToPay.php",
      type: "POST",
      data:  formData,
      contentType: false,
      cache: false,
      processData: false,
      success: function(horasPagadas){
          alert("Horas pagadas" . horasPagadas );
      },
      error: function(data){
          console.log(data)
      }
    });
  });
});
    
answered by 04.10.2018 в 01:02