Semantic-UI search does not read JSON from server response - javascript

I'm currently using Semantic-UI in a project. I use the search module to get the results from input. Here's my JavaScript code:
$('.ui.search')
.search({
apiSettings: {
action: 'search',
url: 'process.php?q={query}',
onSuccess(response, element, xhr){
console.log(response);
}
},
fields: {
results: 'songs', // array of results (standard)
title: 'title', // result title
url: 'videoID'
},
showNoResults: true,
onResults(response) {
console.log(response);
}
})
;
I get the JSON response from process.php. Here it is:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header("Content-Type: application/json; charset=UTF-8");
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
// This code will execute if the user entered a search query in the form
// and submitted the form. Otherwise, the page displays the form above.
$videos = array();
// $videos["action"]["url"] = "youtube.com";
if (isset($_GET['q'])) {
/*
* Set $DEVELOPER_KEY to the "API key" value from the "Access" tab of the
* {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
* Please ensure that you have enabled the YouTube Data API for your project.
*/
$DEVELOPER_KEY = 'MY_API_KEY';
$client = new Google_Client();
$client->setDeveloperKey($DEVELOPER_KEY);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
try {
// Call the search.list method to retrieve results matching the specified
// query term.
$searchResponse = $youtube->search->listSearch('id,snippet', array(
'q' => $_GET['q'],
'maxResults' => 2
));
// Add each result to the appropriate list, and then display the lists of
// matching videos, channels, and playlists.
foreach ($searchResponse['items'] as $searchResult) {
switch ($searchResult['id']['kind']) {
case 'youtube#video':
$videos["songs"][] = array('title' => $searchResult['snippet']['title'], 'videoID' => $searchResult["id"]["videoId"]);
break;
}
}
} catch (Google_Service_Exception $e) {
die($e->getMessage());
}
}
echo json_encode($videos);
The problem is that once I start typing in the search input, nothing shows up, even though my JSON structure is valid. I have assigned the Semantic UI properties correctly. I'm following the standard JSON response that Semantic UI has suggested. Here's my JSON response
{
"songs":[
{
"title":"Wiz Khalifa - See You Again ft. Charlie Puth [Official Video] Furious 7 Soundtrack",
"videoID":"RgKAFK5djSk"
},
{
"title":"Wiz Khalifa - See You Again ft. Charlie Puth (MattyBRaps ft Carissa Adee Cover)",
"videoID":"Rpm8ZJuGEu4"
}
]
}
I've tried everything. It doesn't work. I would really appreciate your help

Related

how to implement resumable large file upload in javascript and laravel

I am trying to implement large file upload with resumable.js and laravel-chunk-upload. Everything is working fine, that is I am able to upload large files properly but the problem is, if anything happens to network connection while uploading, then the uploads is not completing properly. one chunk gets error. the error is:
"message": "fopen(H:\\Codinoz\\Development\\File ECommerce\\digital-product-shopping\\storage\\app\\products/27-09-2021 CMF 20-21 before_166b6fa4934428d2952877c84bed0ef2.): Failed to open stream: Permission denied",
There is no permission problems, because the same function is working properly when there is no network problems.
current javascript code:
let browseFile = $('#browseFile');
let resumable = new Resumable({
target: '{{ route('files.upload.large') }}',
query:{_token:'{{ csrf_token() }}'} ,// CSRF token
//fileType: ['mp4'],
chunkSize: 10*1024*1024, // default is 1*1024*1024, this should be less than your maximum limit in php.ini
headers: {
'Accept' : 'application/json'
},
testChunks: false,
maxChunkRetries: 1000,
chunkRetryInterval: 2000,
throttleProgressCallbacks: 1,
});
resumable.assignBrowse(browseFile[0]);
resumable.on('fileAdded', function (file) { // trigger when file picked
showProgress();
resumable.upload() // to actually start uploading.
});
resumable.on('fileProgress', function (file) {
if(navigator.onLine === true){
// trigger when file progress update
updateProgress(Math.floor(file.progress() * 100));
}
else{
alert('no Internet');
}
});
resumable.on('fileSuccess', function (file, response) { // trigger when file upload complete
response = JSON.parse(response)
console.log('sss');
//$('#videoPreview').attr('src', response.path);
});
resumable.on('fileError', function (file, response) { // trigger when there is any error
console.log(response);
});
let progress = $('.progress');
function showProgress() {
progress.find('.progress-bar').css('width', '0%');
progress.find('.progress-bar').html('0%');
progress.find('.progress-bar').removeClass('bg-success');
progress.show();
}
function updateProgress(value) {
progress.find('.progress-bar').css('width', `${value}%`)
progress.find('.progress-bar').html(`${value}%`)
}
function hideProgress() {
progress.hide();
}
Laravel Server side code:
public function uploadLargeFiles(Request $request) {
$receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
if (!$receiver->isUploaded()) {
// file not uploaded
}
$fileReceived = $receiver->receive(); // receive file
if ($fileReceived->isFinished()) { // file uploading is complete / all chunks are uploaded
$file = $fileReceived->getFile(); // get file
$extension = $file->getClientOriginalExtension();
$fileName = str_replace('.'.$extension, '', $file->getClientOriginalName()); //file name without extenstion
$fileName .= '_' . md5(time()) . '.' . $extension; // a unique file name
$disk = Storage::disk(config('filesystems.default'));
$path = $disk->putFileAs('products', $file, $fileName);
// delete chunked file
unlink($file->getPathname());
return [
'path' => asset('storage/' . $path),
'filename' => $fileName
];
}
// otherwise return percentage information
$handler = $fileReceived->handler();
return [
'done' => $handler->getPercentageDone(),
'status' => true
];
}
I am a beginner in this, so not so good in finding solutions. Tried my best, but couldn't find any solutions. It will be so kind if you could help.
Thank you..

PayPal Smart Payment Buttons: Error: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I've been trying to figure out this problem for 2 days already..
I want to implement Smart Payment Buttons from PayPal, literally followed every step of the explanation closely but still getting following error:
Error: JSON.parse: unexpected character at line 1 column 1 of the JSON data
My javascript for Button rendering:
paypal.Buttons({
createOrder: function() {
return fetch('vendor/paypal/paypal-checkout-sdk/samples/CaptureIntentExamples/CreateOrder.php', {
method: 'post',
headers: {
'content-type': 'application/json'
}
}).then(function(res) {
return res.json();
}).then(function(data) {
return data.orderID; // Use the same key name for order ID on the client and server
});
},
onApprove: function(data, actions) {
// This function captures the funds from the transaction.
return actions.order.capture().then(function(details) {
// This function shows a transaction success message to your buyer.
alert('Transaction completed by ' + details.payer.name.given_name);
});
},
onError: function(err) {
alert(err);
}
}).render('#paypal-button-container');
My CreateOrder.php:
namespace Sample\CaptureIntentExamples;
require __DIR__ . '/../../../../autoload.php';
use Sample\PayPalClient;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
class CreateOrder
{
/**
* Setting up the JSON request body for creating the Order. The Intent in the
* request body should be set as "CAPTURE" for capture intent flow.
*
*/
private static function buildRequestBody()
{
return array(
'intent' => 'CAPTURE',
'application_context' =>
array(
'return_url' => 'https://example.com/return',
'cancel_url' => 'https://example.com/cancel'
),
'purchase_units' =>
array(
0 =>
array(
'amount' =>
array(
'currency_code' => 'USD',
'value' => '220.00'
)
)
)
);
}
/**
* This is the sample function which can be sued to create an order. It uses the
* JSON body returned by buildRequestBody() to create an new Order.
*/
public static function createOrder($debug=false)
{
$request = new OrdersCreateRequest();
$request->headers["prefer"] = "return=representation";
$request->body = self::buildRequestBody();
$client = PayPalClient::client();
$response = $client->execute($request);
if ($debug)
{
print "Status Code: {$response->statusCode}\n";
print "Status: {$response->result->status}\n";
print "Order ID: {$response->result->id}\n";
print "Intent: {$response->result->intent}\n";
print "Links:\n";
foreach($response->result->links as $link)
{
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
// To toggle printing the whole response body comment/uncomment below line
echo json_encode($response->result, JSON_PRETTY_PRINT), "\n";
}
return $response;
}
}
if (!count(debug_backtrace()))
{
CreateOrder::createOrder(true);
}
It's basicly all copied from the PayPal walkthough.
If I visit the CreateOrder.php directly it is creating an order and I can see the response without errors.
Status Code: 201 Status: CREATED [...]
What I did was deleting the part of the code which was printing out the response in txt format. This is why you were getting JSON syntax error.
public static function createOrder($debug=false)
{
$request = new OrdersCreateRequest();
$request->prefer('return=representation');
$request->body = self::buildRequestBody();
// 3. Call PayPal to set up a transaction
$client = PayPalClient::client();
$response = $client->execute($request);
// To print the whole response body, uncomment the following line
echo json_encode($response->result, JSON_PRETTY_PRINT);
// 4. Return a successful response to the client.
return $response;
}
By the way, this answer is very helpful: https://stackoverflow.com/a/63019280/12208549

Create/update lead using Javascript for Intercom?

We would like to create/update a lead in Intercom via Javascript, we can do it through the PHP, but I have no idea how to do the same with Javascript, because we are using Unbounce landing page and when visitor fill out the form we would like send it to Intercom and create the lead for us.
We can use Zapier integration inside the Unbounce but passing the UTM parameters is not allowed, so we want to use the Intercom API/Javascript directly.
Below is the PHP script that we are using to create lead through WP Intercom API
Anyone how to do the same using Javascript? so I can put inside the Unbounce page script manager.
$client = new IntercomClient('xxxxxxxxxxxxx=', null);
try {
// First check if this already exists
$leads = $client->leads->getLeads(['email' => $post['email']]);
foreach ($leads->contacts as $lead) {
$id = $lead->id;
}
if(!$id) {
$id = '';
}
$client->leads->update([
"id" => $id,
"email" => $post['email'],
"name" => preg_replace("/[^a-zA-Z0-9\s]/", "", ucwords($post['first_name'])),
"last_request_at" => time(),
"last_seen_ip" => $_SERVER['REMOTE_ADDR'],
"utm_campaign" => $post['Utm_campaign],
"utm_content" => $post['Utm_content'],
"utm_medium" => $post['Utm_medium'],
"utm_source" => $post['Utm_source'],
"utm_term" => $post['Utm_term'],
'Form Message' => preg_replace("/[^a-zA-Z0-9\s]/", "", $post['description'])]
]);
} catch(ClientException $e) {
$response = $e->getResponse();
$statusCode = $response->getStatusCode();
if ($statusCode == '404') {
// Handle 404 error
return;
} else {
throw $e;
}
}

Why use 'php://input' over the POST superglobal - Stripe SCA example

Stripe are soon to roll out their use of Strong Customer Authentication for payments with their platform. There's a fairly substantial section in their documentation about it.
https://stripe.com/docs/payments/payment-intents/quickstart#manual-confirmation-flow
The process has the following flow:
The vanilla PHP implementation is like so:
<?php
# vendor using composer
require_once('vendor/autoload.php');
\Stripe\Stripe::setApiKey(getenv('STRIPE_SECRET_KEY'));
header('Content-Type: application/json');
# retrieve json from POST body
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
$intent = null;
try {
if (isset($json_obj->payment_method_id)) {
# Create the PaymentIntent
$intent = \Stripe\PaymentIntent::create([
'payment_method' => $json_obj->payment_method_id,
'amount' => 1099,
'currency' => 'gbp',
'confirmation_method' => 'manual',
'confirm' => true,
]);
}
if (isset($json_obj->payment_intent_id)) {
$intent = \Stripe\PaymentIntent::retrieve(
$json_obj->payment_intent_id
);
$intent->confirm();
}
generatePaymentResponse($intent);
} catch (\Stripe\Error\Base $e) {
# Display error on client
echo json_encode([
'error' => $e->getMessage()
]);
}
function generatePaymentResponse($intent) {
# Note that if your API version is before 2019-02-11, 'requires_action'
# appears as 'requires_source_action'.
if ($intent->status == 'requires_action' &&
$intent->next_action->type == 'use_stripe_sdk') {
# Tell the client to handle the action
echo json_encode([
'requires_action' => true,
'payment_intent_client_secret' => $intent->client_secret
]);
} else if ($intent->status == 'succeeded') {
# The payment didn’t need any additional actions and completed!
# Handle post-payment fulfillment
echo json_encode([
"success" => true
]);
} else {
# Invalid status
http_response_code(500);
echo json_encode(['error' => 'Invalid PaymentIntent status']);
}
}
?>
The necessary JavaScript for its use with Stripe Elements looks like this:
var cardholderName = document.getElementById('cardholder-name');
var cardButton = document.getElementById('card-button');
cardButton.addEventListener('click', function(ev) {
stripe.createPaymentMethod('card', cardElement, {
billing_details: {name: cardholderName.value}
}).then(function(result) {
if (result.error) {
// Show error in payment form
} else {
// Otherwise send paymentMethod.id to your server (see Step 2)
fetch('/ajax/confirm_payment', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ payment_method_id: result.paymentMethod.id })
}).then(function(result) {
// Handle server response (see Step 3)
result.json().then(function(json) {
handleServerResponse(json);
})
});
}
});
});
function handleServerResponse(response) {
if (response.error) {
// Show error from server on payment form
} else if (response.requires_action) {
// Use Stripe.js to handle required card action
stripe.handleCardAction(
response.payment_intent_client_secret
).then(function(result) {
if (result.error) {
// Show error in payment form
} else {
// The card action has been handled
// The PaymentIntent can be confirmed again on the server
fetch('/ajax/confirm_payment', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ payment_intent_id: result.paymentIntent.id })
}).then(function(confirmResult) {
return confirmResult.json();
}).then(handleServerResponse);
}
});
} else {
// Show success message
}
}
In my own project I'm using Laravel which is entirely based on the MVC architecture and it fairly nice to you when it comes to most things.
I have tried to refactor a little but I have a question.
Why would you use this line $json_str = file_get_contents('php://input'); over just trying to grab the posted variables from the Request object used in Laravel?
I also read the following article from the PHP Manual:
https://www.php.net/manual/en/wrappers.php.php
To be perfectly honest I've been away from procedural PHP so this has confused me to no end.
Why use 'php://input' over the POST superglobal - Stripe SCA example
The body is encoded as JSON. You can tell because the next line explicitly decodes it.
PHP doesn't understand application/json requests. It will only populate $_POST if the data is encoding using the application/x-www-form-urlencoded or multipart/form-data formats.
Why would you use this line $json_str = file_get_contents('php://input'); over just trying to grab the posted variables from the Request object used in Laravel?
If you were using Laravel, there's no reason to do that.
Since there is no sign of anything Laravel in the example you gave, it is presumably not written with the intention of introducing a dependency on Laravel.

Sign in with Paypal API: get basic user info

I am using JavaScript to login with PayPal.
My JavaScript code is as follows and seems to work fine.
<script type="text/javascript" src="https://www.paypalobjects.com/js/external/api.js"></script>
<script type="text/javascript">
paypal.use( ["login"], function(login) {
login.render ({
"appid": "<%=paypalAppId%>",
"scopes": "profile email address phone https://uri.paypal.com/services/paypalattributes",
"containerid": "paypalLogin",
"locale": "en-gb",
"returnurl": "http://www.domain.net/plogin.html"
});
});
</script>
However, I am struggling with the next step. Using either JavaScript or classic ASP, I am trying to obtain the following data about the signed in user:
Email address
First name
Family name
unique id (optional)
Address (optional)
Telephone number
I have done this with Facebook, Google & LinkedIn, using examples available on the respective sites. However, with Paypal, I cannot find any useful examples of how to do this...
I manage to achieve that with the next code. It never worked for me the way paypal does it. So I do everything on one code instead of jumping.
testingPaypalIdentity.php is the url callback that i put as 'return url' and is the same that you must put on your paypal app.
Basically the code checks if there's a code wich is user permission, if there's one then creates the tokens, if there's a refresh token then it search for user info and print it.
require __DIR__ . '/bootstrap.php';
use PayPal\Api\OpenIdSession;
use PayPal\Api\OpenIdTokeninfo;
use PayPal\Exception\PayPalConnectionException;
use PayPal\Api\OpenIdUserinfo;
$baseUrl = getBaseUrl() . '/testingPaypalIdentity.php?success=true';
$tmp;
//Get Authorization URL returns the redirect URL that could be used to get user's consent
$redirectUrl = OpenIdSession::getAuthorizationUrl(
$baseUrl,
array('openid', 'profile', 'address', 'email', 'phone',
'https://uri.paypal.com/services/paypalattributes',
'https://uri.paypal.com/services/expresscheckout',
'https://uri.paypal.com/services/invoicing'),
null,
null,
null,
$apiContext
);
$refreshToken='';
if (isset($_GET['code']) && $_GET['code'] != '') {
$code = $_GET['code'];
try {
$accessToken = OpenIdTokeninfo::createFromAuthorizationCode(array('code' => $code), null, null, $apiContext);
} catch (PayPalConnectionException $ex) {
echo $_GET['code']." ".$ex;
//ResultPrinter::printError("Obtained Access Token", "Access Token", null, $_GET['code'], $ex);
exit(1);
}
$refreshToken=$accessToken->getRefreshToken();
print_r($accessToken);
//ResultPrinter::printResult("Obtained Access Token", "Access Token", $accessToken->getAccessToken(), $_GET['code'], $accessToken);
}
if($refreshToken!='') {
try {
$tokenInfo = new OpenIdTokeninfo();
$tokenInfo = $tokenInfo->createFromRefreshToken(array('refresh_token' => $refreshToken), $apiContext);
$params = array('access_token' => $tokenInfo->getAccessToken());
$userInfo = OpenIdUserinfo::getUserinfo($params, $apiContext);
} catch (Exception $ex) {
// NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
echo $ex;
exit(1);
}
$tmp=$userInfo;
print_r($userInfo);
}
And check OpenIdUserinfo class to obtain the info needed, for example:
$email = $userInfo.getEmail();
Sorry for bad english, and if you required further information, please ask.
Greetings

Categories

Resources