Problem with Ajax + PHP - Attempt to make a Form

1

I'm trying to create a form that works with Ajax and Php, but I still have not been able to do it because I'm making a mistake and I do not know which. I leave here the code so you can help me.

The idea of the page is that where is the input that is where the person will enter a url, I can save what you have entered in a txt file. I do not want the page to be reloaded because I need to use Ajax so that the page does not recharge and that user can enter a url, example: link so that can visualize in the player jw player.

Delete the styles and a bit of the player code so that the html code does not get too long. If someone wants it, they can ask me to try it.

/*
*CODIGO AJAX: FORM.JS
*/
/*
*CODIGO AJAX: FORMS.JS
*/
/*
*Funcion Javascript para enviar formularios sin recargar la página mediante ajax
*/

/* "escuchamos" el click en el botón con id "submit" solo si ya se ha cargado la página*/

$(function(){
   $('#submit').click(function(e){
      //evitamos la carga de la página
      e.preventDefault();
      //recogemos el id del formulario a enviar
      var form = $(this).attr("form-id");
      //llamamos a la función que contendrá el llamado ajax dándole como argumento el id del formulario
      submitForm(form);
   });
});

//fuera de la carga de la página, creamos la función que recibe el id del formulario a enviar.

function submitForm(form){
   //recogemos el "action" a donde se enviarán los datos mediante "POST"
   var action = $("form#" + form).attr("action");
   //ahora recogemos los datos de los controles que hayamos definido y los serializamos como un formulario con Javascript
   var datos = $('form#' + form).serialize();
   //recogemos la posicion actual del id "mensaje" esto para que al recibir la respuesta de PHP se haga scroll hasta alli para mostrarlo correctamente.
   var mensaje = document.getElementById('mensaje').offsetTop - 20;

   //enviamos los datos mediante Ajax con la función de Jquery que nos facilita esta tarea

   $.ajax({
      //url a enviar
      url: 'enviar_chh.php',
      //el tipo GET o POST en nuestro caso POST
      type: 'POST',
      //evitamos el cacheo de los datos
      cache: false,
      //evitamos que el JS procese los datos
      proccessData: false,
      //definimos los datos a enviar, nosotros ya los tenemos definidos en la variable "datos"
      data: datos
      //cuando se recibe la respuesta se activa el siguiente trozo de código
      //la r que recibe la funcion de callback es "response" que viene del script PHP
   }).done(function(r){
      //hacemos scroll hasta el id "mensaje"
      $('body, html').animate({
         scrollTop: mensaje
      }, 700);
      //imprimimos con HTML el mensaje recibido
      $('#mensaje').html(r);
      //eso es todo
   });
}
<!DOCTYPE html>
<!-- CODIGO HTML: INDEX.HTM -->
<!-- CODIGO HTML: INDEX.HTM -->
<html>

<head>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><script type="text/javascript" charset="utf-8" async="" src="./ipptv_files/related.js.descarga"></script><script type="text/javascript" charset="utf-8" async="" src="./ipptv_files/jwpsrv.js.descarga"></script>
    
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>IPTV Player - DaZPlayer</title>
    <link rel="stylesheet" href="./ipptv_files/developer.css">
    <link rel="stylesheet" href="./ipptv_files/style.css">
    <script src="jquery-3.1.1.js"></script>
    <script src="form.js"></script>

  <script type="text/javascript" charset="utf-8" async="" src="./ipptv_files/jwplayer.core.controls.js.descarga"></script><script type="text/javascript" charset="utf-8" async="" src="./ipptv_files/provider.hlsjs.js.descarga"></script>

</head>
  <body>

  <div class="page" id="stream-tester">
    <div class="mkdocs-jwplayer">
    <div>

  <div class="jw-tool">
    <div class="container">
      <div class="row">
        <div class="column sm-12 lg-6">

          <div class="tool-settings">
            <div class="configuration" style="display:none">
              <h2>Player Version:</h2>
              <label>
                <input name="version" type="radio" value="8" checked="">
                  JW Player 8
              </label>
              <label>
                <input name="version" type="radio" value="7">
                  JW Player 7
              </label>
            </div>

            <div id="mensaje"></div>
            <form id="form-registro" action="enviar_chh.php" method="post">
            <div class="configuration">
              <h2>Escriba una URL de algún canal:</h2>
              <input id="file" type="text" name="canal" placeholder="https://content.jwplatform.com/manifests/yp34SRmf.m3u8" value="">
            </div>

            <div class="configuration" style="display:none">

              <label style="display:none">
                <input name="primary" type="radio" value="html5" checked="">
                HTML5
              </label>

              <label style="display:none">
                <input name="primary" type="radio" value="flash" disabled="">
                Flash
              </label>

              <label style="display:none" class="tooltip tooltip-top-center">
                <input name="hls" type="checkbox">
                Force type to HLS
                <span class="tooltip-content tooltip-content-wrap">
                </span>
              </label>

            </div>

            <div id="drm" class="configuration" style="display:none">

              <div id="drm-default" class="drm-item drm-item-selected" style="display:none">
                <label>
                  <input name="drm" type="radio" value="" checked="checked">
                  None
                </label>
              </div>

              <div id="drm-widevine" class="drm-item">
                <label>
                  <input name="drm" type="radio" value="widevine">
                  Widevine
                </label>
                <div class="drm-item-options">
                  <label>
                    Widevine Url:
                    <input id="drm-widevine-url" type="text">
                  </label>
                  <label>
                    <input name="drm-item-custom-data" type="checkbox">
                    Use custom data? (optional)
                  </label>
                  <div class="drm-item-custom-data">
                    <label>
                      Custom Name:
                      <input id="drm-widevine-custom-name" type="text">
                    </label>
                    <label>
                      Custom Value:
                      <input id="drm-widevine-custom-value" type="text">
                    </label>
                  </div>
                </div>
              </div>

              <div id="drm-playready" class="drm-item drm-item-not-supported">
                <label>
                  <input name="drm" type="radio" value="playready" disabled="">
                  Playready
                </label>
                <div class="drm-item-options">
                  <label>
                    Playready Url:
                    <input id="drm-playready-url" type="text" disabled="">
                  </label>
                  <label>
                    <input name="drm-item-custom-data" type="checkbox" disabled="">
                    Use custom data? (optional)
                  </label>
                  <div class="drm-item-custom-data">
                    <label>
                      Custom Name:
                      <input id="drm-playready-custom-name" type="text" disabled="">
                    </label>
                    <label>
                      Custom Value:
                      <input id="drm-playready-custom-value" type="text" disabled="">
                    </label>
                  </div>
                </div>
              </div>

              <div id="drm-fairplay" class="drm-item drm-item-not-supported">
                <label>
                  <input name="drm" type="radio" value="fairplay" disabled="">
                  Fairplay
                </label>
                <div class="drm-item-options">
                  <label>
                    Certificate URL:
                    <input id="drm-fairplay-certificate-url" type="text" disabled="">
                  </label>
                  <label>
                    Process SPC URL:
                    <input id="drm-fairplay-process-spc-url" type="text" disabled="">
                  </label>
                </div>
              </div>

              <div id="drm-clearkey" class="drm-item">
                <label>
                  <input name="drm" type="radio" value="clearkey">
                  Clearkey
                </label>
                <div class="drm-item-options">
                  <label>
                    ClearKey Key:
                    <input id="drm-clearkey-key" type="text">
                  </label>
                  <label>
                    ClearKey Key ID:
                    <input id="drm-clearkey-key-id" type="text">
                  </label>
                </div>
              </div>

            </div>

            <div class="button-set">
              <button class="button button-sm" type="submit" id="submit" form-id="form-registro" type="button" name="button" >Reproducir canal</button>
            </div>
          </form>
            <div id="test-output" class="test-output test-output-visible" style="display:none">
              <h2>Test Player Config Output</h2>
              <pre><code id="output-code" class="javascript hljs">{
  <span class="hljs-string">"playlist"</span>: [
    {
      <span class="hljs-string">"sources"</span>: [
        {
          <span class="hljs-string">"default"</span>: <span class="hljs-literal">false</span>,
          <span class="hljs-string">"file"</span>: <span class="hljs-string">"https://content.jwplatform.com/manifests/yp34SRmf.m3u8"</span>,
          <span class="hljs-string">"label"</span>: <span class="hljs-string">"0"</span>,
          <span class="hljs-string">"type"</span>: <span class="hljs-string">"hls"</span>
        }
      ]
    }
  ],
  <span class="hljs-string">"primary"</span>: <span class="hljs-string">"html5"</span>,
  <span class="hljs-string">"hlshtml"</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-string">"id"</span>: <span class="hljs-string">"stream-tester-player-https"</span>
}</code></pre>
            </div>

          </div>
        </div>

        <div class="column sm-12 lg-6">
          <div class="tool-player">
            <div class="player-preview">JW Player Test</div>
           
            <!-- <div id="stream-tester-player-http" class="u-hidden">
              <iframe style="border: none; display: block; height: 500px; width: 100%;"></iframe>
              This stream tester requires HTTPS streams. Using an HTTP stream with our stream tester may cause your test to fail.
            </div> -->
            <p>
              DRM solutions are available for both HLS and MPEG-DASH adaptive streaming technologies and are configurable via the <a href="http://demo.jwplayer.com/jw-player/docs/developer-guide/customization/configuration-reference/#drm">JW Player Javascript API</a>.
            </p>
            <p>
              Note that JW Player's DRM support is constrained by what the DRM makers themselves support. For example, Apple supports FPS in Safari on Mac OS, but not in Safari on iOS.
            </p>
          </div>
        </div>

      </div>

    </div>

  </div>

</div>


    </div>
    <script src="./ipptv_files/jquery.min.js.descarga"></script>
    <script src="./ipptv_files/developer.js.descarga"></script>
    <script type="text/javascript" src="./ipptv_files/stream-tester.js.descarga"></script><script src="./ipptv_files/wr6i4gal.js.descarga"></script>


</body>
</html>

---------------------------

Then the php code: enviar_chh.php

//codigo php: enviar_chh.php
//codigo php: enviar_chh.php

<?php
$canal="";
if (!empty($_REQUEST['canal'])){
$canal=$_REQUEST['canal'];
}

//Luego sobrescribo el txt

$archivo="datos.txt";

     $file=fopen($archivo,"a");
     fwrite($file,$canal);
     fclose($file);
?>

I would give a thousand thanks if someone could help me, telling me where the error is and how to solve it. Greetings.

    
asked by DaZ 08.03.2018 в 23:17
source

1 answer

0

The ajax's Done parameter does not do what you think, it helps to know if the ajax request has been sent correctly or not, but it does not control the response.

To control the response of the ajax you have to use the "success"

Try running your code, this works for me

File: index.js

var request = $.ajax({
    //url a enviar
    url: '/test.php',
    //el tipo GET o POST en nuestro caso POST
    type: 'post',
    //definimos los datos a enviar, nosotros ya los tenemos definidos en la variable "datos"
    data: {data: 'aaaaa'},
    success: function (output) {
        // aqui tu respuesta se enseña en consola
        console.log(output);
    }

});
request.done(function () {
    console.log('La peticion AJAX se ha enviado correctamente ');
});
request.fail(function () {
    console.log('Algo ha malo ha sucedido :( ');
});

File: index.php

$canal="";
if (!empty($_REQUEST['data'])){
    $canal=$_REQUEST['data'];
}

//Luego sobrescribo el txt

$archivo="datos.txt";

$file=fopen($archivo,"a");
fwrite($file,$canal);
fclose($file);
echo $canal;
  

It is important to consider your folder structure so that the   call AJAX find the PHP, in my case it's all in the root   /index.php, /index.js Check that you are not confusing with the   relative and / or absolute routes

    
answered by 21.03.2018 / 18:50
source