Bonsoir,
je suis entrain de finir mon site pour ma webradio et il me reste à finir le système de dédicace.
Je n'arrive pas à ajouter le champ pseudo dans le script.

dedicaces.php

<script type="text/javascript">
    $(document).ready(function() {

        //##### send add record Ajax request to response.php #########
        $("#FormSubmit").click(function (e) {
            e.preventDefault();
            if($("#contentText").val()==='')
            {
                alert("Please enter some text!");
                return false;
            }

            $("#FormSubmit").hide(); //hide submit button
            $("#LoadingImage").show(); //show loading image

            var myData = 'content_txt='+ $("#contentText").val(); //build a post data structure
            jQuery.ajax({
                type: "POST", // HTTP method POST or GET
                url: "response.php", //Where to make Ajax calls
                dataType:"text", // Data type, HTML, json etc.
                data:myData, //Form variables
                success:function(response){
                    $("#responds").append(response);
                    $("#contentText").val(''); //empty text field on successful
                    $("#FormSubmit").show(); //show submit button
                    $("#LoadingImage").hide(); //hide loading image

                },
                error:function (xhr, ajaxOptions, thrownError){
                    $("#FormSubmit").show(); //show submit button
                    $("#LoadingImage").hide(); //hide loading image
                    alert(thrownError);
                }
            });
        });

        //##### Send delete Ajax request to response.php #########
        $("body").on("click", "#responds .del_button", function(e) {
            e.preventDefault();
            var clickedID = this.id.split('-'); //Split ID string (Split works as PHP explode)
            var DbNumberID = clickedID[1]; //and get number from array
            var myData = 'recordToDelete='+ DbNumberID; //build a post data structure

            $('#item_'+DbNumberID).addClass( "sel" ); //change background of this element by adding class
            $(this).hide(); //hide currently clicked delete button

            jQuery.ajax({
                type: "POST", // HTTP method POST or GET
                url: "response.php", //Where to make Ajax calls
                dataType:"text", // Data type, HTML, json etc.
                data:myData, //Form variables
                success:function(response){
                    //on success, hide  element user wants to delete.
                    $('#item_'+DbNumberID).fadeOut();
                },
                error:function (xhr, ajaxOptions, thrownError){
                    //On error, we alert user
                    alert(thrownError);
                }
            });
        });

    });
</script>

<div class="content_wrapper">
    <div class="form_style">
        <div class="form-group">
            <input name="content_dedi" id="contentDedi" class="form-control" placeholder="Votre pseudo!"><br>
            <textarea name="content_txt" id="contentText" class="form-control" cols="45" rows="5" placeholder="Enter some text"></textarea>
        </div>
        <button class="btn btn-primary btn-block" id="FormSubmit"><i class="fa fa-bullhorn"></i> Envoyer ma dédicace!</button>
    </div>
</div>

Response.php

<?php
//include db configuration file
include_once("config.php");

if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0)
{   //check $_POST["content_txt"] is not empty

    //sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH Strip tags, encode special characters.
    $contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 

    // Insert sanitize string in record
    $insert_row = $mysqli->query("INSERT INTO add_delete_record(content) VALUES('".$contentToSave."')");

    if($insert_row)
    {
         //Record was successfully inserted, respond result back to index page
          $my_id = $mysqli->insert_id; //Get ID of last inserted row from MySQL
          echo '<li id="item_'.$my_id.'">';
          echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">';
          echo '<img src="images/icon_del.gif" border="0" />';
          echo '</a></div>';
          echo $contentToSave.'</li>';
          $mysqli->close(); //close db connection

    }else{

        //header('HTTP/1.1 500 '.mysql_error()); //display sql errors.. must not output sql errors in live mode.
        header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
        exit();
    }

}
elseif(isset($_POST["recordToDelete"]) && strlen($_POST["recordToDelete"])>0 && is_numeric($_POST["recordToDelete"]))
{   //do we have a delete request? $_POST["recordToDelete"]

    //sanitize post value, PHP filter FILTER_SANITIZE_NUMBER_INT removes all characters except digits, plus and minus sign.
    $idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT); 

    //try deleting record using the record ID we received from POST
    $delete_row = $mysqli->query("DELETE FROM add_delete_record WHERE id=".$idToDelete);

    if(!$delete_row)
    {    
        //If mysql delete query was unsuccessful, output error 
        header('HTTP/1.1 500 Could not delete record!');
        exit();
    }
    $mysqli->close(); //close db connection
}
else
{
    //Output error
    header('HTTP/1.1 500 Error occurred, Could not process request!');
    exit();
}
?>

Merci beaucoup

5 réponses


Salutations,
Si j'ai bien compris tout ce que tu veux faire c'est passé la valeur du champ pseudo à ta requête AJAX ? Sinon je ne vois pas ce qui te bloques, un simple .val() et c'est fait du style :

data: {
    content_txt : $("#contentText").val(),
    pseudo : $("#contentDedi").val()
}

Est-ce ça que tu veux, ou peux-tu décrire ton problème plus précisémment :) !
Lud00

Yubo
Auteur

Il faudrais rajouter le champs pseudo sur tous les scripts que j'ai envoyer, mais je galère.

Merci beaucoup

Du coup, avec ce que je t'ai montré ça devrait le faire, tu n'as plus qu'a récupérer le résultat dans ton fichier response.php, comme si tu avais la variable normalement, avec un $_POST['pseudo '].

Yubo
Auteur

Sur la response.php je suis bloqué

<?php
//include db configuration file
include_once("config.php");

if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0 AND isset($_POST['pseudo ']) && strlen($_POST['pseudo '])>0)
{   //check $_POST["content_txt"] is not empty

    //sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH Strip tags, encode special characters.
    $contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 

    // Insert sanitize string in record
    $insert_row = $mysqli->query("INSERT INTO add_delete_record(content) VALUES('".$contentToSave."')");

    if($insert_row)
    {
         //Record was successfully inserted, respond result back to index page
          $my_id = $mysqli->insert_id; //Get ID of last inserted row from MySQL
          echo '<li id="item_'.$my_id.'">';
          echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">';
          echo '<img src="images/icon_del.gif" border="0" />';
          echo '</a></div>';
          echo $contentToSave.'</li>';
          $mysqli->close(); //close db connection

    }else{

        //header('HTTP/1.1 500 '.mysql_error()); //display sql errors.. must not output sql errors in live mode.
        header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
        exit();
    }

}
elseif(isset($_POST["recordToDelete"]) && strlen($_POST["recordToDelete"])>0 && is_numeric($_POST["recordToDelete"]))
{   //do we have a delete request? $_POST["recordToDelete"]

    //sanitize post value, PHP filter FILTER_SANITIZE_NUMBER_INT removes all characters except digits, plus and minus sign.
    $idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT); 

    //try deleting record using the record ID we received from POST
    $delete_row = $mysqli->query("DELETE FROM add_delete_record WHERE id=".$idToDelete);

    if(!$delete_row)
    {    
        //If mysql delete query was unsuccessful, output error 
        header('HTTP/1.1 500 Could not delete record!');
        exit();
    }
    $mysqli->close(); //close db connection
}
else
{
    //Output error
    header('HTTP/1.1 500 Error occurred, Could not process request!');
    exit();
}
?>

Et sur le js c'est bien comme ça?

<script type="text/javascript">
    $(document).ready(function() {

        //##### send add record Ajax request to response.php #########
        $("#FormSubmit").click(function (e) {
            e.preventDefault();
            if($("#contentText").val()==='')
            {
                alert("Please enter some text!");
                return false;
            }

            $("#FormSubmit").hide(); //hide submit button
            $("#LoadingImage").show(); //show loading image

            var myData = 'content_txt='+ $("#contentText").val(); //build a post data structure
            jQuery.ajax({
                type: "POST", // HTTP method POST or GET
                url: "response.php", //Where to make Ajax calls
                dataType:"text", // Data type, HTML, json etc.
                data: {
                    content_txt : $("#contentText").val(),
                    pseudo : $("#contentDedi").val()
                }
                success:function(response){
                    $("#responds").append(response);
                    $("#contentText").val(''); //empty text field on successful
                    $("#FormSubmit").show(); //show submit button
                    $("#LoadingImage").hide(); //hide loading image

                },
                error:function (xhr, ajaxOptions, thrownError){
                    $("#FormSubmit").show(); //show submit button
                    $("#LoadingImage").hide(); //hide loading image
                    alert(thrownError);
                }
            });
        });

        //##### Send delete Ajax request to response.php #########
        $("body").on("click", "#responds .del_button", function(e) {
            e.preventDefault();
            var clickedID = this.id.split('-'); //Split ID string (Split works as PHP explode)
            var DbNumberID = clickedID[1]; //and get number from array
            var myData = 'recordToDelete='+ DbNumberID; //build a post data structure

            $('#item_'+DbNumberID).addClass( "sel" ); //change background of this element by adding class
            $(this).hide(); //hide currently clicked delete button

            jQuery.ajax({
                type: "POST", // HTTP method POST or GET
                url: "response.php", //Where to make Ajax calls
                dataType:"text", // Data type, HTML, json etc.
                data:myData, //Form variables
                success:function(response){
                    //on success, hide  element user wants to delete.
                    $('#item_'+DbNumberID).fadeOut();
                },
                error:function (xhr, ajaxOptions, thrownError){
                    //On error, we alert user
                    alert(thrownError);
                }
            });
        });

    });
</script>

Quand c'est comme ça, il faut utiliser la console développeur pour débugger du javascript, sous chrome ctrl+shift+u, puis tu choisis l'onglet console et tu regardes si tu as des erreurs. Par exemple ici, il faut rajouter une virgule après data :

data: {
    content_txt : $("#contentText").val(),
    pseudo : $("#contentDedi").val()
},
success:function(response){
    $("#responds").append(response);
    ...
},

Essaye déjà avec ça, ensuite tu peux également faire un print_r de la variable $_POST dans ton php, après en passant par l'outil debug tu va dans l'onglet network, tu cliques sur l'appel de ton fichier php et dans header tu peux voir l'affichage de ton script php. Pratique :) ! Bon courage.