What is the equivalent of jquery object in PHP? - javascript

the jquery function below is a sample script from boomerang. It is their GetSendList function. I was trying to make a php version of it but still unsuccessful. Here's the function:
function GetSendList() {
var r = new Object;
r = [
{
email: $("#txt-SendList-email-0").val(),
jobNumber: $("#txt-SendList-jobNumber-0").val()
},
{
email: $("#txt-SendList-email-1").val(),
jobNumber: $("#txt-SendList-jobNumber-1").val()
}
]
var dataString = JSON.stringify(r);
$.ajax({
type: "POST",
url: "https://target.boomerang.com/V1.0/api/SendList",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
data: dataString,
headers: { auth_token: $('#txtAuthenticationCode').val() },
success: function (response) {
}
});
}
Here's my PHP script:
$main_url = "https://target.boomerang.com/V1.0/api/";
$token = "xxx";
$values = array('email'=>'email',
'jobNumber'=>'jobnumber'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$main_url."SendList");
curl_setopt($ch,CURLOPT_HTTPHEADER,array('auth_token: '.$token));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($values));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
$output = json_decode($server_output);
I'm guessing I have a wrong formatting for my values that's why I'm unsuccessful. I do not know the equivalence of jquery object in PHP.
PS. I use the same php script to call their other functions and Im successful with those. It's only the GetSendList that I'm having problem right now. Please advice. Thanks!

to make an object on PHP you just need to do :
$object = (object) array(); // Or new stdClass();
Use :
$object->name = "John";
echo $object->name;
Use with Javascript :
$object = json_decode( $_POST['json'] );
$json = json_encode( $object );

Related

How can i implement paypal checkout v2 server side / JS sdk

I'm trying to make an implementation for paypal using checkout.js, however, i need to store the details of the transaction once the payment it's completed but first, i'm having trouble getting the button values from the server side, my code goes as follows:
<script>
paypal.Buttons({
// Order is created on the server and the order id is returned
// Call your server to set up the transaction
createOrder: function(data, actions) {
return fetch('php/create.php', {
method: 'post'
}).then(function(response) {
return response.json();
}).then(function(orderData) {
return orderData.id;
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
// Call your server to save the transaction
return fetch('/paypal-transaction-complete.php', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: details.id
})
});
});
}
}).render('#paypal-button-container');
</script>```
<?php session_start();
// PayPal configuration
define('PAYPAL_CONFIG', [
'URL' => "https://api-m.sandbox.paypal.com/",
'CLIENT_ID' => 'xxx',
'SECRET' => 'xxx',
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, PAYPAL_CONFIG['URL'] . "v2/checkout/orders");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERPWD, PAYPAL_CONFIG['CLIENT_ID'] . ":" . PAYPAL_CONFIG['SECRET']);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = [
"intent" => "sale",
"redirect_urls" => [
"return_url" => "http://localhost:8888/index.php",
"cancel_url" => "http://localhost:8888/index.php"
],
"payer" => [
"payment_method" => "paypal"
],
"transactions" => [
[
"amount" => [
"total" => $_SESSION['price'],
"currency" => "USD"
]
]
]
];
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$response = curl_exec($ch);
$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$result = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
error_log("Invalid JSON response: " . json_last_error_msg());
var_dump($httpStatusCode);
return false;
}
if (!$result) {
error_log("cURL request failed with HTTP status code: " . $httpStatusCode);
var_dump($httpStatusCode);
return false;
}
return $result;
Whenever i try to click the paypal button, i keep getting a console error saying that Error: Unexpected end of Json input and closes the paypal window almost immediately
I've tried debbuging with several methods but i can't get it working, any suggestions?
(That code is not for checkout.js , which is older and deprecated ; you're using the current PayPal JS SDK)
Anyway, this issue:
Error: Unexpected end of Json input
Occurs when your server-side code is outputting something other than a purse JSON string, such as a var_dump or other echo statement. Your create and capture routes must output only a JSON string, never any other text or HTML.
You can get a log of the response being outputted to the XHR request in your browser's dev tools -> Network tab.

401 unauthorized ajax call error to Watson Assistant API

I am trying to make ajax request to Watson Assistant API from client side only, so I had this code in php which is working fine but when I tried to make it in jQuery I got 401 unauthorized error.
PHP:
$data['input']['text'] = $_POST['message'];
if(isset($_POST['context']) && $_POST['context']){
$data['context'] = json_decode($_POST['context'], JSON_UNESCAPED_UNICODE);
}
$data['alternate_intents'] = false;
$json = json_encode($data, JSON_UNESCAPED_UNICODE);
// Post the json to the Watson API via cURL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://watson-api-explorer.mybluemix.net/conversation/api/v1/workspaces/'.$workspace_id.'/message?version='.$release_date);
curl_setopt($ch, CURLOPT_USERPWD, $username.":".$password);
curl_setopt($ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = trim( curl_exec( $ch ) );
curl_close($ch);
// Responce the result.
echo json_encode($result, JSON_UNESCAPED_UNICODE);
JS:
$.ajax({
url: apiUrl,
type: 'POST',
dataType: 'json',
data: {
message: message,
context: context
},
headers:{
'Authorization' : 'Basic' + btoa('f7be829c-ae6d-47d8-b2bd-65a40ad45aa' +':'+ 'hJcToxQ23Zk'),
},
contentType: 'application/json',
timeout:10000
})
Anything missing from the JS code?
Note: credentials mentioned are for example only.

Access to REST API from JS

Need access to REST API from JS code, using jQuery ajax:
function tryQwintry () {
var data = {
"params[weight]" : "100",
"params[dimensions]" : "100x100x100",
"params[delivery_pickup]" : "msk_1",
"params[insurance]" : "false",
"params[items_value]" : "350",
"params[retail_pricing]" : "1"
};
$.ajax({
url: "http://logistics.qwintry.com/api/cost",
type: "POST",
dataType: "jsonp",
contentType: "application/json",
headers: {"Authorization":"Bearer " + MY_API_KEY},
data: data,
success: function (cost) {
console.log("стоимость доставки $"+cost);
},
error: getErrorMsg
});
}
Documentation of API (all examples are PHP):
<?php
define('SITE_URL', 'logistics.qwintry.com');
define('API_KEY', 'YOUR_API_KEY'); //don't forget to set your key!
$url = 'http://'. SITE_URL .'/api/cost';
$data = array (
'params' => array(
'weight' => 5, // in lb
'delivery_pickup' => 'msk_1', // full list of pickup points can be retrieved from /api/locations-list
'insurance' => true,
'items_value' => 500, // declaration items total cost in USD
'retail_pricing' => true // retail / wholesale pricing?
),
);
$data_string = http_build_query($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. API_KEY));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
Same thing I've coded in Java:
public double getCostPickup(String weight, String dimensions, String toPickup, String insurance, String value) throws Exception {
Map<String, Object> params = new HashMap<>();
params.put("params[weight_kg]", weight);
params.put("params[dimensions_cm]", dimensions);
params.put("params[delivery_pickup]", toPickup);
params.put("params[insurance]", insurance);
params.put("params[items_value]", value);
params.put("params[retail_pricing]", RETAIL_PRICING);
String url = BASE_URL+"/api/cost";
HttpResponse<JsonNode> jsonResponse = Unirest.post(url).fields(params).asJson();
return getCost(jsonResponse, insurance);
}
Have problems with configuring data of ajax request.
So any help would be greatly appreciated.
UPDATE: Changed my JS code:
function tryQwintry () {
var data = {
"params[weight]" : "100",
"params[dimensions]" : "100x100x100",
"params[delivery_pickup]" : "msk_1",
"params[insurance]" : "false",
"params[items_value]" : "350",
"params[retail_pricing]" : "1"
};
$.ajax({
url: "http://logistics.qwintry.com/api/cost",
type: "POST",
dataType: "json",
contentType: "application/json",
headers: {"Authorization" : "Bearer"+MY_API_KEY, "Access-Control-Allow-Origin" : "true"},
data: JSON.stringify(data),
success: function (cost) {
console.log("стоимость доставки $"+cost);
},
error: getErrorMsg
});
}
Getting this error in Chrome's developers mode:
Are you using CORS request?
If no then change datatype to "json" instead "dataType: "jsonp".
if you are doing CORS then enable CORS request then you need to add the php code to allow CORS request.
header("Access-Control-Allow-Origin: *");
check this link CORS with php headers
Json data format:
var data = {
weight : 100,
dimensions : "100x100x100",
delivery_pickup : "msk_1",
insurance : false,
items_value : 350,
retail_pricing : 1
};
$.ajax({
url: "http://logistics.qwintry.com/api/cost",
dataType: "jsonp",
contentType: "application/json",
headers: {"Authorization":"Bearer " + MY_API_KEY},
data: JSON.stringify(data),
success: function (cost) {
console.log("стоимость доставки $"+cost);
},
error: getErrorMsg
});
Note: method: "POST" is not allowed with JOSNP

(Wordpress / Ajax) ReferenceError: Can't find variable: ajaxobject

I'm working with Wordpress + Ajax and even using the proper hooks I get the error "ReferenceError: Can't find variable: ajaxobject". Of course there is some problem with my ajaxurl but I don't understand where since it seems well done to me. Can you help me?
In my functions.php
add_action( 'wp_enqueue_scripts', 'add_frontend_ajax_javascript_file', 11, 2 );
function add_frontend_ajax_javascript_file()
{
wp_localize_script( 'ajax-script', 'ajaxobject', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
my jQuery/AJAX file
var itemtitle = $('#itemtitle').val();
var itemdescription = $('#itemdescription').val();
jQuery.ajax({
method: 'post',
url : ajaxobject.ajaxurl, //Why???
dataType: "json",
data: {
'action':'update_portfolio_function',
'pid' : id,
'itemtitle' : itemtitle,
'itemdescription' : itemdescription,
},
success:function(data) {
// This outputs the result of the ajax request
alert("Coooool");
},
error: function(errorThrown){
console.log(errorThrown);
}
});
of course the update_portfolio_function looks like
add_action('wp_ajax_update_portfolio', 'update_portfolio_function' );
function update_portfolio_function(){
$id = $_REQUEST['pid'];
$title = $_REQUEST['itemtitle'];
$description = $_REQUEST['itemdescription'];
$attachment = array(
'ID' => $id,
'post_title' => $title,
'post_content' => $description
);
// now update main post body
wp_update_post( $attachment );
die();
}
Should I use init or no_priv?
You just need to use ajaxurl instead of ajaxobject.ajaxurl
like below
jQuery.ajax({
method: 'post',
url : ajaxurl,
dataType: "json",

Use a PHP variable in Javascript / Ajax without showing in the inspect element

i want to send emails with de mandrill api. I have mi apikey in a php var but when i do var apikey='<?php echo$apikey;?>'; this shows in the inspect elemnt.
its posibble hide, encrypt or something the variable with php, javascript, ajax or json?
this is and example of my code:
<?php
$apikey='aaaaaaaaaaaaaa';
?>
<script type="text/javascript">
var apikey='<?php echo$apikey;?>';
sendEmail();
function sendEmail() {
$.ajax({
type: 'POST',
url: 'https://mandrillapp.com/api/1.0/messages/send.json',
data: {
'key': apikey,
'message': {
'from_email': 'FROM_EMAIL_GOES_HERE',
'to': [{
'email': $('.email').val(), // get email from form
'name': $('.name').val(), // get name from form
'type': 'to'
}
],
'autotext': 'true',
'subject': 'EMAIL_SUBJECT_GOES_HERE',
'html': "Hey *|COOLFRIEND|*, we've been friends for *|YEARS|*.", // example of how to use the merge tags
'track_opens': true,
'track_clicks': true,
}
}
}).done(function(response) {
console.log(response); // if you're into that sorta thing
});
});
</script>
You can setup a php service and use curl to do the transferring work. Then just have AJAX do the front end work and send the subject/body/etc to the php service.
#Lifz works great for me
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
$result = curl_exec($ch);

Categories

Resources