0

I am unable to insert de data into mysql using angular. If i want to fetch data in mysql it works ok, but this doesn't work.

I can't see the error. Can you help me?

this is my html form:

           <form #suscribir="ngForm">      
                <div class="modal-body bodycolabora">
                    <label class="labelmodal">Recibe nuestros correos para estar al tanto de los últimos post y recursos subidos.</label>
                    <div class="md-form mb-2">
                        <label class="labelmodal">Tu nombre*</label>
                        <input class="form-control" type="text" name="nombre" class="input" placeholder="Tu nombre" [(ngModel)]="datos.nombre" required minlength="3" #nameInput="ngModel">          
                    </div>
                    <div *ngIf="nameInput.invalid && (nameInput.dirty || nameInput.touched)"
                        class="alert alert-danger">

                    <div *ngIf="nameInput.errors.required">
                        Escribe tu nombre.
                    </div>
                    <div *ngIf="nameInput.errors.minlength">
                        Name must be at least 4 characters long.
                    </div>
                    </div>                        
                    <div class="md-form mb-2">
                        <label class="labelmodal">Email*</label>
                        <input class="form-control" type="email" name="email" class="input" placeholder="Tu email" [(ngModel)]="datos.email" required email #emailInput="ngModel">         
                    </div> 
                    <div *ngIf="emailInput.invalid && (emailInput.dirty || emailInput.touched)"
                        class="alert alert-danger">

                    <div *ngIf="emailInput.errors.required">
                        Escribe tu email.
                    </div>          
                    </div>                         
                    <!--Privacidad-->
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" id="aceptopolitica" name="privacidad" value="acepto" ngModel required #privacidadInput="ngModel">
                        <label class="labelmodal" class="form-check-label" for="infantil" name="etapa" >Acepto la Política de privacidad</label> 
                    </div> 
                    <div *ngIf="privacidadInput.invalid && (privacidadInput.dirty || privacidadInput.touched)"
                        class="alert alert-danger">

                    <div *ngIf="privacidadInput.errors.required">
                        Acepta la política de privacidad
                    </div> 
                    </div>                      
                </div>
                <div class="modal-footer footercolabora d-flex justify-content-center">
                    <button (click)="suscriptores()" value="Nuevo suscriptor" type="submit" name="submit" id="submit" class="btn btncolabora" [disabled]="suscribir.invalid">Enviar →</button>
                </div>
            </form>

In my component.ts i have:

datos={
    nombre:null,
    email:null
  }
constructor(private articulosServicio: ServicioService) { 
    
  }
suscriptores() {
    this.articulosServicio.suscriptores(this.datos).subscribe(datos => {
      if (datos['resultado']=='OK') {
        alert(datos['mensaje']);
      }
    });

In the service.ts:

url='http://xxxxxxxxxxx/'; // 

  constructor(private http: HttpClient) { }    
suscriptores(datos) {
        return this.http.post(`${this.url}suscriptores.php`, JSON.stringify(datos));
      }

and finally the file.php,

<?php
header('Access-Control-Allow-Origin: *'); 
      header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
      header('Content-Type: application/json');
      
      $json = file_get_contents('php://input');
     
      $params = json_decode($json);
      
      require("conexion.php");
      $con=retornarConexion();   
      
      $email = mysqli_real_escape_string($con, $params->email);  
      $nombre = mysqli_real_escape_string($con, $params->nombre);  
    
      $query= 'INSERT INTO newsletter(email, nombre) VALUES ("' . $email . '","'. $nombre .'")';
      
      if(mysqli_query($con, $query)) 
        { 
          class Result {}
    
          $response = new Result();
          $response->resultado = 'OK';
          $response->mensaje = 'datos grabados';
        }  
        else  
        {  
          class Result {}
    
          $response = new Result();
          $response->resultado = 'OK';
          $response->mensaje = 'datos grabados';
        }
        header('Content-Type: application/json');
      echo json_encode($response);  
    ?>

Sorry for all the code but i think you might need id to see the error

puluku
  • 1
  • 1
  • After `$params = json_decode($json);` what is output if you add `var_dump($params->email); var_dump($params->nombre); die();`? You should be able to use your browser's Developer Tools and view the Network tab to see the output when it makes this request to your PHP script. What I'm suggesting here is to narrow down the problem - is the issue with Angular or is it with PHP/MySQL? – WOUNDEDStevenJones Aug 20 '20 at 16:21
  • If i go to the url of the php it works ok by itself. Inserting blanks into database because there isn't info in the $params, so i think the problem come from the angular site. It seems the data doesn't reach the php script. – puluku Aug 20 '20 at 16:29
  • Can you inspect the request to file.php in the Network tab of Developer Tools so you can see the actual request that Angular is making? This will help test if `$params` is even being set correctly. I'm not sure how Angular is making the request to your PHP file, so at the top of your PHP file maybe first try `var_dump(file_get_contents('php://input')); die();` and view that output via the Network tab to see if it's even being passed in standard input. Maybe it's being POSTed instead, but it's hard to tell unless you view the actual request and response of that. – WOUNDEDStevenJones Aug 20 '20 at 16:35
  • if i write that in php i see the error: SyntaxError: Unexpected token s in JSON at position 0 at JSON.parse – puluku Aug 20 '20 at 16:52
  • that's the error in JS because your PHP is now returning non-JSON, but in the Network tab, click on the actual request (row), and then you should be able to see a Response tab that will show you what the "response" of your PHP script is. https://stackoverflow.com/a/3019085/1499877 may be helpful in figuring out how to use this tab – WOUNDEDStevenJones Aug 20 '20 at 17:11
  • Thank you for helping by the way. I have three rows inside network tab two of them show suscriptores.php (response tab says failed to load response data) and another one only shows suscriptores( response tab shows string(0) "") – puluku Aug 20 '20 at 17:28
  • Perfect, that shows that `file_get_contents('php://input')` is empty. So your first step is going to be debugging your PHP script to determine how to get the variables that are being passed from Angular (assuming they actually _are_ being passed - you'll need to verify this somehow). Probably by starting at `this.http.post(\`${this.url}suscriptores.php\`, JSON.stringify(datos))` to inspect `datos`. In PHP you may need to use `$_POST` instead https://www.php.net/manual/en/reserved.variables.post.php to retrieve the POST data. – WOUNDEDStevenJones Aug 20 '20 at 18:08

0 Answers0