IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Langage PHP Discussion :

Upload Image Php Ajax [PHP 7]


Sujet :

Langage PHP

  1. #1
    Membre actif
    Avatar de XeGregory
    Homme Profil pro
    Passionné par la programmation
    Inscrit en
    Janvier 2017
    Messages
    318
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Marne (Champagne Ardenne)

    Informations professionnelles :
    Activité : Passionné par la programmation
    Secteur : High Tech - Matériel informatique

    Informations forums :
    Inscription : Janvier 2017
    Messages : 318
    Points : 295
    Points
    295
    Par défaut Upload Image Php Ajax
    Bonjour, j'essaye désespérément de uploader une image, mais un problème se pose, lors du post impossible de publier ni de uploader l'image sa me retourne toujours l'erreur Js Ajax (error: function() {)

    Code HTML : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <form action="#" method="POST" enctype="multipart/form-data" accept-charset="UTF-8">
    <textarea id="tweet-textbox" class="form-control form-control-sm" name="tweet-textbox" onkeyup="" rows="7" maxlength="300" placeholder="<?php echo $tweettextholder;?>" onfocus="this.placeholder = ''" onblur="this.placeholder = '<?php echo $tweettextholder; ?>'"
     <div id="link-block" class="link-block">
        <div class="custom-file">
        <input type="file" class="custom-file-input" name="link" id="tweet-linkbox" lang="fr" accept=".jpg,.jpeg,.gif,.png">
        <label class="custom-file-label" for="tweet-linkbox" data-browse="&bull;&bull;&bull;">Image : jpg, jpeg, gif, png</label>
    </div>
    </div>
    <div id="hashtag-block" class="hashtag-block">
        <div class="input-group mb-2 mr-sm-2">
            <div class="input-group-prepend">
                <div class="input-group-text"><img src="assets/images/tweet/tweet-box/hashtag-box.svg" alt="" /></div>
            </div>
            <input type="text" id="tweet-hashtagbox" class="form-control" id="inlineFormInputGroup" placeholder="#DarkTweet">
        </div>
    </div>
    <div id="tweet-error" class="alert alert-danger">
    <?php echo $tweeterror; ?>
    </div>                           
    </form>

    JS Ajax
    Code JavaScript : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    function sendtweet() {
       var text = $('#tweet-textbox').val();
       var link = $('#tweet-linkbox').val();
       var hashtag = $('#tweet-hashtagbox').val();
       var gresponse = recapstatus();
       recapreset();
     
       if(text.length < 20) {
          $('#tweet-short').fadeIn(400);
          $('#tweet-short').delay(3000).fadeOut(400);
       } else {
          $("#tweet-textbox").val('');
          $("#tweet-linkbox").val('');
          $("#tweet-hashtagbox").val('');
     
          $("#charNum").val('300');
          $.ajax({
             type: 'POST',
             url: 'includes/upload.tweet.php',
             contentType: false,
             processData: false,
             data: {
                tweet: text,
                link: link,
                hashtag: hashtag,
                "g-recaptcha-response": gresponse
             },
             success: function(data) {
                if(data.status === 'ok') {
                   $('#tweet-success').fadeIn(400);
                   $('#tweet-success').delay(3000).fadeOut(400);
     
                   setTimeout(function() {
                      $(location).attr('href', 'index.php');
                   }, 3800);
     
                } else if(data.status === 'limit_reached') {
                   $('#tweet-limit').fadeIn(400);
                   $('#tweet-limit').delay(3000).fadeOut(400);
     
                   setTimeout(function() {
                      $(location).attr('href', 'index.php');
                   }, 3800);
     
                } else if(data.status === 'guest') {
                   $('#tweet-guest').fadeIn(400);
                   $('#tweet-guest').delay(3000).fadeOut(400);
     
                   setTimeout(function() {
                      $(location).attr('href', 'index.php');
                   }, 3800);
     
                } else if(data.status === 'captcha') {
                   $('#tweet-captcha').fadeIn(400);
                   $('#tweet-captcha').delay(3000).fadeOut(400);
                } else {
                   $('#tweet-error').fadeIn(400);
                   $('#tweet-error').delay(3000).fadeOut(400);
     
                   setTimeout(function() {
                      $(location).attr('href', 'index.php');
                   }, 3000);
                }
             },
             error: function() {
                $('#tweet-error').fadeIn(400);
                $('#tweet-error').delay(3000).fadeOut(400);
             }
          });
       }
    }

    Code PHP : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    <?php
    session_start();
     
    if (!empty($_POST['tweet']) && strlen($_POST['tweet']) <= 300 && strlen($_POST['tweet']) >= 20) {
        if ($_SESSION['username'] != 'Guest') {
            require 'class.darktweet.php';
            $conn = new Includes\Database();
     
            $limit_check = $conn->limit_tweet_check($_SESSION['username']);
     
            if ($limit_check >= '1') {
                header('Content-Type: application/json');
                $arr = array(
                    "status" => 'limit_reached'
                );
                echo json_encode($arr, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
            } else {
     
                require 'configuration/recaptcha.php';
                $post_data = http_build_query(array(
                    'secret' => $secret_key,
                    'response' => $_POST['g-recaptcha-response'],
                    'remoteip' => $_SERVER['REMOTE_ADDR'],
                    'timeout' => 5));
     
                $opts = array(
                    'http' => array(
                        'method' => 'POST',
                        'header' => 'Content-type: application/x-www-form-urlencoded',
                        'content' => $post_data));
     
                $context  = stream_context_create($opts);
                $response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
                $result   = json_decode($response);
     
    // Uploader
     
                if (isset($_FILES['link']['name'])) {
                    $filename = $_FILES['link']['name'];
     
                    $location      = "assets/images/uploads/" . $filename;
                    $imageFileType = pathinfo($location, PATHINFO_EXTENSION);
                    $imageFileType = strtolower($imageFileType);
                    $valid_extensions = array("jpg", "jpeg", "png");
     
                    if (in_array(strtolower($imageFileType), $valid_extensions)) {
                        move_uploaded_file($_FILES['link']['tmp_name'], $location))
                    }
                }
     
                preg_match("/[#]+([a-zA-Z0-9_+]+)/", $_POST['hashtag'], $hashtag);
                if (!empty($hashtag) && strlen($hashtag) < 15) {
                    $_POST['hashtag'] = "#" . ucfirst($hashtag[1]);
                } else {
                    $_POST['hashtag'] = "#DarkTweet";
                }
     
                if ($result->success) {
                    session_start();
                    $conn->insert_tweet($_SESSION['username'], $_POST['tweet'], $_POST['link'], $_POST['hashtag'], $_SERVER['REMOTE_ADDR']);
                } else {
                    header('Content-Type: application/json');
                    $arr = array("status" => 'captcha');
                    echo json_encode($arr, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
                }
            }
        } else {
            header('Content-Type: application/json');
            $arr = array("status" => 'guest');
            echo json_encode($arr, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        }
    }

    Merci

  2. #2
    Membre actif
    Avatar de XeGregory
    Homme Profil pro
    Passionné par la programmation
    Inscrit en
    Janvier 2017
    Messages
    318
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Marne (Champagne Ardenne)

    Informations professionnelles :
    Activité : Passionné par la programmation
    Secteur : High Tech - Matériel informatique

    Informations forums :
    Inscription : Janvier 2017
    Messages : 318
    Points : 295
    Points
    295
    Par défaut
    J'ai comme l'impression que la fonction (sendtweet) et bancal si j’enlève (contentType: false, & processData: false,) le post fonctionne.

  3. #3
    Expert confirmé Avatar de Toufik83
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Janvier 2012
    Messages
    2 447
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : Suisse

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Janvier 2012
    Messages : 2 447
    Points : 4 966
    Points
    4 966
    Par défaut
    Bonjour,

    Pour les images, tu as besoin d'utiliser l'objet FormData() dans lequel tu ajoutes seulement les variables qui n'existent pas dans <form id="myForm"> (avec append), et laisse le reste au FormData($("#myForm").get(0)) qui ajoutera automatiquement les autres variables existant dans <form id="myForm"> en fonction de leurs name :

    Code html : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    <form id="myForm"...></form>

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    var formData=new FormData($("#myForm").get(0));
    formData.append("g-recaptcha-response", gresponse);
    $.ajax({
       method: 'POST',/* type est remplacé par method dans les nouvelles versions de jQuery */
       url: 'includes/upload.tweet.php',
       contentType: false,
       processData: false,
       dataType:"json",/* puisque le fichier php renvoie du json*/
       data:formData
    })
    .done(...)
    .fail(...);
    Attention tu as deux id ici :
    <input type="text" id="tweet-hashtagbox" class="form-control" id="inlineFormInputGroup" placeholder="#DarkTweet">.

    Remarques :
    • Ajoutes l'option dataType:"json" puisque le fichier php renvoie du json.
    • Les callback success et error sont dépréciés depuis jQuery 3.x, il va donc falloir les remplacer par done et fail.

  4. #4
    Membre actif
    Avatar de XeGregory
    Homme Profil pro
    Passionné par la programmation
    Inscrit en
    Janvier 2017
    Messages
    318
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Marne (Champagne Ardenne)

    Informations professionnelles :
    Activité : Passionné par la programmation
    Secteur : High Tech - Matériel informatique

    Informations forums :
    Inscription : Janvier 2017
    Messages : 318
    Points : 295
    Points
    295
    Par défaut
    Merci Toufik83 je vais jeter un coup d'œil à mon code et faire un teste.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [AJAX] Upload image en ajax
    Par Laurelaie dans le forum AJAX
    Réponses: 4
    Dernier message: 15/10/2009, 13h21
  2. Upload image php
    Par Meloooo dans le forum Langage
    Réponses: 2
    Dernier message: 09/01/2009, 11h43
  3. [Upload] Upload image php
    Par totofe dans le forum Langage
    Réponses: 5
    Dernier message: 10/07/2008, 16h00
  4. [AJAX] upload d'images php/ajax
    Par zehni dans le forum Général JavaScript
    Réponses: 5
    Dernier message: 17/08/2007, 14h13
  5. [Upload] Upload images php
    Par lls dans le forum Langage
    Réponses: 15
    Dernier message: 19/07/2007, 18h23

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo