-1

I'm trying to use a php api with ajax to create a new contact. When I want to use the postContact.php file with ajax the query fail every time but if I write the post url directly in the browser it'll work.

I looked over internet but I didn't find a solution.

  • I looked in in the php function directly
  • I checked if the data format was good
  • I enter directly the data in the ajax code
  • I change the contentType and the dataType
  • I looked jQuery Ajax POST example with PHP before posting here
  • I remove datatype and content-type
  • I change this.method by "POST" and this.action by the url to the api

HTML Form to add contact

<form id="addContact_form" action="php/postContact.php" method="POST">
    <div class="modal-body">
        <div class="form-group">
            <label>Nom</label>
            <input id="addContact_nom" name="nom" type="text" class="form-control" required/>
         </div>
         <div class="form-group">
             <label>Prénom</label>
             <input id="addContact_prenom" name="prenom" type="text" class="form-control" />
         </div>
         <div class="form-group">
             <label>Fonction</label>
             <input id="addContact_fonction" name="fonction" type="text" class="form-control" />
         </div>
         <div class="form-group">
             <label>Téléphone</label>
             <input id="addContact_tel" name="telephone" type="number" class="form-control" />
          </div>
          <div class="form-group">
              <label>Adresse Mail</label>
              <input id="addContact_mail" name="couriel" type="email" class="form-control" />
          </div>
          <label>Lycée</label>
          <!--this is filled with an ajax function when the modal show up-->
          <select id="addContact_lycee" name="id_lycee" class="custom-select" required>
              <option selected>Sélectionner un lycée</option>
           </select>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
         <button type="submit" class="btn btn-perso-success">Save changes</button>
    </div>
 </form>

Ajax AddContact

$("#addContact_form").submit(function(event){

  $('#addContactDialog').modal('hide');
  loader('show','Sauvegarde en cours');

  event.preventDefault();

  console.log(this.action+$(this).serialize()); //this print https://..../php/postContact.phpnom=charle%20&prenom=edouard&fonction=eleve&telephone=0000&couriel=sdf%40dfg.g&id_lycee=2

  $.ajax({
    method: this.method,
    url:  this.action,
    data: $(this).serialize(),
    error: function(jqXHR, textStatus, errorThrown){
      loader('hide');
      errorAlert(errorThrown); 
    },
    success: function (data) {
      loader('hide');
      var message = data.message;
      if(message.indexOf('failed') != -1){
        errorAlert(data.message);
      }else{
        successAlert(data.messages);
      }
    }
  });
});

php file called by ajax

this is not mine so I don't really know how it's work

<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// get database connection

include_once 'lycee.php';
include_once 'bdd.php';

$bdd = getConnexion();
$lycee = new lycee($bdd);
// get posted data
$nom = $_GET['nom'];
$prenom = $_GET['prenom'];
$fonction = $_GET['fonction'];
$telephone = $_GET['telephone'];
$couriel = $_GET['couriel'];
$id_lycee = $_GET['id_lycee'];


$lycee->postContact($nom, $prenom, $fonction, $telephone, $couriel, $id_lycee);

?>

function PostContact()

public function postContact($nom, $prenom, $fonction, $telephone, $couriel, $id_lycee){
        $req2 = $this->conn->prepare ('SELECT * FROM contact WHERE lycee_contact=:id_lycee');
        $req2->execute(array('id_lycee' => $id_lycee));
        $donnees2 = $req2->fetchAll();
        $num = count($donnees2);
        //if alerady a contact to this entry -> update
        if($num > 0){
            $req = $this->conn->prepare('UPDATE contact SET nom=:nom, prenom=:prenom, fonction=:fonction, telephone=:telephone, couriel=:couriel WHERE lycee_contact=:id_lycee');
        $result = $req->execute(array('nom' => $nom, 'prenom' => $prenom, 'fonction' =>$fonction, 'telephone'=>$telephone, 'couriel'=>$couriel, 'id_lycee' => $id_lycee));
            if($result){
            echo '{';
                 echo '"message": "Contact a été sauvegardé"';
                echo '}';

            }else{
                echo '{';
                 echo '"message": "Une erreur est survenue, modification échoué"';
                echo '}';
            }
        }else{ //cerate contact
            $req = $this->conn->prepare('INSERT INTO contact SET nom=:nom, prenom=:prenom, fonction=:fonction, telephone=:telephone, couriel=:couriel, lycee_contact=:id_lycee');
            $result = $req->execute(array('nom' => $nom, 'prenom' => $prenom, 'fonction' =>$fonction, 'telephone'=>$telephone, 'couriel'=>$couriel, 'id_lycee' => $id_lycee));
            if($result){
                echo '{';
                    echo '"message": "Contact a été sauvegardé"';
                echo '}';
            }else{
                echo '{';
                 echo '"message": "Une erreur est survenue, création échoué"';
                echo '}';
            }
        }
    }

When the ajax method is executed it goes to the success callback but it returnd the api's error message and the data aren't add

I expect the ajax function to call execute the postContact.php file from the api to save a contact

  • What is the error that you get? – Mark Aug 15 '19 at 08:17
  • 2
    You're telling the server you're sending JSON, but your `data` is a queryString. Remove `contentType` and `dataType`. Don't overengineer this. Keep it simple. –  Aug 15 '19 at 08:18
  • "the query fail every time" - which kind of query are you talking about? What have you tried to debug the problem? – Nico Haase Aug 15 '19 at 08:18
  • Have you got value of `this.action & this.method` ! I dont think so – Jack jdeoel Aug 15 '19 at 08:18
  • @DavidJawHpan I do though. –  Aug 15 '19 at 08:20
  • ```this.action``` and ```this.method``` get the correct value a checked in the ```console.log``` I get a generic error : ```Request failed, please try again.``` the query is a simple URL ```/php/postContact.phpnom=charle%20&prenom=edouard&fonction=eleve&telephone=0000&couriel=sdf%40dfg.g&id_lycee=2``` – Maxime MOHANDI Aug 15 '19 at 08:21
  • What is your folder structure like, where from the root is your AJAX file and where is your form? – Mark Aug 15 '19 at 08:21
  • And I didn't catch this until now: you have `$("this").serialize()` instead of `$(this).serialize()` –  Aug 15 '19 at 08:27
  • @ChrisG thank you I changed it but it still not working plus i've tried with raw data and it didn't work too. – Maxime MOHANDI Aug 15 '19 at 08:31
  • Here's working code: https://jsfiddle.net/khrismuc/pukgx68v/ (please check my first comment I made 13 minutes ago and remove unnecessary parameters from the AJAX call) –  Aug 15 '19 at 08:32
  • @ChrisG thank you again I copied your code..iit didn't work. it goes to the success callback but the api return an error message – Maxime MOHANDI Aug 15 '19 at 08:37
  • 4
    If it goes to the success callback, this question is resolved. If your API doesn't properly handle the form data, that's a separate question. Even if it made sense to keep rewriting this question, you'd have to post your PHP code. –  Aug 15 '19 at 08:39
  • @ChrisG thank you very much i'll look into the php and i'll post the php here too – Maxime MOHANDI Aug 15 '19 at 08:40
  • 1
    Your form says `method="post"`, but php tries to fetch the values from `$_GET`. Try changing `$_GET['...']` to `$_POST['...']` – arkuuu Aug 15 '19 at 10:02
  • 1
    That was it ! how can I put your answer as accepted ? – Maxime MOHANDI Aug 15 '19 at 10:10

1 Answers1

1

I solved my problems thanks to arkuuu.

his anwser :

Your form says method="post", but php tries to fetch the values from $_GET. Try >changing $_GET['...'] to $_POST['...']

I follow his instruction and now it's work