Ajax request in YouTube API browser-based upload - ajax

I'd like to upload a YouTube video using ajax requests. The following script is used to create a form in order to upload a video to YouTube:
function createUploadForm($videoTitle, $videoDescription, $videoCategory, $videoTags, $nextUrl = null)
{
$httpClient = getAuthSubHttpClient();
$youTubeService = new Zend_Gdata_YouTube($httpClient);
$newVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
$newVideoEntry->setVideoTitle($videoTitle);
$newVideoEntry->setVideoDescription($videoDescription);
//make sure first character in category is capitalized
$videoCategory = strtoupper(substr($videoCategory, 0, 1))
. substr($videoCategory, 1);
$newVideoEntry->setVideoCategory($videoCategory);
// convert videoTags from whitespace separated into comma separated
$videoTagsArray = explode(' ', trim($videoTags));
$newVideoEntry->setVideoTags(implode(', ', $videoTagsArray));
$tokenHandlerUrl = 'http://gdata.youtube.com/action/GetUploadToken';
try {
$tokenArray = $youTubeService->getFormUploadToken($newVideoEntry, $tokenHandlerUrl);
if (loggingEnabled()) {
logMessage($httpClient->getLastRequest(), 'request');
logMessage($httpClient->getLastResponse()->getBody(), 'response');
}
} catch (Zend_Gdata_App_HttpException $httpException) {
print 'ERROR ' . $httpException->getMessage()
. ' HTTP details<br /><textarea cols="100" rows="20">'
. $httpException->getRawResponseBody()
. '</textarea><br />'
. '<a href="session_details.php">'
. 'click here to view details of last request</a><br />';
return;
} catch (Zend_Gdata_App_Exception $e) {
print 'ERROR - Could not retrieve token for syndicated upload. '
. $e->getMessage()
. '<br /><a href="session_details.php">'
. 'click here to view details of last request</a><br />';
return;
}
$tokenValue = $tokenArray['token'];
$postUrl = $tokenArray['url'];
// place to redirect user after upload
if (!$nextUrl) {
$nextUrl = $_SESSION['homeUrl'];
}
print <<< END
<br /><form id="ajaxform" action="${postUrl}?nexturl=${nextUrl}"
method="post" enctype="multipart/form-data">
<input name="file" type="file"/>
<input name="token" type="hidden" value="${tokenValue}"/>
<input value="Upload Video File" type="submit" />
</form>
END;
}
At the end, a form is created using action="${postUrl}?nexturl=${nextUrl} which tells to YouTube to redirect the browser after the uploading has been completed. When the user is redirected, to nextUrl, two variables are passed with the URL (the status of the uploaded video and an ID for that video). I don't want a page reload but it seems that nextUrl is mandatory. Furthermore, I want to be able to get that ID for further use.
Is it possible to change the behavior of that automatic redirection and to pass those values in any other way?
Thanks

Related

Having issues submitting form via AJAX on WordPress with reCAPTCHA

I've spent a good few hours trying to Google my way out of this, and I keep coming up with one issue or another. I'm getting myself wrapped up in knots and I am hoping that someone can help me by giving me a metaphorical slap around the face and showing me how the hell to do this properly.
Ok ... so I have a page on my front end that is inserted by a shortcode. This form is essentially a sort of AMA (Ask Me Anything) form, which I am using to create posts in my Admin area. Visitors enter their question, name and email, and submit the form to me via AJAX. The submissions are saved into the WordPress database under an ama custom post type, and an email is sent to me via wp_mail because I have an SMTP plugin installed that routes all requests for wp_mail through there. I have CMB2 installed on my website, and have keys for reCAPTCHA saved there.
So far, so good.
I had a working form with CMB2 fields, but CMB2 doesn't seem to support reCAPTCHA (otherwise it worked fine). So I decided to start from scratch and write my own form since it was just three fields that I wanted to submit. What could possibly go wrong, right?
Here's my Franken-code.
<?php
function ccdClient_shortcode_amaForm( $atts ) {
// Parse attributes
$atts = ( shortcode_atts( array(
'id' => uniqid('ccdClient_amaForm_'),
), $atts, 'ama_form' ) );
$rcKey = cmb2_get_option( 'ccdtheme_settings_apikeys', '_ccdclient_themesettings_apikeys_captcha_sitekey' );
$form = '
<form id="' . $atts['id'] . '" name="' . $atts['id'] . '" method="post" action="">
<div class="amaError"></div>
<div class="amaForm-field-question amaForm-field">
<p><label for="question">Your Question</label></p>
<p><textarea id="question" name="question" tabindex="1"></textarea></p>
</div>
<div class="amaForm-fieldGroup amaForm-groupTwo">
<div class="amaForm-field-name amaForm-field">
<p><label for="name">Your Name</label></p>
<p><input type="text" id="name" name="name" tabindex="2" /></p>
</div>
<div class="amaForm-field-email amaForm-field">
<p><label for="email">Your Email</label></p>
<p><input type="email" id="email" name="email" tabindex="3" /></p>
</div>
</div>
<div class="amaForm-fieldGroup amaForm-groupTwo">
<div class="amaForm-field-recaptcha amaForm-field amaForm-recaptcha">
<div class="g-recaptcha" data-sitekey="' . $rcKey . '"></div>
</div>
<div class="amaForm-field-submit amaForm-field amaForm-submit">
<input type="submit" value="Publish" id="submit" name="submit" />
</div>
</div>
</form>
<script>
$(document).ready(function() {
// Get form
var amaForm = $("#' . $atts['id'] . '");
// Get messages div
var amaError = $("#' . $atts['id'] . ' .amaError");
// Set data
var amaData = { "action" : "ama_form_process"}
var options = {
url: "'. admin_url( 'admin-ajax.php' ) .'",
type: "post",
dataType: "json",
data: amaData,
success : function(responseText, statusText, xhr, $form) {
$(amaError).html("Your form has been submitted successfully");
},
};
//Set submit function
amaForm.on("submit", function(e) {
//Prevent default form behavior
e.preventDefault();
// Serialise form data
//Post via AJAX
$.ajax(options)
.done(function(response) {
// Make sure that the amaError div has the "success" class.
$(amaError).removeClass("error");
$(amaError).addClass("success");
// Set the message text.
$(amaError).text(response);
})
.fail(function(data) {
// Make sure that the amaError div has the "error" class.
$(amaError).removeClass("success");
$(amaError).addClass("error");
// Set the message text.
if (data.responseText !== "") {
$(amaError).text(data.responseText);
} else {
$(amaError).text("Oops! An error occured, and your message could not be sent.");
}
});
});
});
</script>';
return $form;
}
add_shortcode('ama_form', 'ccdClient_shortcode_amaForm');
function ama_form_process() {
// If the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Include WordPress files
include_once '../../../../../wp-includes/wp-load.php';
// Set reCaptcha private key
$recaptchaKey = cmb2_get_option( 'ccdtheme_settings_apikeys', '_ccdclient_themesettings_apikeys_captcha_secretkey' );
// If the Google Recaptcha box was clicked
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
$captcha = $_POST['g-recaptcha-response'];
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . $recaptchaKey . "&response=" . $captcha);
$obj = json_decode($response);
// If the Google Recaptcha check was successful
if($obj->success == true) {
$question = strip_tags( trim( $_POST['question'] ) );
$name = strip_tags( trim( $_POST["name"] ) );
$name = str_replace( array("\r","\n"), array(" "," "), $name);
$email = filter_var( trim( $_POST["email"] ), FILTER_SANITIZE_EMAIL );
if ( !$name || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Add the content of the form to $post as an array
$post = array(
'post_title' => $question,
'post_status' => 'pending', // Could be: publish
'post_type' => 'ama', // Could be: `page` or your CPT
'meta_input' => array(
'_ccdclient_ama_name' => $name,
'_ccdclient_ama_email' => $email,
),
);
wp_insert_post($post);
echo 'Saved your post successfully! :)';
$recipient = get_option('admin_email');
$subject = "New question from $name";
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$question\n";
$email_headers = "From: $name <$email>";
wp_mail( $recipient, $subject, $email_content, $email_headers );
}
// If the Google Recaptcha check was not successful
else {
echo "Robot verification failed. Please try again. Success:" . $response;
}
}
// If the Google Recaptcha box was not clicked
else {
echo "Please click the reCAPTCHA box.";
}
}
// If the form was not submitted
// Not a POST request, set a 403 (forbidden) response code.
else {
echo "There was a problem with your submission, please try again.";
}
}
add_action("wp_ajax_ama_form_process", "ama_form_process");
//use this version for if you want the callback to work for users who are not logged in
add_action("wp_ajax_nopriv_ama_form_process", "ama_form_process");
As you can guess, I have looked at about a dozen or so pages and combined the efforts of each of them, thus overwriting parts that would perhaps have worked and confused myself no end, and so am resorting to here to preserve what is left of my sanity.
EDIT: Apologies. Whilst I copied the code, I wasn't specific on what issues I was facing. Goes to show the extent I was frustrated.
I have had a number of issues with this code. Currently, when I submit the form, it keeps the same URL but returns a 404 error page. However, it has previously told me that it cannot recognise functions - and therefore couldn't run - such as cmb2_get_option (which is a modification of get_option that specifically works with CMB2 options pages) and wp_insert_post. The latter error (ie: wp_insert_post) came up when the secret key was hard-coded into the script and not called from the get_option function.

Adding button to controlgroup dynamically on every list item takes too long jquery mobile

I am quite new to jquery mobile so this might be a trivial question. The fact that documentation is not centralized for jquery mobile is making me post this on stackoverflow.
Currently, I am trying to load a listview and every item of the listview has the following structure. The options button is a controlgroup button with variable number of buttons below it, again received from the JSON.
Currently there are about 250 objects and they are obtained from the server over an 85 KB JSON. Due to the dynamic nature of the content caching data is a bit tricky.
I am running into a problem wherein its taking almost 15 seconds to load this page. To find out the reason causing it I added timestamp values within the for loops that create the list items dynamically.
Interestingly the main bottleneck - which is upto 12 out of the 14 seconds is taken while creating the HTML for the controlgroup.
Here is an image of the options button to give you an idea about the HTML
I am keen to know why rendering dynamic control groups on list items is causing so much delay. I do not know how to cache the controlgroup since, the grouped buttons are also dynamic and are received from the JSON.
<
I look forward to your feedback on this,
Thanks
Rajat
EDIT Code Snippet Added. I use this routine to generate every list item
foreach ($jsonArray AS $item) {
Show the adapter
echo '<li>';
if($item['reactionCount'] > 0) {
echo ' <a href="/planner/reactionbox/id:'. $item['jobId'] . '">';
if(isset($item['requiresAction'])) {
echo ' <span class="ui-li-count redBubble" style="background:#088A08"> </span>';
} else {
echo ' <span class="ui-li-count redBubble" style="background:#6E6E6E"> </span>';
}
} else {
echo ' <a href="/planner/job-details/id:'. $item['jobId'] .'" name=\"job' . $item['jobId'] . '\">';
}
echo '<img style="float:left; padding: 11px 0px 0px 11px; width: 66px; vertical-align:middle;"
src="' . (($item['imageUrl'] != '') ? $item['imageUrl'] : '/img/website/profilephotodummy.png') . '" alt="dummyphoto" />
<h3>' . $item['firstLine'] . '</h3>
<p><strong>' . $item['secondLine'] . '</strong></p>
<p>' . $item['thirdLine'] . '</p>
<p class="ui-li-aside"><strong>' . $item['optionalLine'] . '</strong></p>
</a>';
if(isset($item['actions'])) {
echo '<div data-role="controlgroup" data-type="horizontal" style="margin-left: 15px;" data-mini="true">
<select data-native-menu="false" data-theme="b" data-inline="true" data-mini="true" data-icon="gear" onchange="doJobAction(\'' . $currentUrl . '/\'+this.value); this.selectedIndex=0;">
<option>' . __d('website','opties',true) . '';
foreach ($item['actions'] AS $value) {
# for every action from the JSON generate an action button dynamically ...
if($value == 'annuleer_opdracht') {
echo '<option value=" ' . $currentUrl . '/cancelJob:' . $flexbox['jobId'] . ' ">annuleer</option>';
} else if($value == 'zoek_opnieuw') {
echo '<option value="' . $currentUrl . '/newSearchJob:' . $flexbox['jobId'] . '">zoek opnieuw</option>';
} else if($value == 'publiceer_externe') {
echo '<option value="' . $currentUrl . '/openForFreelancer:' . $flexbox['jobId'] . '">publiceer externe</option>';
}
}
echo '</option></select></div>';
}
echo '</li>';
}

add submit to delete comment using ajax , php

Hi, I use a php code to view the all comments to any post from my sql and I want to add a submit button to every comment in order to delete it without refreshing the page, I mean using AJAX i don't know how to write that codes and connect it with html codes i want add submit like this :
<form>
<input type="submit" id="deletecomment">
</form>
and connected it with AJAX and delete.php page to delete the comment (ajax,delete.php)???????
this is my codes
$result = mysql_query ("select * from post_comments WHERE link ='$getlink' order by link asc");
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$link = $row['link'];
$time = $row['time'];
$content = nl2br($row['content']);
$name = ($row['link'] != '') ? '<h3 style="color:blue">'.$row['name'].'</h3>' : $row['name'];
$imge = $row['imge'];
echo '
<div class="commentuserbackground">
<img src="'.$imge.'" width="30px" height="30px">
<div id="comment-'.$id.'" class="username1">'.$name.'</div>
<div class="username2">'.$content.'</div><div class="commenttime"><h4 style="color:#5a5a5a">'.$time.'</h4>
</div></div>';
}
If you already have the jquery lib included in your html, you could do something like this:
# html page
<button data-id="1" class="delete_comment" /> # no need to wrap in form
# At the bottom of the body tag
$(".delete_comment").click(function(e){
e.preventDefault();
var $button = $(this), $comment = $button.parent(), id = $button.data("id");
$.ajax({
type: 'DELETE',
url: "/path/to/comment/" + id,
success: function(){ $comment.remove(); }
});
});

Ajax and output pdf file are not working together

I have a file named download.php and call getpdf function inside it.
I call download.php via ajax to download pdf file when users click download button. but nothing happend and no download window appears. I checked it in firebug Net tab and download.php are requested on click event. Its size also changes that shows the file is reading from its location,but no download window.
Here's getpdf code:
function getpdf($id) {
header('Content-Type: application/pdf');
readfile('/san/theo-books/PDFs/'.$id.'.pdf');
exit;
}
And here's download.php code:
$pdf_id = $_POST('pdi');
echo getpdf($pdf_id);
What is the problem? Would you help me?
Here is the full postback version. It's not using the jQuery Ajax, because Popup download window needs the full postback:
<a id="pdf-10" href="#">PDF Export</a>
$(document).ready(function () {
$('a[id^="pdf"]').click(function (event) {
event.preventDefault();
var pdfExportPath = "/san/theo-books/PDFs/";
var $a = $(this);
var postId = $a.attr('id').replace("pdf-","");
var form = $('<form action="' + pdfExportPath + '" name="pdf' + postId + '" id="pdf' + postId + '" method="POST"> <input id="id" name="id" type="hidden" value="' + postId + '" /></form>');
$(form).appendTo('body');
form.submit();
});
});

filename and contenttype of upload image

how to get the name of the file and the content type of the image which we uploaded in mvc application please tell me its urgent
thanks
ritz
May be below code will be helpful..
//index..
<?php
require_once("include/DBConnect.php");
include_once('header.php');
?>
<div align="center">
<h1 style="color:red">Welcome </h1>
<br/>
<form action="upload.php" method="post" enctype="multipart/form-data" id="UploadForm">
<input name="ImageFile" type="file" />
<input type="submit" id="SubmitButton" value="Upload" />
</form>
</div>
<?php include_once('footer.php');?>
//upload
<?php
require_once("include/DBConnect.php");
require_once("include/FunctionGeneral.php");
include_once('header.php');
if(isset($_POST))
{
$ThumbSquareSize = 200; //Thumbnail will be 200x200
$BigImageMaxSize = 500; //Image Maximum height or width
$ThumbPrefix = "thumb_"; //Normal thumb Prefix
$DestinationDirectory = 'uploads/'; //Upload Directory ends with / (slash)
$Quality = 90;
// check $_FILES['ImageFile'] array is not empty
if(!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name']))
{
die('Something went wrong with Upload!'); // output error .
}
// Random number for both file, will be added after image name
$RandomNumber = rand(0, 9999999999);
// Elements (values) of $_FILES['ImageFile'] array
//let's access these values by using their index position
$ImageName = str_replace(' ','-',strtolower($_FILES['ImageFile']['name']));
$ImageSize = $_FILES['ImageFile']['size']; // Obtain original image size
$TempSrc = $_FILES['ImageFile']['tmp_name']; // Tmp name of image file stored in PHP tmp folder
$ImageType = $_FILES['ImageFile']['type']; //Obtain file type, returns "image/png", image/jpeg, text/plain etc.
switch(strtolower($ImageType))
{
case 'image/png':
$CreatedImage = imagecreatefrompng($_FILES['ImageFile']['tmp_name']);
break;
case 'image/gif':
$CreatedImage = imagecreatefromgif($_FILES['ImageFile']['tmp_name']);
break;
case 'image/jpeg':
case 'image/pjpeg':
$CreatedImage = imagecreatefromjpeg($_FILES['ImageFile']['tmp_name']);
break;
default:
die('Unsupported File!'); //output error and exit
}
//PHP getimagesize() function returns height-width from image file stored in PHP tmp folder.
list($CurWidth,$CurHeight)=getimagesize($TempSrc);
//Get file extension from Image name, this will be re-added after random name
$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.','',$ImageExt);
//remove extension from filename
$ImageName = preg_replace("/\\.[^.\\s]{3,4}$/", "", $ImageName);
//Construct a new image name (with random number added) for our new image.
$NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt;
//set the Destination Image
$thumb_DestRandImageName = $DestinationDirectory.'thumbnail/'.$ThumbPrefix.$NewImageName; //Thumb name
$DestRandImageName = $DestinationDirectory.$NewImageName; //Name for Big Image
//Resize image to our Specified Size by calling resizeImage function.
if(resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType))
{
//Create a square Thumbnail right after, this time we are using cropImage() function
if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType))
{
echo 'Error Creating thumbnail';
}
/*
At this point we have succesfully resized and created thumbnail image
We can render image to user's browser or store information in the database
For demo, we are going to output results on browser.
*/
echo '<div id="output">';
echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
echo '<tr>';
echo '<td align="center"><img src="'.$thumb_DestRandImageName.'" alt="Thumbnail"></td>';
echo '</tr><tr>';
echo '<td align="center"><img src="'.$DestRandImageName.'" alt="Resized Image"></td>';
echo '</tr>';
echo '</table>';
echo '</div>';
/*
// Insert info into database table!
mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath)
VALUES ($DestRandImageName, $thumb_DestRandImageName, 'uploads/')");
*/
$added = getCurDate();
$title = "test";//$dbObj->escape_special_char($_POST['title']);
session_start();
$_SESSION['user_id'] = "rakhi";
$user_id = $_SESSION['user_id'];
$fields = "`photo_title` ,`createuser` ,`image_name` ,`added`";
$values = "'$title','$user_id','$NewImageName','$added'";
}else{
die('Resize Error'); //output error
}
}
include_once('footer.php');
?>

Resources