I am trying to figure out how to send back a value to the Ajax popup box. Currently, the value that gets returned is just the JSON that comes back from the API call. I would much rather use jsondecode to pull out a specific value and have that return, or... lets not even get that complex. I just want to set a variable equal to some message such as "API GET complete" and return that to the Ajax box. This will also help with troubleshooting so I can return a variable to see if things are working. As I said, currently the Ajax popup just displays the JSON that comes back from the API call. This is my first time working with both Ajax and curl_setopt so if you can please make recommendations with examples, that would be fantastic! Thank you!
test.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'auto.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
alert(response);
});
});
});
</script>
</head>
<body>
<input type="submit" class="button" name="test" value="Test" />
</body>
</html>
auto.php
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'Test':
Test();
break;
case 'to_the_n':
to_the_n();
break;
}
}
function Test() {
$ch = curl_init('https://api.digitalocean.com/v2/droplets?tag_name=MYTAG');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer MYTOKEN','Content-Type: application/json'));
$result = curl_exec($ch);
$message = "Yay it worked" //Send this message back to Ajax popup, not the API reply
exit;
}
?>
* UPDATE *
* UPDATE *
You can just echo the value from php and it will be alerted in the Ajax success function.
echo 'Yay it worked!! ';
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'Test':
if(Test() == true) {
echo('yay it worked!! ');
exit;
}
break;
case 'to_the_n':
to_the_n();
break;
}
}
function Test() {
$ch = curl_init('https://api.digitalocean.com/v2/droplets?tag_name=MYTAG');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer MYTOKEN','Content-Type: application/json'));
$result = curl_exec($ch);
return true;
}
?>
Related
I have the code from below, once the form is sended I want to check in it if the user passed the recaptcha test. How do i do it? Searched many things and i can't find a way that works for me ..
<html>
<head>
<script type="text/javascript">
var verifyCallback = function(response) {
alert(response);
};
var onloadCallback = function() {
grecaptcha.render('example3', {
'sitekey' : '6LdlRIgaAAAAAJXOu3EsuGVnKVjmSaWfSbuwSHLI',
'callback' : verifyCallback,
'theme' : 'dark'
});
};
</script>
</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
// here I want to verify if the use user passed the recaptcha
{
some code
}
}
?>
<form method="POST">
<div id="example3"></div>
<br>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
</body>
</html>
You should lookup the Server side validation docs for reCAPTCHA:
https://developers.google.com/recaptcha/docs/verify
You have to send an API request via PHP CURL, as stated in the docs:
URL: https://www.google.com/recaptcha/api/siteverify METHOD: POST
So something like this:
function validate_captcha($secret, $response, $remoteip) {
$captcha_url = "https://www.google.com/recaptcha/api/siteverify";
$captcha_url .= "?secret=".$secret;
$captcha_url .= "&response=".$response;
$captcha_url .= "&remoteip=".$remoteip;
$ch = curl_init($captcha_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$response=json_decode($data,true);
if ($response["success"]) {
return true;
}
else {
return false;
}
}
And you call the function like this:
$captcha_is_ok = validate_captcha(
"......mySecret.....",
$_POST['g-recaptcha-response'],
$_SERVER['REMOTE_ADDR']);
if ($captcha_is_ok) {
... do something cool ...
} else {
... don't do something cool ...
}
When I open update.php on its own (with self supplied test vars), it sends the SSE to testsse.php just fine and there are no issues (Everything I need to be printed is showing up in inspect element), However, I am trying to have POST data from another page (In this case mootssetest.php) get received by update.php so it may send out the SSE containing the data. I am not sure what I am doing wrong, but this test rig is not working. Guidance would be appreciated.
testsse.php (front end page meant to receive SSE and print)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Using Server-Sent Events</title>
<script>
window.onload = function() {
var link = new EventSource("update.php");
var antispam;
var inputthing = event.data;
var splitted;
link.onmessage = function(event) {
inputthing = event.data;
splitted = inputthing.split(" ");
if (splitted[0] != antispam && splitted[1] == <?php echo $page; ?>) {
document.getElementById("livemsg").innerHTML += "<div id=\"post-" + splitted[0] + "\" class=\"reply\">" + "</div>";
antispam = splitted[0];
};
};
};
</script>
</head>
<body>
<div id="livemsg">
<!--Server response will be inserted here-->
</div>
</body>
</html>
update.php (SSE sender, post receiver)
<?php
$data = json_decode(file_get_contents('php://input'), true);
$postnum = $data[0];
$bread = $data[1];
postnum = 32;
bread = 4;
function liveupdate($postnum, $bread)
{
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
echo "data: " . $postnum . " " . $bread . "\n\n";
flush();
}
liveupdate($postnum, $bread);
?>
mootssetest.php (POST sender)
function httppost($postnum, $bread)
{
$url = "http://localhost/update.php";
$data = array($postnum, $bread);
$curl = curl_init($url);
$jsondata = json_encode($data);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $jsondata );
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
httppost(420, 4);
?>
(For context, I am trying to have this print a new post in some forum software every time a function is called without refreshing the page for the user)
you haven't included the event in your window.onload() function, please fix it first and try again.
I have been stuck on this for over a week and I think I am long overdue for asking on here.. I am trying to get my users to upload their video files using the jQuery File Upload Plugin. We do not want to save the file on our server. The final result is having the file saved in our Backlot using the Ooyala API. I have tried various approaches and I am successful in creating the asset in Backlot and getting my upload URLs, but I do not know how to upload the file chunks using the URLs into Backlot. I have tried FileReader(), FormData(), etc. I am pasting the last code I had that created the asset, and gave me the upload URLs, but did not save any chunks into Backlot. I assume I may be getting stuck in one of my AJAX calls, but I am not very sure.
I keep getting:
Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable.
Here is my page with the JS for the jQuery File Upload widget by BlueImp:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="<?php print base_path() . path_to_theme() ?>/res/js/jQuery-File-Upload/js/vendor/jquery.ui.widget.js"></script>
<script type="text/javascript" src="<?php print base_path() . path_to_theme() ?>/res/js/jQuery-File-Upload/js/jquery.iframe-transport.js"></script>
<script type="text/javascript" src="<?php print base_path() . path_to_theme() ?>/res/js/jQuery-File-Upload/js/jquery.fileupload.js"></script>
</head>
<body>
<input id="fileupload" type="file" accept="video/*">
<script>
//var reader = FileReader();
var blob;
$('#fileupload').fileupload({
forceIframeTransport: true,
maxChunkSize: 500000,
type: 'POST',
add: function (e, data) {
var goUpload = true;
var ext = ['avi','flv','mkv','mov','mp4','mpg','ogm','ogv','rm','wma','wmv'];
var uploadFile = data.files[0];
var fileName = uploadFile.name;
var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
if ($.inArray( fileExtension, ext ) == -1) {
alert('You must upload a video file only');
goUpload = false;
}
if (goUpload == true) {
$.post('../sites/all/themes/episcopal/parseUploadJSON.php', 'json=' + JSON.stringify(data.files[0]), function (result) {
var returnJSON = $.parseJSON(result);
data.filechunk = data.files[0].slice(0, 500000);
data.url = returnJSON[0];
//reader.onloadend = function(e) {
//if (e.target.readyState == FileReader.DONE) { // DONE == 2
//data.url = returnJSON[0];
// }
//}
//$.each(returnJSON, function(i, item) {
//data.url = returnJSON[0];
//blob = data.files[0].slice(0, 500000);
//console.log(blob);
//reader.readAsArrayBuffer(blob);
//data.submit();
//});
data.submit();
});
}
},//end add
submit: function (e, data) {
console.log(data); //Seems fine
//console.log($.active);
$.post('../sites/all/themes/episcopal/curlTransfer.php', data, function (result) { //fails
console.log(result);
});
return false;
}
});
</script>
</body></html>
Then there is the parseUploadJSON.php code, please keep in mind that my real code has the right Backlot keys. I am sure of this:
<?php
if(isset($_POST['json'])){
include_once('OoyalaAPI.php');
$OoyalaObj = new OoyalaApi("key", "secret",array("baseUrl"=>"https://api.ooyala.com"));
$expires = time()+15*60; //Adding 15 minutes in seconds to the current time
$file = json_decode($_POST['json']);
$responseBody = array("name" => $file->name,"file_name"=> $file->name,"asset_type" => "video","file_size" => $file->size,"chunk_size" => 500000);
$response = $OoyalaObj->post("/v2/assets",$responseBody);
$upload_urls = $OoyalaObj->get("/v2/assets/".$response->embed_code."/uploading_urls");
$url_json_string = "{";
foreach($upload_urls as $key => $url){
if($key+1 != count($upload_urls)){
$url_json_string .= '"' . $key . '":"' . $url . '",';
}else {
$url_json_string .= '"' . $key . '":"' . $url . '"';
}
}
$url_json_string .= "}";
echo $url_json_string;
}
?>
Then I have the curlTransfer.php:
<?php
echo "starting curl transfer";
echo $_POST['filechunk'] . " is the blob";
if(isset($_FILES['filechunk']) && isset($_POST['url'])){
echo "first test passed";
$url = $_POST['url'];
//print_r(file_get_contents($_FILES['filechunk']));
$content = file_get_contents($_FILES['filechunk']);
print_r($content);
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: multipart/mixed"));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
try {
//echo 'success';
return httpRequest($ch);
}catch (Exception $e){
throw $e;
}
}
/****Code from Ooyala****/
function httpRequest($ch){
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
if(curl_error($ch)){
curl_close($ch);
return curl_error($ch);
}
$head=curl_getinfo($ch);
$content = $head["content_type"];
$code = $head["http_code"];
curl_close($ch);
}
?>
And the OoyalaApi.php is here (I saved a copy on my server):
https://github.com/ooyala/php-v2-sdk/blob/master/OoyalaApi.php
I apologize in advance if the code is messy and there's a lot of parts commented out. I have changed this code so much and I cannot get it. I appreciate all of your time and effort.
EDIT
I went back to trying FileReader out as this post Send ArrayBuffer with other string in one Ajax call through jQuery kinda worked for me, but I think it would be safer to read it using readAsArrayBuffer and now I am having trouble saving the array buffer chunks in some sort of array...
We have implemented ooyala file chunk upload in Ruby On Rails by referring this.
We have used the entire JS file as it is from this link.
https://github.com/ooyala/backlot-ingestion-library
I'm using CURL to scrape a website like this:
<?php
$url = "http://www.bbc.com/news/";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curl_scraped_page = curl_exec($ch);
curl_close($ch);
$curl_scraped_page = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#",'$1http://www.bbc.com/news/$2$3', $curl_scraped_page);
echo $curl_scraped_page;
?>
As you can see the URL is set for BBC news. However, I would like the URL to be a variable instead. The variable would have to be the value of parent.document. In JQuery for example I would do this:
var value = $("input", parent.document.body).val();
How do I set something like that in PHP? I have Googled but I couldn't find anything about parent.document in PHP.
PHP is a server-side scripting language and therefore has no access to the current HTML page. It is processed before the HTML is sent to the client's browser, therefore parent.document doesn't even exist at the time the script is being processed.
If you would like to pass data from an HTML page to a PHP script, you can do so using an HTML <form> or through JavaScript/JQuery AJAX requests.
For example, the following code will pass the value of input to the PHP script:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function pass(){
var value = $("input", parent.document.body).val();
$.ajax({
type: "POST",
url: "myscript.php",
data: { mydata: value }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>
</head>
<body>
<input type="text" />
<button onclick="pass();return false;">Pass Value</button>
</body>
</html>
And the revised script (myscript.php):
<?php
$url = isset($_POST['mydata']) ? $_POST['mydata'] : '';
$curl_scraped_page = '';
if(!empty($url)){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curl_scraped_page = curl_exec($ch);
curl_close($ch);
$curl_scraped_page = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#",'$1'.$url.'$2$3', $curl_scraped_page);
}
echo $curl_scraped_page;
?>
I would recommend using $(id) to retrieve the value of an <input> instead of $("input",context).
E.g.
var value = $('#txt').val();
And in the HTML:
<input type="text" id="txt" />
For more info on JQuery.ajax see here.
here i am supposed to call a web service in php and the return json of the web service is stored in a variable called $response,then i am passing that json to javascript ,here i am parsing the json and depending on the type of the employee and each type have differebt attributes i am alerting all ,when i have did the same function in another page for testing it was working where i have given value to var txt='' by hardcoding , when i have integrated the php web service with the one i havew tried nothing is having ,i am confused there is no error showing with javascript console.
<?php
session_start();
$regid=$_SESSION['product_registration_id'];
//echo $regid;
$details=array(
'product_registration_id'=> "$regid");
//coverting the vlaues collected from form into json
//calling the web service
$url='webservice url';
$data=$details;
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($details));
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
$response= curl_exec($ch);
echo ("The Server Response is:" .$response);
curl_close($ch);
json_decode($response);
$json_a=json_decode($response,true);
echo $json_a[expired];
echo $json_a[account_detail][0];
?>
</div>
<script>
var txt = '<?php echo $response ?>';
alert(txt);
//var jsonData = eval ("(" + txt + ")");
var jsonData = JSON.parse(txt);
for (var i = 0; i < jsonData.employees.length; i++) {
var counter = jsonData.employees[i];
//console.log(counter.counter_name);
alert(counter.type);
if(counter.type=="0")
{
alert(counter.building_name);
alert(counter.org_name);
alert(counter.user_name);
alert(counter.name);
alert(counter.loc_name);
alert(counter.email_id);
alert(counter.password);
}
if(counter.type=="1")
{
alert(counter.user_name);
alert(counter.name);
alert(counter.password);
alert(counter.email_id);
}
if(counter.type=="2")
{
alert(counter.building_name);
alert(counter.org_name);
alert(counter.user_name);
alert(counter.opr_code);
alert(counter.name);
alert(counter.loc_name);
alert(counter.email_id);
alert(counter.password);
}
if(counter.type=="3")
{
alert(counter.building_name);
alert(counter.org_name);
alert(counter.machine_type);
alert(counter.activate_status);
alert(counter.machine_name);
alert(counter.entrance_exit_name);
alert(counter.entrance_or_exit);
alert(counter.loc_name);
alert(counter.activation_code);
}
}
</script>
if you want the php array to be an array in javascript you must:
<?php echo json_encode($response) ?>
this does not need to be parsed in javascript, it will already be an array because the echo will return something in the likings of {'message': 'hellew world'} of ['value1','value2'] which in javascript is an array or an object definition.
So remove the parsing in javascript.
If response contains a quote you will get a js syntax error. Nothing from there on will be processed. So... no alerts. Check the response. Escape the quotes.