Calling PayPal JS SDK inside in PHP - php

I am trying to integrate JS PayPal SDK into my PHP code block :
case 'PAYPAL':
header('Content-Type: text/plain; charset=ISO-8859-1');
$cart = new Cart();
if ($cart->isEmpty()) {
die(t_lang('M_TXT_CART_IS_EMPTY'));
}
if (!$cart->validateCartItems()) {
die(t_lang('M_TXT_CART_IS_EMPTY'));
}
if (!$cart->validateShippingCharges()) {
// die('Shipping details are not saved!!');
echo "This Product is not Deliverable";
}
$showPaypalMsg = '<span class="wrapTitle">' . t_lang('M_TXT_PAYPAL') .
'</span>';
die($showPaypalMsg);
break;
What I need is to attain the SDK code to the PHP variable and call it: $showPaypalMsg , So I will be able to call PayPal JS SDK. I have tried to add like 'echo <script> .... </script>' but did not work. I have also tried by calling with .js file that also did not work. The code I want to attain to the variable is :
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Add meta tags for mobile and IE -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title> PayPal Checkout Integration | Server Demo </title>
</head>
<body>
<!-- Set up a container element for the button -->
<div id="paypal-button-container"></div>
<!-- Include the PayPal JavaScript SDK -->
<script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD"></script>
<script>
// Render the PayPal button into #paypal-button-container
paypal.Buttons({
// Call your server to set up the transaction
createOrder: function(data, actions) {
return fetch('/demo/checkout/api/paypal/order/create/', {
method: 'post'
}).then(function(res) {
return res.json();
}).then(function(orderData) {
return orderData.id;
});
},
// Call your server to finalize the transaction
onApprove: function(data, actions) {
return fetch('/demo/checkout/api/paypal/order/' + data.orderID + '/capture/', {
method: 'post'
}).then(function(res) {
return res.json();
}).then(function(orderData) {
// Three cases to handle:
// (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
// (2) Other non-recoverable errors -> Show a failure message
// (3) Successful transaction -> Show confirmation or thank you
// This example reads a v2/checkout/orders capture response, propagated from the server
// You could use a different API or structure for your 'orderData'
var errorDetail = Array.isArray(orderData.details) && orderData.details[0];
if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
return actions.restart(); // Recoverable state, per:
// https://developer.paypal.com/docs/checkout/integration-features/funding-failure/
}
if (errorDetail) {
var msg = 'Sorry, your transaction could not be processed.';
if (errorDetail.description) msg += '\n\n' + errorDetail.description;
if (orderData.debug_id) msg += ' (' + orderData.debug_id + ')';
return alert(msg); // Show a failure message (try to avoid alerts in production environments)
}
// Successful capture! For demo purposes:
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
var transaction = orderData.purchase_units[0].payments.captures[0];
alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details');
// Replace the above to show a success message within this page, e.g.
// const element = document.getElementById('paypal-button-container');
// element.innerHTML = '';
// element.innerHTML = '<h3>Thank you for your payment!</h3>';
// Or go to another URL: actions.redirect('thank_you.html');
});
}
}).render('#paypal-button-container');
</script>
</body>
</html>
Is there any way to call this codes inside of the php-ajax code block ?

To output HTML from PHP, close your PHP tag with ?> and paste the HTML after that.
When you want to begin PHP again, use <?php

Related

'paypal' is not defined in PHP

I have codes in ajax which calls php file to show the paypal sdk button in that page :
function redirectPaypal() {
$('#tabs2').html('<img src="' + webroot + 'facebox/loading.gif">');
callAjax(webroot + 'TESTS.php', 'mode=paypall', function (t) {
// $.facebox(t);
$('#walletBg').removeClass('addBgColor');
$('#paypalBg').addClass('addBgColor');
$('#neverBg').removeClass('addBgColor');
$('#authBg').removeClass('addBgColor');
// $('#paymentInfo').show();
$('#tabs2').html(t);
});
}
As you see it calls TESTS.php file with the mode value paypal. The TESTS.php file is looks like below :
<?
require_once 'application-top.php';
require_once 'includes/navigation-functions.php';
require_once 'includes/site-functions-extended.php';
require_once 'includes/buy-deal-functions.php';
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
$post = getPostedData();
print_r($post);
if ($_POST['mode'] == 'paypall')
{
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Add meta tags for mobile and IE -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title> PayPal Checkout Integration | Client Demo </title>
</head>
<body>
<!-- Set up a container element for the button -->
<div id="paypal-button-container"></div>
<!-- Include the PayPal JavaScript SDK -->
<script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD" data-namespace="paypal_sdk"></script>
<script>
// Render the PayPal button into #paypal-button-container
paypal_sdk.Buttons({
// Set up the transaction
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '88.44'
}
}]
});
},
// Finalize the transaction
onApprove: function(data, actions) {
return actions.order.capture().then(function(orderData) {
// Successful capture! For demo purposes:
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
var transaction = orderData.purchase_units[0].payments.captures[0];
alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details');
// Replace the above to show a success message within this page, e.g.
// const element = document.getElementById('paypal-button-container');
// element.innerHTML = '';
// element.innerHTML = '<h3>Thank you for your payment!</h3>';
// Or go to another URL: actions.redirect('thank_you.html');
});
}
}).render('#paypal-button-container');
</script>
</body>
</html>
<?
}
?>
File is called successfully but as you see the code below I am getting the reference error when the page is called :
VM1597:3
Uncaught ReferenceError: paypal_sdk is not defined
at eval (eval at <anonymous> (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:2:11369), <anonymous>:3:9)
at eval (<anonymous>)
at js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:2:11369
at Function.globalEval (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:2:11380)
at HTMLScriptElement.<anonymous> (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:4:2538)
at Function.each (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:2:11776)
at init.domManip (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:4:2441)
at init.append (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:3:32408)
at init.<anonymous> (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:4:1283)
at Function.access (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:2:13266)
The error is related to the script which is called in TESTS.php :
<script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD" data-namespace="paypal_sdk"></script>
It seems the file is not imported or there is some errors in php file which I am not able to find it out. Can anyone help me with this please as I have spent my whole day on it. Thanks.
EDIT :
I have seperated the codes like below in order to prevent the preloading the papyal.button codes first. And now it looks like below :
<?
require_once 'application-top.php';
require_once 'includes/navigation-functions.php';
require_once 'includes/site-functions-extended.php';
require_once 'includes/buy-deal-functions.php';
?>
<script type="text/javascript" src="https://www.paypal.com/sdk/js?client-id=AQgUM6x3URK1A-rcNIq56covuc0CYGv3pb5sYeL6-cqsO1HYV2CV6h4ur6BCly_1YYd3-UOMTNGtwQXd&currency=USD"></script>
<?
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
$post = getPostedData();
print_r($post);
if ($_POST['mode'] == 'paypall')
{
?>
<script src="https://example.com/TESTS.js"></script>
<?
}
?>
Now I am getting the error like below :
GET https://www.paypal.com/sdk/js?client-id=AQgUM6x3URK1A-rcNIq56covuc0CYGv3pb5sYeL6-cqsO1HYV2CV6h4ur6BCly_1YYd3-UOMTNGtwQXd&currency=USD&_=1647908135353 net::ERR_ABORTED 400
When I checked the error code the requested src url is looking like different as it adds the timestamp at the end of the link therefore I am getting the error :
https://www.paypal.com/sdk/js?client-id=AQgUM6x3URK1A-rcNIq56covuc0CYGv3pb5sYeL6-cqsO1HYV2CV6h4ur6BCly_1YYd3-UOMTNGtwQXd&currency=USD&_=1647908731335
EDIT 2:
The payment page looks like below :
You don't have to inject the whole page. You can do something like this.
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Add meta tags for mobile and IE -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title> PayPal Checkout Integration | Client Demo </title>
<script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD" data-namespace="paypal_sdk"></script>
</head>
<body>
<!-- Set up a container element for the button -->
<div id="paypal-button-container"></div>
<!-- Include the PayPal JavaScript SDK -->
<?php if($_POST['mode'] == 'paypall') { ?>
<script>
// Render the PayPal button into #paypal-button-container
paypal_sdk.Buttons({
// Set up the transaction
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '88.44'
}
}]
});
},
// Finalize the transaction
onApprove: function(data, actions) {
return actions.order.capture().then(function(orderData) {
// Successful capture! For demo purposes:
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
var transaction = orderData.purchase_units[0].payments.captures[0];
alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details');
// Replace the above to show a success message within this page, e.g.
// const element = document.getElementById('paypal-button-container');
// element.innerHTML = '';
// element.innerHTML = '<h3>Thank you for your payment!</h3>';
// Or go to another URL: actions.redirect('thank_you.html');
});
}
}).render('#paypal-button-container');
</script>
<?php } ?>
</body>
</html>
Anyone who is struggling with this case just use the code like below :
function loadAsync(url, callback) {
var s = document.createElement('script');
s.setAttribute('src', url); s.onload = callback;
document.head.insertBefore(s, document.head.firstElementChild);
}
// Usage -- callback is inlined here, but could be a named function
loadAsync('https://www.paypal.com/sdk/js?client-id=test&currency=USD', function() {
paypal.Buttons({
// Set up the transaction
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '0.01'
}
}]
});
},
// Finalize the transaction
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
//...
});
}
}).render('#paypal-button-container');
});
Loading a script that way is asynchronous and takes time therefore the event onload must be used as callback.

Trying to call a PHP script in separate JS file, how do i display the output onto my HTML page

First time trying this can anyone help me, i get an output on the console but have no idea how to display it in a tag. This is the problem for both the sections of my code. Any help would be appreciated.
const URL_GETOFFERS = 'getOffers.php';
const URL_GETOFFERS_XML = 'getOffers.php?useXML';
fetch(URL_GETOFFERS)
.then(
function (response) {
return response.text();
})
.then(
function (data) {
console.log(data);
document.getElementById("getHTMLOffer").innerHTML = "<p>" + this.responseText + "</p>";
})
.catch(
function (err) {
console.log("Something went wrong!", err);
});
fetch(URL_GETOFFERS_XML)
.then(
function (response) {
return response.text();
})
.then(
function (data) {
console.log(data);
parser = new DOMParser();
xmlDoc = parser.parseFromString(data,"text/xml");
xmlDoc.getElementsById("getXMLOffer").innerHTML = this.responseText;
})
.catch(
function (err) {
console.log("Something went wrong!", err);
});
});
If you want to put some content inside HTML elements you have to:
create the desired HTML elements
<div id="getHTMLOffer">initial content</div>
<div id="getXMLOffer">initial content</div>
get the elements in Javascript, after DOM has loaded
change the contents of the elements
// the contents of this function is executed after the HTML structure (DOM) is loaded
// aka `on ready`
(function() {
document.getElementById("getHTMLOffer").innerHTML = "new content here";
document.getElementById("getXMLOffer").innerHTML = "new content here";
})();
Know that there are multiple ways to accomplish this. Above is shown just one of those ways.
Also be aware the function getElementById gets only one element. In your code there is a typo getElementsById (extra s character).
A rudimentary example that sends a basic GET request with a querystring to the same page, processes th servers response and displays on the page
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['task'] ) ){
ob_clean();
echo 'Some text as respons to the FETCH request task = "'.$_GET['task'].'"';
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>FETCH</title>
</head>
<body>
<aside id='getHTMLOffer'></aside>
<script>
fetch( '?task=fetch&source=text' )
.then( r=>{ return r.text() } )
.then( data=>{
document.getElementById('getHTMLOffer').innerHTML=data
})
.catch(err=>{ alert( err ) } )
</script>
</body>
</html>

jQuery.Timer Ajax send multiple form values to secondary page

I'm using this jquery timer to collect time spent while it is running.
https://github.com/walmik/timer.jquery
http://jquerytimer.com/
In a prior Stack Overflow post we were able to Post to another page the current accumulated time using jQuery Ajax (jQuery.timer how to get current value in php?). Many thinks to #Dakis
It seems our current solution is trying to save on any Stop and Restart of the Timer. It only needs to do a Save to DB routine IF the “Save Time and Notes” button is selected.
I’ve been researching jQuery Ajax and understand that a key/value pair is needed to be sent to the server/receiving page. I understand the first value identifies the target from which to get the "key", but I could not get a clear understanding of proper formatting for the second “value”.
'task': $('.ta_tasks').data('task’) does not seem to be passing the value as expected.
I’ve added a TextArea with an ID of “ta_tasks” and appended the current working AJAX with:
data: {
'time': $('.timer').data('seconds'),
'state': $('.timer').data('state'),
'task': $('.ta_tasks').data('task’)
On the receiving page I added a simple alert to see if the value is being received but it is not. If I can figure out how to properly send the contents of the TextArea I could also figure out how to submit a value from the “Save Time and Notes” button so that a Pause and Restart will not also submit to the database.
Working page: http://sgdesign.com/timer2.php
Parent page script:
<script src="https://cdnjs.cloudflare.com/ajax/libs/timer.jquery/0.7.1/timer.jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var hasTimer = false;
/**
* Save the current timer value.
*
* Performs an ajax request to the server, which will
* save the timer value in a database table and return
* a corresponding message.
*/
function saveTime() {
$.ajax({
method: 'post',
dataType: 'html',
url: 'saveTime.php',
data: {
'time': $('.timer').data('seconds'),
'state': $('.timer').data('state'),
'task': $('.ta_tasks').data('task')
},
success: function (response, textStatus, jqXHR) {
displayAlert('success', response);
},
error: function (jqXHR, textStatus, errorThrown) {
/*
* If the status code of the response is the custom one
* defined by me, the developer, in saveTime.php, then I
* can display the corresponding error message. Otherwise,
* the displayed message will be a general user-friendly
* one - so, that no system-related infos will be shown.
*/
var message = (jqXHR.status === 420)
? jqXHR.statusText
: 'An error occurred during your request. Please try again.';
displayAlert('danger', message);
},
complete: function (jqXHR, textStatus) {
//...
}
});
}
/**
* Display a bootstrap alert.
*
* #param type string success|info|warning|danger.
* #param message string Alert message.
* #return void
*/
function displayAlert(type, message) {
var alert = '<div class="alert alert-' + type + ' alert-dismissible" role="alert">'
+ '<button type="button" class="close" data-dismiss="alert" aria-label="Close">'
+ '<span aria-hidden="true">×</span>'
+ '</button>'
+ '<span>' + message + '</span>'
+ '</div>';
$('.messages').html(alert);
}
// Init timer start
$('.save-timer-btn').on('click', function () {
saveTime();
});
// Init timer start
$('.start-timer-btn').on('click', function () {
hasTimer = true;
$('.timer').timer({
editable: true
});
$(this).addClass('d-none');
$('.pause-timer-btn').removeClass('d-none');
});
// Init timer resume
$('.resume-timer-btn').on('click', function () {
$('.timer').timer('resume');
$(this).addClass('d-none');
$('.pause-timer-btn').removeClass('d-none');
});
// Init timer pause
$('.pause-timer-btn').on('click', function () {
$('.timer').timer('pause');
$(this).addClass('d-none');
$('.resume-timer-btn').removeClass('d-none');
saveTime();
});
// Remove timer. Leaves the display intact.
$('.remove-timer-btn').on('click', function () {
hasTimer = false;
$('.timer').timer('remove');
$(this).addClass('d-none');
$('.start-timer-btn').removeClass('d-none');
$('.pause-timer-btn, .resume-timer-btn').addClass('d-none');
});
// Additional focus event for this demo
$('.timer').on('focus', function () {
if (hasTimer) {
$('.pause-timer-btn').addClass('d-none');
$('.resume-timer-btn').removeClass('hidden');
}
});
// Additional blur event for this demo
$('.timer').on('blur', function () {
if (hasTimer) {
$('.pause-timer-btn').removeClass('d-none');
$('.resume-timer-btn').addClass('d-none');
}
});
});
</script>
Target Page contents:
<?php
// Price per hour variable
$cost = 50;
# require 'connection.php';
// Validate the timer value.
if (!isset($_POST['time']) || empty($_POST['time'])) {
/*
* This response header triggers the ajax error because the status
* code begins with 4xx (which corresponds to the client errors).
* I defined 420 as the custom status code. You can choose whatever
* code between 401 and 499 which is not officially assigned, e.g.
* which is marked as "Unassigned" in the official HTTP Status Code Registry.
* See the link.
*
* #link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml HTTP Status Code Registry.
*/
header('HTTP/1.1 420 No time value defined. Did you start the timer?');
exit();
}
// Validate the timer state.
if (!isset($_POST['state']) || empty($_POST['state'])) {
header('HTTP/1.1 420 No timer state recognized. Did you start the timer?');
exit();
}
// Read the posted values.
$time = $_POST['time'];
$state = $_POST['state']; /* The state of the timer when the saving operation was triggered. */
$task = $_POST['ta_tasks'];
$r = $cost / 3600 * $time;
$rate = round($r, 2);
/*
* Save the timer value in a db table using PDO library.
*/
/* $sql = 'INSERT INTO my_timer_table (
time
) VALUES (
:time
)';
$statement = $connection->prepare($sql);
$statement->execute([
':time' => $time,
]);
// Print success message.
echo 'Time (' . $time . ' seconds) successfully saved when timer was ' . $state . '.';
exit(); */
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script>
var a = "<?php echo $task; ?>";
alert ('task: ' + a);
</script>
</head>
<body>
<?php function secondsToTime($seconds) {
$dtF = new \DateTime('#0');
$dtT = new \DateTime("#$seconds");
return $dtF->diff($dtT)->format('%h hours, %i minutes and %s seconds');
// return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
}
?>
<?php echo secondsToTime($time);
echo '<br>';
echo 'Tasks: '.$task .'<br>';
echo 'Cost: $'. $rate;
?>
</body>
</html>
Goal Summary
Proper formatting of data in: 'task': $('.ta_tasks').data('task’)
Understanding of Why so as to learn how to also transfer when the 'Save Time and Notes" button to invoke saving Cost and Notes to DB
Don't define functions inside $(document).ready. Bring them outside.
Functions in PHP should reside only in pages destined for this purpose. See PSR-1 Side Effects. In principle you should definitely read: PSR-1 and PSR-2. Optional, especially PSR-4.
When you try to read a value sent through ajax, then you should read the value, not the CSS selector. So: Wrong: $task = $_POST['ta_tasks'];, correct: $task = $_POST['task'];.
Before validating posted values (on top of the page saveTime.php) you shouldn't declare any variables or do other things - so to say. So no $cost = 50; before validations, but after them. Still, if you want to define constants for saveTime.php, then better bring them in another file, which you can include.
In this case, the data() method is a proprietary method of http://jquerytimer.com ! You can use it to fetch some values (timer value, timer state, etc). But, in order to fetch the value of a html control you need to use val(), or text(), or innerHtml, etc. In a word: native js or jquery methods/functions. So, use like this:
data: {
'time': $('.timer').data('seconds'),
'state': $('.timer').data('state'),
'task': $('#ta_tasks').val()
}
Do you see the selector ('#ta_tasks')? It references an id (because of #). You used .ta_tasks, therefore referencing a class name. Which you didn't define.
Better: use the camelCase naming convention for html id's and names, and the "hyphen-separated" form for css classes:
data: {
'time': $('.timer').data('seconds'),
'state': $('.timer').data('state'),
'task': $('#ta_tasks').val()
}
//...
<textarea id="taTasks" name="taTasks" class="form-control" rows="4">Doh!</textarea>
Avoid as much as possible referencing php code from javascript or css code. If you need a php value inside a javascript code, then pass it through a javascript function - as argument, or save the php value inside an attribute of a html control and read it through referencing the attribute by js/jquery methods/functions. As an example, see the code in saveTime.php, which saves the task value in a hidden input and alerts it from js code.
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo - Timer</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/timer.jquery/0.7.1/timer.jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var hasTimer = false;
// Init timer start
$('.save-timer-btn').on('click', function () {
saveTime();
});
// Init timer start
$('.start-timer-btn').on('click', function () {
hasTimer = true;
$('.timer').timer({
editable: true
});
$(this).addClass('d-none');
$('.pause-timer-btn').removeClass('d-none');
});
// Init timer resume
$('.resume-timer-btn').on('click', function () {
$('.timer').timer('resume');
$(this).addClass('d-none');
$('.pause-timer-btn').removeClass('d-none');
});
// Init timer pause
$('.pause-timer-btn').on('click', function () {
$('.timer').timer('pause');
$(this).addClass('d-none');
$('.resume-timer-btn').removeClass('d-none');
saveTime();
});
// Remove timer. Leaves the display intact.
$('.remove-timer-btn').on('click', function () {
hasTimer = false;
$('.timer').timer('remove');
$(this).addClass('d-none');
$('.start-timer-btn').removeClass('d-none');
$('.pause-timer-btn, .resume-timer-btn').addClass('d-none');
});
// Additional focus event for this demo
$('.timer').on('focus', function () {
if (hasTimer) {
$('.pause-timer-btn').addClass('d-none');
$('.resume-timer-btn').removeClass('d-none');
}
});
// Additional blur event for this demo
$('.timer').on('blur', function () {
if (hasTimer) {
$('.pause-timer-btn').removeClass('d-none');
$('.resume-timer-btn').addClass('d-none');
}
});
});
/**
* Save the current timer value.
*
* Performs an ajax request to the server, which will
* save the timer value in a database table and return
* a corresponding message.
*/
function saveTime() {
$.ajax({
method: 'post',
dataType: 'html',
url: 'saveTime.php',
data: {
'time': $('.timer').data('seconds'),
'state': $('.timer').data('state'),
'task': $('#taTasks').val()
},
success: function (response, textStatus, jqXHR) {
displayAlert('success', response);
},
error: function (jqXHR, textStatus, errorThrown) {
var message = (jqXHR.status === 420)
? jqXHR.statusText
: 'An error occurred during your request. Please try again.';
displayAlert('danger', message);
},
complete: function (jqXHR, textStatus) {
//...
}
});
}
/**
* Display a bootstrap alert.
*
* #param type string success|info|warning|danger.
* #param message string Alert message.
* #return void
*/
function displayAlert(type, message) {
var alert = '<div class="alert alert-' + type + ' alert-dismissible" role="alert">'
+ '<button type="button" class="close" data-dismiss="alert" aria-label="Close">'
+ '<span aria-hidden="true">×</span>'
+ '</button>'
+ '<span>' + message + '</span>'
+ '</div>';
$('.messages').html(alert);
}
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-12">
<h4>
Timer Demo 2
</h4>
</div>
</div>
<div class="row">
<div class="col-xs-6 messages"></div>
</div>
<div class="row">
<div class="col-md-3">
<input type="text" id="timer" name="timer" class="form-control timer" placeholder="0 sec">
</div>
<div class="col-md-9">
<button type="button" class="btn btn-success start-timer-btn">
Start
</button>
<button type="button" class="btn btn-success resume-timer-btn d-none">
Resume
</button>
<button type="button" class="btn btn-danger pause-timer-btn d-none">
Pause
</button>
<button type="button" class="btn btn-danger remove-timer-btn d-none">
Remove Timer
</button>
<button type="button" class="btn btn-primary save-timer-btn">
Save Time and Notes
</button>
</div>
</div>
<div class="row mt-1">
<div class="col-sm-12">
<lable for="taTasks">Notes to accompany task:</lable>
<textarea id="taTasks" name="taTasks" class="form-control" rows="4">Doh!</textarea>
</div>
</div>
</div>
</body>
</html>
saveTime.php
<?php
require_once 'functions.php';
// Validate the timer value.
if (!isset($_POST['time']) || empty($_POST['time'])) {
header('HTTP/1.1 420 No time value defined. Did you start the timer?');
exit();
}
// Validate the timer state.
if (!isset($_POST['state']) || empty($_POST['state'])) {
header('HTTP/1.1 420 No timer state recognized. Did you start the timer?');
exit();
}
// Validate the task.
if (!isset($_POST['task']) || empty($_POST['task'])) {
header('HTTP/1.1 420 No task value received.');
exit();
}
// Price per hour variable
$cost = 50;
// Read the posted values.
$time = $_POST['time'];
$state = $_POST['state']; /* The state of the timer when the saving operation was triggered. */
$task = $_POST['task'];
$r = $cost / 3600 * $time;
$rate = round($r, 2);
?>
<script type="text/javascript">
$(document).ready(function () {
alertTask();
});
function alertTask() {
var task = $('#task').val();
alert(task);
}
</script>
<input type="hidden" id="task" name="task" value="<?php echo $task; ?>">
<?php
echo secondsToTime($time);
echo '<br>';
echo 'Tasks: ' . $task . '<br>';
echo 'Cost: $' . $rate;
?>
functions.php
<?php
function secondsToTime($seconds) {
$dtF = new \DateTime('#0');
$dtT = new \DateTime("#$seconds");
return $dtF->diff($dtT)->format('%h hours, %i minutes and %s seconds');
// return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
}
Edit 1: In index.php, I brought the js functions outside of $(document).ready. I forgot to do it earlier.
Edit 2: Changed hidden to d-none in
$('.resume-timer-btn').removeClass('hidden');
Edit 3: I found the problem about which I commented. It was in my saveTime.php code: I loaded the jquery library, but it was already loaded in index.php. More of it: since you are loading the content of saveTime.php in a html page (index.php) which already has all resources loaded, you don't need to structure the saveTime.php as a whole structured html (with doctype, head, body, etc). It is completely enough to just define the content and script tags that you need. So, I reedited saveTime.php correspondingly.
textarea don't have ta_tasks class, u use id and it doesn't have html5 data object, correct to $("#ta_tasks").val().
check your ajax request data that you re sending and the one you are getting in your saveTime.php, you are sending 'task' and receiving 'ta_task' in saveTime.php
$.ajax({
method: 'post',
dataType: 'html',
url: 'saveTime.php',
data: {
'time': $('.timer').data('seconds'),
'state': $('.timer').data('state'),
'ta_task': $('.ta_tasks').data('task')
},
//other codes here
//saveTime.php
//now get the value with 'ta_task'
$task = $_POST['ta_task'];

Can't get this AJAX call working in PhoneGap

Using PhoneGap, I'm trying to build a basic android app that makes an AJAX call to a PHP API and return some JSON data. The code, in its entirety works on the desktop, but it doesn't seem to work for my Android when I make a build. When I build the app, install it on my device, and load it up, I get blank screen.
Here's the client that I wrote... Is there anything wrong with this code?
<head>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.3/jquery.mobile.min.css" />
</head>
<body>
<script>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
// Now safe to use the PhoneGap API
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
$.ajax({
url: 'http://api.example.com/test.php',
dataType: 'json',
timeout: 5000,
success: function(data, status) {
//data loaded
$('#results').append(data[0].about);
},
error: function() {
//error loading data
$('#results').append('No data received.');
}
});
$(document).ajaxError(function(event, request, settings) {
$("#msg").append("<li>Error requesting page " + settings.url + "</li>");
});
$(document).ajaxComplete(function(event, request, settings) {
$("#msg").append("<li>Request Complete.</li>");
});
}
</script>
<p id="results"></p>
<p id="msg"></p>
</body>
</html>
I also set the access origins in the config.xml to:
<access origin="http://example.com" subdomains="true" />
<access origin="*"/>
It seems that the AJAX code (and the global AJAX event handlers) is not getting called.
Be sure to have cordova.js included in the right location and available (e.g. by alert(<some cordova property>);). Then try if the onDeviceReady is called at all:
document.addEventListener("deviceready", function(){
alert("deviceready");
},false);

Using variables with jQuery and embedded objects

I am using a java script library that allows me to query information from a shoutcast server such as the current song playing, recent songs played, and etc which all works fine. This library places the data into a span element on the page based on it's defined ID.
Now, my issue is that I am trying to pass the contents of my span which is a string (current song title) to PHP so that I can use it for my Twitter library which uses PHP to post to Twitter.
<?php
// Insert your keys/tokens
$consumerKey = '';
$consumerSecret = '';
$accessToken = '';
$accessTokenSecret = '';
// Full path to twitterOAuth.php (change OAuth to your own path)
require_once('/home/soundcheck/public_html/app/twitter/auto/twitteroauth.php');
require_once('/home/soundcheck/public_html/app/twitter/auto/twitter.class');
// create new instance
$twitter = new Twitter($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
$twitter->send('testing...'); // This will send testing to twitter status!
?>
<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="jquery.shoutcast.min.js"></script>
<!-- Current Song Played -->
<script>
// Get current song playing and load it into an element with an ID of songtitle
$.SHOUTcast({
host : 'live.soundcheck.xyz',
port : 8000,
interval : 5000,
}).stats(function(){
$('#songtitle').text(this.get('songtitle'));
$(document).ready(function() {
console.log("Document Ready!");
var content = $('#songtitle').text();
var nowplaying = ("#NowPlaying: " + content);
$.ajax({
url: 'receiver.php',
type: 'POST',
data: { data : nowplaying },
success: function (result) {
console.log(nowplaying);
}
});
});
});
</script>
<!-- Last 10 Songs Played -->
<script>
// Get last 10 songs playing and load it into an ul element
$.SHOUTcast({
host : 'live.soundcheck.xyz',
port : 8000
}).played(function(tracks){
$('ul').html('');
$.each(tracks,function(k,track){
$('ul').append('<li>'+track.title+'</li>');
});
});
</script>
</head>
<body>
This SPAN has the current song title within it upon page load which is good. I want to pass this data to my PHP above to post to twitter.
<span id="songtitle" name="songtitle"></span>
<ul></ul>
</body>
</html>
Any assistance with this will be very helpful.. I have looked at so many places with no luck and this is getting very frustrating.
Regards,
I have posted my updated code which successfully sends a jQuery variable to PHP using AJAX upon a page load.
Here is the HTML/JAVASCRIPT
<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="jquery.shoutcast.min.js"></script>
<!-- Current Song Played -->
<script>
// Get current song playing and load it into an element with an ID of songtitle
$.SHOUTcast({
host : 'live.soundcheck.xyz',
port : 8000,
interval : 5000,
}).stats(function(){
$('#songtitle').text(this.get('songtitle'));
$(document).ready(function() {
console.log("Document Ready!");
var content = $('#songtitle').text();
var nowplaying = ("#NowPlaying: " + content);
console.log('TOP' + nowplaying);
$.post("receiver.php", //Required URL of the page on server
{ // Data Sending With Request To Server
name:nowplaying,
},
function(response){ // Required Callback Function
alert("Response: " + response); // "response" receives - whatever written in echo of above PHP script.
});
});
});
</script>
<!-- Last 10 Songs Played -->
<script>
// Get last 10 songs playing and load it into an ul element
$.SHOUTcast({
host : 'live.soundcheck.xyz',
port : 8000
}).played(function(tracks){
$('ul').html('');
$.each(tracks,function(k,track){
$('ul').append('<li>'+track.title+'</li>');
});
});
</script>
</head>
<body>
<span id="songtitle" name="songtitle"></span>
<ul></ul>
</body>
</html>
Here is the PHP code
<?php
// Insert your keys/tokens
$consumerKey = '';
$consumerSecret = '';
$accessToken = '';
$accessTokenSecret = '';
// Full path to twitterOAuth.php (change OAuth to your own path)
require_once('/home/soundcheck/public_html/app/twitter/auto/twitteroauth.php');
require_once('/home/soundcheck/public_html/app/twitter/auto/twitter.class');
// create new instance
$twitter = new Twitter($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
if($_POST["name"])
{
$name = $_POST["name"];
// Here, you can also perform some database query operations with above values.
// echo "Welcome ". $name ."!"; // Success Message
echo $name; // Success Message
$tag = ('# http://soundcheck.xyz #radio - powered by: http://buzzzhost.com');
$twitter->send($name .= $tag); // This will send testing to twitter status!
}
?>
I hope this will help someone out there as I was searching for a long time for a good option.

Categories