Link to home
Start Free TrialLog in
Avatar of B O
B O

asked on

Hi, some of my form input ($_POST) gets recognized and inserted in my php file (youtube_api) to upload to a database, but the uploaded img ($_FILES) and variables are not recognized

I am busy creating a website for a business. And glad to get the oppertunity help someonewith their bussiness.
I am busy creacting a form for a page, the user can type in title, text, image and video.
The issue I have is uploading the image using $_Files it appears not be recognized by php when update with ajax. I have tried searching for the solution on the web but been struggling with it for a couple of days.

First I had issues with all form element being recognized but now its just the image.

https://pastebin.com/wBUtJRLS 


Avatar of Scott Fell
Scott Fell
Flag of United States of America image

I am putting your pastbin here to keep things in one thread.
======================================================= incl.page.php ==============================================================
<?php


if (isset($_POST['page_upload'])) {


   $newFileName = $_POST["page_img"];
   
   if (empty($newFileName)) {
      $newFileName = "gallery";
   } else {
      //create lowercase of filename and replace empty space with -
      $newFileName = strtolower(str_replace(" ", "-", $newFileName));
   }
   $imgTitle = $_POST["page_title"];
   $imgDescr = $_POST["page_descr"];
   
   $pageImg = $_FILES['page_img'];
   
   $fileName = $pageImg['name'];
   $fileType = $pageImg['type'];
   $fileTempName = $pageImg['tmp_name'];
   $fileError = $pageImg['error'];
   $fileSize = $pageImg['size'];


   $youtubeVideoId = $_POST["videoId"];
   
   $fileExtension = explode(".", $fileName);
   $fileActualExt = strtolower(end($fileExtension));
   
   $allowed = array("jpg", "jpeg", "png");
   
   if (in_array($fileActualExt, $allowed)) {
      if ($fileError === 0) {
         if ( $fileSize < 2000000 ){
            $imageFullName = $newFileName . "." . uniqid("", true) . "." . $fileActualExt;
            $fileDestination = "../img/page/" . $imageFullName;
            
            include_once "dbh.incl.php";
            
            if (empty($imgTitle) || empty($imgDescr) || empty($youtubeVideoId)) {
               header("Location: ../page-post.php?upload=empty'$youtubeVideoId'" . $youtubeVideoId );
               exit();
            } else {
               $sql = "SELECT * FROM pages";
               $stmt = mysqli_stmt_init($conn);
               if (!mysqli_stmt_prepare($stmt, $sql)) {
                  echo"SQL statement gefaald 1!";
               } else {
                  mysqli_stmt_execute($stmt);
                  $result = mysqli_stmt_get_result($stmt);
//                  $rowCount = mysqli_num_rows($result);
//                  $setImageOrder = $rowCount + 1;
                  
                  $sql = "INSERT INTO pages (titlePage, descPage, imgPage, youtubeVideoId) VALUES (?, ?, ?, ?)";
                  if (!mysqli_stmt_prepare($stmt, $sql)) {
                  echo "SQL statement gefaald 2!";
                  }
                  else {
                     // bind 3 strings to statement
                     mysqli_stmt_bind_param($stmt, "ssss", $imgTitle, $imgDescr, $imageFullName, $youtubeVideoId);
                     mysqli_stmt_execute($stmt);
                     
                     move_uploaded_file($fileTempName, $fileDestination);
                     
                     header("Location: ../page-manage.php?upload=succes");
                     exit();
                  }
               }
            }
            
            
         } else {
            echo 'bestand is te groot!';
         }
         
      } else {
         echo 'U heeft een error bij het uploaden van uw bestand!';
      }
   } else {
      echo 'Om een bestand te uploaden moet het een PNG/JPEG/JPG bestand zijn!';
   }
   
   print_r($pageImg);
   
}


=============================================== youtube_api.js ======================================================


        const searchField = document.querySelector('#search');          


        searchField.addEventListener('input', youtubeApiCall);


        function ajaxJS(url, callback){
            let xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function(){
                if (xhr.readyState==4 && xhr.status==200){
                    callback(JSON.parse(xhr.responseText))
                }  
            }
            xhr.open('GET',url, true);
            xhr.send();
        }


        const api_key = 'AIzaSyCmEJztJ7c2CTPNwLearKkVS7kJ47BAysA';
        const channel_Id = 'UCSX8u8oui51cdUj3pQxszhA';
            function youtubeApiCall(){
                $.ajax({
                    cache: false,
                    data: $.extend({
                        key: api_key,
                        q: $('#search').val(),
                        channelId: channel_Id,
                        part: 'snippet'
                    }, {
                        maxResults: 10,
                        // pageToken: $("#pageToken").val()
                    }),
                    dataType: 'json',
                    type: 'GET',
                    timeout: 5000,
                    url: 'https://youtube.googleapis.com/youtube/v3/search?',
                    // method: "post",
                    // data: {data: JSON.stringfy( data)},
                }).done(function(data) {
                    // $('.btn-group').show();
                    if (typeof data.items[0] === 0) {
                        $("#result").hide();
                        alert('items in json not found')
                    } else {
                        $("#result").show();
                    }
                    // if (typeof data.nextPageToken === "undefined") {
                    //     $("#pageTokenNext").hide();
                    // } else {
                    //     $("#pageTokenNext").show();
                    // }
                    let items = data.items,
                        videoList = "";                        
                    // $("#pageTokenNext").val(data.nextPageToken);
                    // $("#pageTokenPrev").val(data.prevPageToken);
                    $.each(items, function(index, e) {
                        // videoList = videoList + '<li><div><a href="" class="hyv-content-link" title="' + e.snippet.title + '"><span class="title">' + e.snippet.title + '</span><span class="stat attribution">by <span>' + e.snippet.channelTitle + '</span></span></a></div><div class="hyv-thumb-wrapper"><a href="" class="hyv-thumb-link"><span class="hyv-simple-thumb-wrap"><img alt="' + e.snippet.title + '" src="' + e.snippet.thumbnails.default.url + '" width="120" height="90"></span></a></div></li>';
                    videoList += `<div class="my-2" >
                    <div>Title: ${e.snippet.title}</div>
                    <iframe src="https://www.youtube.com/embed/${e.id.videoId}"
                        class="ytVideo"
                        name="video-${e.id.videoId}"
                        width="400"
                        height="300"
                        allowfullscreen>
                    </iframe>
                    <br>                    
                    <button
                        type="button"
                        name=""
                        id="${e.id.videoId}"
                        value="${e.id.videoId}"
                    >select <i id="icon-${e.id.videoId}" class="fas fa-check-square"></i></button>
                    </div>`;                
                    });
                    $("#result").html(videoList);
                    // JSON Responce to display for user     
                    new PrettyJSON.view.Node({
                        // el: $(".hyv-watch-sidebar-body"),
                        data: data
                    });
                });
            }


            // check which button selected
            let videoId = "";


            document.querySelector("#result").addEventListener('click', function(e) {


                if(e.target.id) {
                    // alert(e.target.id);
                    $(".active").removeAttr("name", "youtubeVideoId");
                    $(".active").removeClass("active");
                   
                    let selectYoutubeVideo = document.getElementById(e.target.id);
                    videoId += String(e.target.id);
                   
                    selectYoutubeVideo.className += " active";
                    selectYoutubeVideo.setAttribute("name", "youtubeVideoId");                  
                }
            });


            // extract data
           


            $("button").on('click', function(){
                videoId += $(this).val();
                if (videoId){
                    $("#hide_video").show();
                    $("#name_video").text( videoId );
                }                
            })


            let page_upload = "";


            let page_title = "";


            $(".page_title").on('input', function(){
                page_title += $(this).val();
            })
           
            let page_descr = "";


            $(".page_descr").on('input', function(){
                page_descr += $(this).val();
            })


            let page_img = "page_upload";


            $(".page_img").on('input', function(){
                page_img += this.files[0]['name'];
            })


            let data =  {videoId: videoId, page_title: page_title, page_descr: page_descr, page_img: page_img, page_upload: page_upload };
            // document.querySelector("#submit-button").click();


            $(".submit").on('click', function(){
            //     $.ajax({
            //         url: '/blog-app/includes/page.incl.php',
            //         type: "POST",
            //         data,
            //         dataType: "text",
            //         success: function(data){
            //             console.log("success", data);
            //             alert(data);
                       
            //         },


            //         error: function (e) {
            //             console.log("Unsuccessful:", e);
            //         }
            //     });
                alert(page_title + '<br>' + page_descr + '<br>' + page_img + '<br>' + videoId);
                $.post("/blog-app/includes/page.incl.php",{data: data}, function(data, status){
                    console.log(data);
                    alert(data, status);
                })          
            })


================================================ youtube_api.php ==================================================================


<?php
require __DIR__ . '/vendor/autoload.php';
// Loads .env file token


$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();


$search = $_POST['search'];
$API_key  = $_ENV['YOUTUBE_TOKEN'];
$channelID  = 'UCSX8u8oui51cdUj3pQxszhA';
$maxResults = 10;
$loadApi = 'https://youtube.googleapis.com/youtube/v3/search?part=snippet&channelId=UCSX8u8oui51cdUj3pQxszhA&maxResults=' . $maxResults . '&q='.$search.'&key='.$API_key.'';


// initialise the request
$ch = curl_init();


// set some options
curl_setopt($ch, CURLOPT_URL, $loadApi);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


$resp = curl_exec($ch);
$info = curl_getinfo($ch);


$output = '';


if ($e = curl_error($ch)) {
    echo $e;            
    } else {


    $videoList = json_decode($resp, true);
    if (isset($videoList["items"])) {
        foreach($videoList["items"] as $item){
            if (isset($item["id"]["videoId"])){


            $output .= '<div class="m-3" style="display: inline-flex;">
                    <div
                        style="display: flex; flex-direction: column; position: relative;  aspect-ratio:(16/9); width:300px; max-height: 250px; border:solid 1px lightgrey;"
                        >
                        <iframe width="280" height="150" src="https://www.youtube.com/embed/' . $item["id"]["videoId"] . '" allowfullscreen></iframe><br>
                        <div>' . $item["snippet"]["title"] . '} </div>
                        <input
                        type="submit"
                        class="youtube-btn"
                        name=""
                        value="' . $item["id"]["videoId"] . '"
                        id="' . $item["id"]["videoId"] . '"
                        onClick="videoClicked()"
                    >select <i id="icon" class="fas fa-check-square"></i>
                    </div>                                    
                    </div>
                </div>';
            }        
        }
    print_r($output);
    } else {
        echo 'Unfortunatly you have reached your search limit for the day';
    }
curl_close($ch);
}             

Open in new window

I don't see a file input anywhere in your code...
Avatar of B O
B O

ASKER

Excuse me here it is

==================================================================================

<?php 
    include_once 'admin-nav.php';
    include_once 'admin-page-header.php';
    require "includes/page.incl.php";
?>

<main class="my-5">
    
<div class="col-sm-10">
    <div class="container">
        <div class="align-self-center">
            <h1 class="font-weight-light text-center text-lg-left mt-4 mb-0">Upload pagina</h1>         
            <br>
            <form action="" method="post" id="myForm" enctype="multipart/form-data">
            
            <input type="text" name="page-title" class="page_title" placeholder="Pagina titel.." style="width:100%;"><br><br>
            <textarea name="page-descr" class="page_descr" id="" cols="30" placeholder="pagina beschrijving.." rows="10" style="width:100%;"></textarea>
            <hr>
            <input type="file" name="page-img" class="page_img">
            <label for="page-img">Kies een achtergrond</label>
            <br>
            <hr>
            <h3>Voeg een video toe</h3>
            <br>
            <input type="text" class="form-control" id="search" name="search" placeholder="type in gezochte video">
            <br>
            <div id="hide_video"><div id="name_video"></div></div>
            <br>
            <hr>
            <br>
            <h5 id="vidsAvailable">Videos beschikbaar</h5>
            <div class="row-xs-6 row-md-3">
                <div class="col">
                    <div id="result"></div>
                </div>
            </div>
            <br>
            <hr>
                <section class="form-group">        
                    <button type="button" name="page-upload" class="submit">Pagina Uploaden</button>
                </section>
            </form>
        </div>
    </div>
</div>
</main>

<!-- admin-page-header -->
</div>
<!-- <script scrc="js/youtube_api.js"></script> -->
<!-- <script src="js/preview-image.js"></script> -->
<?php
    require 'footer.php';
?>


It appears that you may need to look at your form field naming and compare to your script variables


$imgTitle = $_POST["page_title"];  
$imgDescr = $_POST["page_descr"];   
$pageImg = $_FILES['page_img'];

Open in new window


<input type="text" name="page-title" class="page_title" placeholder="Pagina titel.." style="width:100%;"><br><br>            
<textarea ]name="page-descr" class="page_descr" id="" cols="30" placeholder="pagina beschrijving.." rows="10" style="width:100%;"></textarea>
            <hr>
<input type="file" name="page-img" class="page_img">

Open in new window

Avatar of B O

ASKER

Thank you very much, I overlooked that.I really appreciate it.
But It still doenst upload to my database.
I dont get any error from my youtube_api.php
So it makes it tricky to find out why it doenst insert the data to the database
So it makes it tricky to find out why it doenst insert the data to the database

Not at all,

if (isset($_POST['page_upload'])) {   
$newFileName = $_POST["page_img"];

Open in new window



<button type="button" name="page-upload" class="submit">Pagina Uploaden</button>
<input type="file" name="page-img" class="page_img">

Open in new window


Like I stated above

You are going to have to go through your code and verify your form id's against your script variables.
You have mismatched identifiers
Avatar of B O

ASKER

haha love your accuracy,
I checked if I forgot something else and I have all element names corrected.
But I still dont get a data/ status response after posting to youtube_api.php file
or see the database updated with a new page
Please update the referenced code and form

It's hard to track what's been changed and what hasn't
Hey there,

Right ... unfortunately, you've got quite a few problems with your code, and I think you're probably mis-understanding some of the key concepts that you need. This tends to happen when you're trying to write code that does 10 different things - you can never quite get a grasp on which part is broken. My suggestion would be to take a step back and focus on each individual moving moving part.

First off, let's look at your AJAX call. The basically principle of an AJAX call is that it sends some data from your front-end (browser) to your back-end (server) via an HTTP request. Here's the code that you have (tidied up a little)

let page_upload = "";
let page_title = "";
let page_descr = "";
let page_img = "page_upload";


$(".page_title").on('input', function(){
    page_title += $(this).val();
})


$(".page_descr").on('input', function(){
    page_descr += $(this).val();
})


$(".page_img").on('input', function(){
    page_img += this.files[0]['name'];
})


let data =  {videoId: videoId, page_title: page_title, page_descr: page_descr, page_img: page_img, page_upload: page_upload };

$(".submit").on('click', function(){
    alert(page_title + '<br>' + page_descr + '<br>' + page_img + '<br>' + videoId);

    $.post("/blog-app/includes/page.incl.php",{data: data}, function(data, status){
        console.log(data);
        alert(data, status);
    })
})

Open in new window

And here's what's happening : you initialise 4 variables to empty strings. You then bind the 'input' event to several elements within your page. That's a problem, because you will effectively add the full text of the input every time you type a character, so if you typed 'chris', you would end up with 'cchchrchrichris'


You never actually change the value of the page_upload, so it always remains as ''. You set the value of page_img to the string literal of 'page_upload', and then you add the name of a selected file to that, so you'll end up with something like "page_uploadmyfile.jpg".

You then build a data object containing various keys and values (let data = {...})

Once you've built your data object, you then POST that to your PHP script, which will have access to those values by using the keys on the POST array:

$_POST['page_title']
$_POST['page_descr']
$_POST['page_img']

** On this, @kenfcamp is slightly off the mark. The data that you send is NOT using the names of the HTML elements - it's using the keys you set in the data object.

All your script is doing is sending some text info to your PHP script. At no point are you actually sending any files!

If I were you, I would strip out all of the YouTube stuff. Create a very simply HTML file with a couple of  textboxes and a FILES input, and start working with that. Write your PHP script to be as simple as possible - simply echo back the data it receives. Once you know you're getting good data into your script, build on that. And absolutely make sure you turn on error reporting in your PHP script. Failing silently is NOT good while you're debugging !!

Take it step-by-step.
Avatar of B O

ASKER

Thank you for your suggestion,
I am going to recheck my code,

This is my codebefore I added the youtube api
https://github.com/Ted-bot/istanhairweb/blob/master/includes/page.incl.php

I might try to update with ajax without the files to check, if I update my form directly with php it works fine incl the file img
Yeah - it will work directly with PHP because the file is sent along with the normal form submission. However, when you're dealing with AJAX you need to do it differently - you need to use an instance of FormData
Avatar of B O

ASKER

Hi Thank you for your help,
I was able to track the errors and made adjustment to my code,
I added a formdata function and instead of selecting the names of inputs I just grapped the id of the form and turned it to a "form data"
and I have no errors coming from my jquery ajax.
But now I have a problem with tracking issues in my includes/page.incl.php.
I set a alert in my ajax  success function that should show any error or status from the php file but I see nothing at all.

I hope there is some ideas how I could get some data back so I can know what the issues are

Here is my adjusted code

https://pastebin.com/uEegkpZE

I thank you in advance
OK. The problem you now have is that your entire PHP code in the includes.page.incl.php file is wrapped in the following if statement:

if (isset($_POST['page_upload'])) {

The way you're sending data means that your POST array doesn't contain the page_upload key, so that if statement resolves to FALSE and everything is skipped. Either add a hidden input to your form with a name of page_upload or change the if statement:

if (empty($_POST)) {

Also, turn on error reporting at the top of that script, otherwise any errors will be blackboxed and you'll never see them.
Avatar of B O

ASKER

I thank your for your help

Now I managed to get some response from php with the following error in the console (see picture):
- Undefined index:
- Trying to access array offset on value of type null

,I tried isset, is_uploaded_file and basename() on the $_POST variables but it cant seem to read the file input

I appreciate the help that i have gotten. https://pastebin.com/0297NCqY
I checked with the following code to validate the file inserted and validates the filetype every time:

        // File type validation
        $(".page_img").on('change', function() {
            let file = this.files[0];
            let fileType = file.type;
            let match = ['application/pdf', 'application/msword', 'application/vnd.ms-office', 'image/jpeg', 'image/png', 'image/jpg'];
            if(!((fileType == match[0]) || (fileType == match[1]) || (fileType == match[2]) || (fileType == match[3]) || (fileType == match[4]) || (fileType == match[5]))){
                alert('Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.');
                $("#file").val('');
                return false;
            } else {
                alert(fileType);
            }
        });

User generated image
OK. First off - when you post code, can you please post it here, instead of on another website - just makes it easier for everyone to see what you're working with. When you comment, on the toolbar, you'll see the StyleCode button - use that.

Now, your problem is caused because you start off by setting the AJAX request method to POST, and then you override that and set it to GET, so you never actually make a POST request:

$.ajax({
    url: '/blog-app/includes/page.incl.php',
   type: "POST",
    data: new FormData(this),
    cache: false,
    processData: false,
    contentType: false,
   method: 'get',
    beforesend: function() {

Because you never make a POST request, you never send the files, so your $_FILES array is never populated. Remove the method : 'get' line from your AJAX options.
Avatar of B O

ASKER

Awesome,

Thank you I see no errors, I really appreciate it

But my database is not updated with the new data
User generated imageUser generated image
OK. I'm gonne refer you back to one of my earlier comments - when your coding, trying to 10 things at once will cause your trouble - you have no way of knowing which part of you program is broken. The general idea of development is to work on only one piece of the puzzle at a time. Get that working flawlessly, and then move on to the next part. As you have it, you've got AJAX calls to YouTube going on as well as AJAX calls to your PHP script - you're trying to move uploaded files as well as insert data into the database - that's a lot of things that can and will go wrong.

When you're writing code that uses AJAX your REALLY need to know what's going on behind the scenes. An AJAX request happens in the background which means you don't really see what's happening and all you have to rely on is the Console, unless you know how to debug your code property. Usually, what I suggest to people is to forget about AJAX until you know for sure that your server-side script is working correctly. This means that when you post your form to your php script, you can see exactly what's going on.

Now, if you look at your console, you'll see that the output of your AJAX call is a full webpage and NOT the $response you were expecting. If you look at your PHP code, you'll see a couple of redirects in there (if things like $videoId are empty). You can't do redirects like that in an AJAX handler - basically the outcome of a redirect (i.e. a full web page) will just be sent back to your AJAX Success handler and dumped into the console.

My suggestion would be to drop the idea of the AJAX form submission for a minute or two. Turn on error reporting in your PHP script, and right the very start of the PHP script add a var_dump of $_POST and $_FILES.

Change your HTML form action to point directly at the script:

<form action="/blog-app/includes/page.incl.php" method="post" id="myForm" enctype="multipart/form-data">

And then submit your form. This way, you browser will show the exact output of the PHP script without having to try and see it behind the curtain of an AJAX request.

Keep it like that until you've fully tested and debugged the PHP script (it should only ever return a JSON string). Once that's done, then you implement your AJAX call.
Avatar of B O

ASKER

Hi Thank you for the response,
I just checked my php file without ajax and works fine and inserts it into the data base and moves the file.
I checked everything one by one, I had to make some adjustments but works perfectly

But now I wonder How I can update including with the youtubeVideoId.
I think I need Ajax for this, but am open for other suggestions

here is the updated php without ajax file that inserts data to the database
;<?php

/* Answer to: "php error reporting" */

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$response = array(
    'status' => 0,
    'message' => 'Form submission falied, please try again'
);

if (isset($_POST["page_upload"])) {

    $newFileName = isset($_POST["page_img"]["name"]);
    
    if (empty($newFileName)) {
        $newFileName = "pageImg";
    } else {
        //create lowercase of filename and replace empty space with -
        $newFileName = strtolower(str_replace(" ", "-", $newFileName));
    }
    $imgTitle = $_POST["page_title"];
    $imgDescr = $_POST["page_descr"];
    
    $pageImg = isset($_POST["page_img"]);
    
    $fileName = $_FILES["page_img"]["name"];
    $fileType = $_FILES["page_img"]['type'];
    $fileTempName = $_FILES["page_img"]['tmp_name'];
    $fileError = $_FILES["page_img"]['error'];
    $fileSize = $_FILES["page_img"]['size'];

    $youtubeVideoId = isset($_POST["videoId"]);
    
    $fileExtension = explode(".", $fileName);
    $fileActualExt = strtolower(end($fileExtension));
    
    $allowed = array("jpg", "jpeg", "png");
    
    if (in_array($fileActualExt, $allowed)) {
        if ($fileError === 0) {
            if ( $fileSize < 2000000 ){
                $imageFullName = $newFileName . "." . uniqid("", true) . "." . $fileActualExt;
                $fileDestination = "../img/page/" . $imageFullName;
                
                include_once "dbh.incl.php";
                
                if (empty($imgTitle) || empty($imgDescr)) {
                    header("Location: ../page-post.php?upload=emptyinput" . $youtubeVideoId . "");
                    exit();
                } else {
                    $sql = "SELECT * FROM pages";
                    $stmt = mysqli_stmt_init($conn);
                    if (!mysqli_stmt_prepare($stmt, $sql)) {
                        echo"SQL statement gefaald 1!";
                    } else {
                        mysqli_stmt_execute($stmt);
                        $result = mysqli_stmt_get_result($stmt);
//                      $rowCount = mysqli_num_rows($result);
//                      $setImageOrder = $rowCount + 1;
                        
                        $sql = "INSERT INTO pages (titlePage, descPage, imgPage) VALUES (?, ?, ?)";
                        if (!mysqli_stmt_prepare($stmt, $sql)) {
                        echo "SQL statement gefaald 2!";
                        }
                        else {
                            // bind 3 strings to statement
                            mysqli_stmt_bind_param($stmt, "sss", $imgTitle, $imgDescr, $imageFullName);
                            mysqli_stmt_execute($stmt);
                            
                            move_uploaded_file($fileTempName, $fileDestination);
                            
                            header("Location: ../page-manage.php?upload=succes");
                            exit();
                        }
                    }
                }
                
                
            } else {
                $response['message'] = 'bestand is te groot!';
            }
            
        } else {
            $response['message'] = 'U heeft een error bij het uploaden van uw bestand!';
        }
    } else {
        $response['message'] = 'Om een bestand te uploaden moet het een PNG/JPEG/JPG bestand zijn!';
    }
        
} else {
    $response['message'] = 'Formulier velden zijn niet goed ingevuld!';
}

echo json_encode($response);


User generated imageUser generated imageUser generated imageUser generated image

OK. I'm a little surprised that your code works. Right at the start, you seem to be setting the filename to either true or false:

$newFileName = isset($_POST["page_img"]["name"]);

isset() will only ever return true or false. It's likely to be false because your page_img is part of the $_FILES array, not the $_POST array.

You've also still got the header() redirects in your file, which won't work as soon as you start implementing the AJAX calls. You need to get rid of them.

As for the YouTube Video ID, not sure I understand. How does that come into play in your code. And for the record, you don't make an AJAX call using PHP - you do that with Javascipt.
Avatar of B O

ASKER

hi there,
I use the videoId to set up a specified youtube video for the page.

I managed to  chenge the headers to a $response,

and got rid of the page_img if checkkpoint
But still no succes uploading to the database
Hey,

A little confused - in your previous post you indicated that you did have it updating the database. Is the database updating or not ?

If this is now working apart from the VideoID, then that's a different moving part and will need separate code. The PHP script you have above has nothing to do with getting an ID from YouTube. This is what I mean when I talk about working on one problem at a time.
Avatar of B O

ASKER

Hey,

Thank  you for your answer,
I am going to try and update the youtubeVideoId in a separate page.

I give an update when I have it working or face another problem.
No worries - like I've said before, the key to all of this is to identify the various moving parts of your application and code/test them individually. For the YouTube bit, you just need to write a script (maybe JS/AJAX, maybe PHP) that gets that VideoId and puts it into your page.
Avatar of B O

ASKER

Hi,

I have set up a separate page for the youtube video selection.
I indeed have a problem with selecting a video and inserting the videoId to the database.

I get a success response with no error from ajax or php.

I have removed all regular php headers and replaced them with a respone let that gives information back at a checkpoint. I also tried using isset for videoId but cant fiigure out why it is not inserting to the database.


<?php 
    include_once 'admin-nav.php';
    include_once 'admin-page-header.php';
    // require "includes/page.incl.php";
?>

<main class="my-5">
    
<div class="col-sm-10">
    <div class="container">
        <div class="align-self-center">
            <h1 class="font-weight-light text-center text-lg-left mt-4 mb-0">Upload pagina</h1>         
            <br>
            <form action=" " method="post" id="myYoutubeForm" enctype="multipart/form-data">
    
            <h3>Voeg een video toe</h3>
            <br>
            <input type="text" class="form-control" id="search" name="search" placeholder="type in gezochte video">
            <br>
            <div id="hide_video"><div id="name_video"></div></div>
            <br>
            <hr>
            <br>
            <h5 id="vidsAvailable">Videos beschikbaar</h5>
            <div class="row-xs-6 row-md-3">
                <div class="col">
                    <div id="result"></div>
                </div>
            </div>
            <br>
            <hr>
                <section class="form-group">        
                    <button type="submit" name="video_upload" class="submit">Video Uploaden</button>
                </section>
            </form>
        </div>
    </div>
</div>
</main>

<!-- admin-page-header -->
</div>
<!-- <script scrc="js/youtube_api.js"></script> -->
<!-- <script src="js/preview-image.js"></script> -->
<?php
    require 'footer.php';
?>


let data =  {videoId: videoId};

            $("#myYoutubeForm").on('submit', function(e){
                e.preventDefault();
                $.ajax({
                    url: '/blog-app/includes/postYoutubeVideo.incl.php'
                    type: "POST",
                    data: {videoId: videoId},
                    dataType: "text",
                    // cache: false,
                    // processData: false,
                    // contentType: false,
                    // beforesend: function() {
                    //     $('.submit').attr("disabled", "disabled");
                        // $('#page_img')[0].files, function(file) {
                        //     data.append('file-', file);
                        // };
                    // },
                    success: function(response){
                        console.log("success", response);
                        alert('response', response);
                        
                    },

                    error: function (e) {
                        alert('Something went wrong with uploading the data');
                        console.log("Unsuccessful:", e);
                    }
                });
       

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$response = array(
    'status' => 0,
    'message' => 'Form submission falied, please try again'
);

if (isset($_POST["video_upload"])) {

    $youtubeVideoId = $_POST["videoId"];
                    
        include_once "dbh.incl.php";
        
        if (empty($youtubeVideoId)) {
            // header("Location: ../page-manage.php?upload=emptyinput");
            $response['message'] = 'upload is empty!';
            exit();
        } else {
            $sql = "SELECT * FROM pages";
            $stmt = mysqli_stmt_init($conn);
            if (!mysqli_stmt_prepare($stmt, $sql)) {
                echo"SQL statement gefaald 1!";
            } else {
                mysqli_stmt_execute($stmt);
                $result = mysqli_stmt_get_result($stmt);
//                      $rowCount = mysqli_num_rows($result);
//                      $setImageOrder = $rowCount + 1;
                
                $sql = "INSERT INTO pages (youtubeVideoId) VALUES (?)";
                if (!mysqli_stmt_prepare($stmt, $sql)) {
                $response['message'] = 'SQL statement gefaald 2!';
                }
                else {
                    // bind 3 strings to statement
                    mysqli_stmt_bind_param($stmt, "s", $youtubeVideoId);
                    mysqli_stmt_execute($stmt);
                    // header("Location: ../page-manage.php?upload=succes");
                    $response['message'] = 'Succes! videoId' . $youtubeVideoId . ' updated';
                    exit();
                }
            }
        }
        
        
    } else {
        $response['message'] = 'geen video geselecteerd!/ No video recognized';
    }

        

User generated image
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of B O

ASKER

Excuse me I forgot to add that part

            let data =  {videoId: videoId};


             // check which button selected
             let videoId = "";




             $("button").on('click', function(){
                 videoId += $(this).val();
                 if (videoId){
                     $("#hide_video").show();
                     $("#name_video").text( videoId );
                 }
             })


            $("#myYoutubeForm").on('submit', function(e){
                e.preventDefault();
                $.ajax({
                    url: '/blog-app/includes/postYoutubeVideo.incl.php', 
                    type: "POST",
                    data: {videoId: videoId},
                    dataType: "text",
                    // cache: false,
                    // processData: false,
                    // contentType: false,
                    // beforesend: function() {
                    //     $('.submit').attr("disabled", "disabled");
                        // $('#page_img')[0].files, function(file) {
                        //     data.append('file-', file);
                        // };
                    // },
                    success: function(response){
                        console.log("success", response);
                        alert('response', response);
                        
                    },


                    error: function (e) {
                        alert('Something went wrong with uploading the data');
                        console.log("Unsuccessful:", e);
                    }
                });
                // alert(page_title + '<br>' + page_descr + '<br>' + page_img + '<br>' + videoId);
                // $.post("/blog-app/includes/page.incl.php",{data: data}, function(data, status){
                //     console.log(data);
                //     alert(data, status);
                // })           
            })



Open in new window

Avatar of B O

ASKER

Awesome it kind of worked,

I think I should use update and get the lastest post and it should work

What I did i have the first page where the user can make inputs like Title, text and img,
and after that the page switches to the youtubepost page where the user can select a video he likes

Thank you for the help, removing the isset worked

is it able to switch the page from either ajax or php, after the upload?

User generated image
OK. This question seems to be now covering a dozen different things and like I've said several times - you need to break your application down into it's compoent parts and deal with each part individually. You simply can't code an application by trying to do everything at once - it just work.

In the code you've just posted, you have several issues. First off, your first line is trying to use the videoId variable before you've declared it. Check your console - you'll see the errors.

Secondly, a <button> element doesn't have a value, so this code won't work:

$("button").on('click', function(){
    videoId += $(this).val();

Open in new window

Form fields have values ... buttons don't !

Also, you're assigning that click event to ALL buttons, so even your form's submit button will fire it off. Not what you want.

If I were you, I would take a step back from this, and try and identify the moving parts of your application. Then focus on them one-by-one. So start off with a very simple HTML form. Work on the YouTube VideoID bit. Get that working before moving on to database stuff. Juggling all the moing parts is not going to go well. Trust me on this :)
Avatar of B O

ASKER

Hi,

In my project I do have buttons with values :D,
I tried to be as creative as I could to get my vision turned to a reality

But on a sirious note, I was planning to clean my code up after I got a couple things set,
Not the best thing to do  Iknow

function youtubeApiCall(){
                $.ajax({
                    cache: false,
                    data: $.extend({
                        key: api_key,
                        q: $('#search').val(),
                        channelId: channel_Id,
                        part: 'snippet'
                    }, {
                        // maxResults: 10,
                        // pageToken: $("#pageToken").val()
                    }),
                    dataType: 'json',
                    type: 'GET',
                    timeout: 5000,
                    url: 'https://youtube.googleapis.com/youtube/v3/search?',
                    // method: "post",
                    // data: {data: JSON.stringfy( data)},
                }).done(function(data) {
                    // $('.btn-group').show();
                    if (typeof data.items[0] === 0) {
                        $("#result").hide();
                        alert('items in json not found')
                    } else {
                        $("#result").show();
                    }
                    // if (typeof data.nextPageToken === "undefined") {
                    //     $("#pageTokenNext").hide();
                    // } else {
                    //     $("#pageTokenNext").show();
                    // }
                    let items = data.items,
                        videoList = "";                        
                    // $("#pageTokenNext").val(data.nextPageToken);
                    // $("#pageTokenPrev").val(data.prevPageToken);
                    $.each(items, function(index, e) {
                        // videoList = videoList + '<li><div><a href="" class="hyv-content-link" title="' + e.snippet.title + '"><span class="title">' + e.snippet.title + '</span><span class="stat attribution">by <span>' + e.snippet.channelTitle + '</span></span></a></div><div class="hyv-thumb-wrapper"><a href="" class="hyv-thumb-link"><span class="hyv-simple-thumb-wrap"><img alt="' + e.snippet.title + '" src="' + e.snippet.thumbnails.default.url + '" width="120" height="90"></span></a></div></li>';
                    videoList += `<div class="my-2" >
                    <div>Title: ${e.snippet.title}</div>
                    <iframe src="https://www.youtube.com/embed/${e.id.videoId}"
                        class="ytVideo"
                        name="video-${e.id.videoId}"
                        width="400"
                        height="300"
                        allowfullscreen>
                    </iframe>
                    <br>                    
                    <button
                        type="button"
                        name=""
                        id="${e.id.videoId}"
                        value="${e.id.videoId}"
                    >select <i id="icon-${e.id.videoId}" class="fas fa-check-square"></i></button>
                    </div>`;                
                    });
                    $("#result").html(videoList);
                    // JSON Responce to display for user    
                    // new PrettyJSON.view.Node({
                    // el: $(".hyv-watch-sidebar-body"),
                    //     data: data
                    // });
                });
            }


Ha - of course buttons can have values. Sorry about that - I was obviously having a 'moment' :)

Yeah - trying to tidy code up 'after the fact' is always a struggle - much better to do the planning up-front. Makes for much cleaner, more robust code.

Right. The fact that you've got the YouTube part working is good news. The general approach I would take is that when a 'button' is clicked, that value of the videoId is written to a hidden input (called videoId) within your main form. Then when you submit the main form along with title, description, uploaded file etc, then you'll also receive the videoId and your original PHP script will handle all of it.
Avatar of B O

ASKER

Thank you all for your help
I got it figured out now

User generated image