I have been assigned to integrate API for my client website. This API is provided by vision6.com.au. There is no much information avialble on their website. Can anyone give me one example which will contact vision6 database and add a contact from our website developed using jquery and php.
Here is the way I am trying
var newVal = {
"id": 1,
"method": "addUser",
"params": [
"APIKEY",
"123456",
{
"username" : "username_123",
"password" : "123456abc",
"first_name" : "First Name",
"last_name" : "Last Name",
"email" : "example#example.com",
"mobile" : "0412312312",
"phone" : "56565656",
"fax" : "57575757",
"position" : "Manager",
"is_read_only" : true,
"timezone" : "Australia/Brisbane",
"email_user" : true,
"is_confirmed" : true
}
]
};
$.ajax({
url: 'http://www.vision6.com.au/api/jsonrpcserver.php?version=3.0',
type: 'POST',
beforeSend: function(){alert('sending');},
data: newVal,
//dataType: 'json',
//data: JSON.stringify(newVal),
//contentType: 'application/json; charset=utf-8',
dataType: 'json',
//async: false,
success: function(msg) { alert(msg);
}
});
This is what I have taken from their documentation
developers.vision6.com.au
For those who wants to integrate using Ruby, I've created a gist with a simple code:
require 'httparty'
url = 'http://www.vision6.com.au/api/jsonrpcserver.php?version=3.0'
api_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
JSON.parse(HTTParty.post(url, headers: { 'Content-Type' => 'application/json' }, body: JSON.dump({
'method' => 'getSessionInfo', 'params' => [api_key]
})))
JSON.parse(HTTParty.post(url, headers: { 'Content-Type' => 'application/json' }, body: JSON.dump({
'method' => 'searchLists', 'params' => [api_key]
})))
list_id = 123456
JSON.parse(HTTParty.post(url, headers: { 'Content-Type' => 'application/json' }, body: JSON.dump({
'method' => 'addContacts', 'params' => [api_key, list_id, [{ 'First Name' => 'Foo', 'Last Name' => 'Bar', 'Email' => 'foo#bar.com' }]]
})))
You will need to download a jsonRPCClient.php and include it in your php file. From my dealings with the Vision6 API, its not very comprehensive and doesn't make much sense until you start getting into it more. Unfortunately, they aren't very helpful in getting you started.
My code to get you started
include 'includes/jsonRPCClient.php';
$list_id = 1234;
$url = "http://www.vision6.com.au/api/jsonrpcserver.php?version=3.0";
$apikey = 'YOURAPIKEYHERE'
$api = new JsonRpcClient($url);
$contact = array();
$contact[] = array(
'First Name' => "John",
'Email' => "sample#email.com"
);
$returnID = $api->addContacts($apikey, $list_id, $contact);
the most important change I found was
$api->addContacts($apikey, $list_id, $contact);
All methods using the API follow this structure
$api ->APIMethod($apikey, $OtherRequiredFields/Arrays);
I suggest to follow their documentation
http://developers.vision6.com.au/3.0/guide/getting-started
Documentation mentions a client library to access their JSON-RPC. Download it, create a free account and generate a working snippet of PHP code from their examples. It also seems to contain a lot of insights and examples. I am just quoting PHP code for addbatch
// setup vars
$list_id01 = 123;
$list_id02 = 456;
$message_id = 111;
$batch_details = array
(array
('list_id' => $list_id01,
'type' => 'list', // all Contacts in List 123
'time' => 'send, // populate Batch time of send
)
array
('list_id' => $list_id02,
'type' => 'contact', // send to contact_list, next
'contact_list' => array(2),array(17),array(18),
'time' => 'send, // populate Batch time of send
));
$queue_id = $api->invokeMethod('addBatch', $message_id, $batch_details,
time() + (24*3600), true);
Once you produce a snippet of code that does an authorization request and a simple action, but DOES NOT behave as you expected you should update your question on SO. I.e. you should post the snippet and the results that you get vs. the results that you expect to get. That might really help to tackle the problem.
I would also recommend to contact support of the service directly.
PS
Unless you will be able to ask a question in form that would be potentially useful to other users, It would be very difficult to get an answer that you seek. Otherwise your question can be qualified as too localized.
<?php
$data = array(www.mtalkz.com)
‘dest’ => ‘0000000000’,
‘msg’=>’This is Test message’,
‘pass’=>’xyz’,
‘send’=>’ALERTS’,
‘uname’=>’ xyz ‘,
‘wapurl’=>’www.mtalkz.com‘
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => “https://mtalkz.com/developer-tools/“,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => “”,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => “POST”,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
“cache-control: no-cache”,
“content-type: multipart/form-data”,
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo “cURL Error #:” . $err;
} else {
echo $response;
}
<?php
$data = array(www.mtalkz.com)
‘dest’ => ‘0000000000’,
‘msg’=>’This is Test message’,
‘pass’=>’xyz’,
‘send’=>’ALERTS’,
‘uname’=>’ xyz ‘,
‘wapurl’=>’www.mtalkz.com‘
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => “https://mtalkz.com/developer-tools/“,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => “”,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => “POST”,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
“cache-control: no-cache”,
“content-type: multipart/form-data”,
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo “cURL Error #:” . $err;
} else {
echo $response;
}
Related
I'm trying to use the Advanced Custom Field (ACF) plugin to return JSON via ajax in WordPress.
The below code correctly returns the JSON data of the posts but is not giving me the ACF data inside each post.
How can I get that ACF data into JSON?
PHP File
add_shortcode("owt-ajax-shortcode", "owt_wpl_run_shortcode");
function owt_wpl_run_shortcode() {
ob_start();
include_once plugin_dir_path(__FILE__) . 'views/owt-ajax-page-view.php';
$template = ob_get_contents();
ob_end_clean();
echo $template;
}
add_action("wp_enqueue_scripts", "owt_include_scripts");
function owt_include_scripts() {
wp_enqueue_script("jquery");
}
add_action("wp_ajax_owt_ajax_lib", "owt_lib_ajax_handler_fn");
add_action("wp_ajax_nopriv_owt_ajax_lib", "owt_lib_ajax_handler_fn");
function owt_lib_ajax_handler_fn() {
$param = isset($_REQUEST['param']) ? trim($_REQUEST['param']) : "";
global $wpdb;
if (!empty($param)) {
if ($param == "get_all_posts") {
$all_posts = get_posts(array(
"post_type" => "post",
"post_status" => "publish",
'posts_per_page' => 20,
'order' => 'DESC',
'orderby' => 'date',
'cat' => 66
));
header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
echo json_encode( $all_posts );
die;
}
}
wp_die();
}
JavaScript
<button id="btn-get-all-posts">Click to get All Posts</button>
<script>
jQuery(function () {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
jQuery("#btn-get-all-posts").on("click", function () {
var postdata = "action=owt_ajax_lib¶m=get_all_posts";
jQuery.post(ajaxurl, postdata, function (response) {
console.log(response);
});
});
});
</script>
instead of use get_posts try your own query with WP_Query
here is an example code, please let me know if it works correctly(I didn't test it yet)
function owt_lib_ajax_handler_fn()
{
$param = isset($_REQUEST[ 'param' ]) ? trim($_REQUEST[ 'param' ]) : "";
if ( ! empty($param) ){
if ( $param == "get_all_posts" ){
$args = [
"post_type" => "post",
"post_status" => "publish",
"posts_per_page" => 20,
"order" => 'DESC',
"orderby" => 'date',
"category__in" => [ 66 ],
];
$all_posts = new WP_Query($args);
$json_response = [];
if ( $all_posts->have_posts() ){
while ( $all_posts->have_posts() ) {
$json_response[] = [
'title' => get_the_title(),
'content' => get_the_content(),
'acf_meta' => [
get_fields(get_the_ID()),
],
];
}
wp_send_json($json_response, 200);
wp_die();
}
else {
wp_send_json($json_response, 404);
wp_die();
}
}
}
wp_die();
}
please have a look as below:
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'post',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'color',
'value' => array('red', 'orange'),
'compare' => 'IN',
),
array(
'key' => 'featured',
'value' => '1',
'compare' => '=',
),
),
));
Please use below function:
add_action("wp_ajax_owt_ajax_lib", "owt_ajax_lib");
add_action("wp_ajax_nopriv_owt_ajax_lib", "owt_ajax_lib");
function owt_ajax_lib() {
$param = isset($_REQUEST['param']) ? trim($_REQUEST['param']) : "";
global $wpdb;
if (!empty($param)) {
if ($param == "get_all_posts") {
$args = [
"post_type" => "post",
"post_status" => "publish",
"posts_per_page" => 20,
"order" => 'DESC',
"orderby" => 'date',
"category__in" => [ 33 ],
];
$all_posts = new WP_Query($args);
$json_response = array();
if ( $all_posts->have_posts() ):
while ( $all_posts->have_posts() ) : $all_posts->the_post();
$json_response[] = [
'title' => get_the_title(),
'content' => get_the_content(),
'acf_meta' => [
get_fields( get_the_ID() ),
],
];
endwhile;
endif;
echo json_encode($json_response);
die;
}
}
die;
}
I use Select2 widget in multiply mode in YII2 framework. "kartik-v/yii2-widget-select2": "#dev" - this one I have downloaded via composer.
kartik-v/yii2-widget-select2 dev-master dd09e46
I added initial values with ajax on widget init ('initSelection'). And added another ajax method to suggest new values on user's typing. When user select one from list, it replaced initial values what were added on init. New values replace initial values, but don't another new.
I want new values to add to initial instead of replace it.
<?= $form->field($model, 'security[]')->widget(Select2::class, [
'attribute' => 'security',
'hideSearch' => true,
'data'=>$security_data,
'options' => [
'placeholder' => 'Security',
'multiple' => true,
],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 1,
'ajax' => [
'url' => Url::toRoute([ '/admin/security/select-items' ]),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }'),
'results' => new JsExpression('function(data,page) { return {results:data.results}; }'),
],
'initSelection' => new JsExpression('function(element, callback) { var id = '.Yii::$app->request->getQueryParams()['id'].';if(id !== "") {$.ajax("' . \yii\helpers\Url::toRoute([ '/admin/security/init-items' ]) . '", {data: {id: id},dataType: "json"}).done(function(data) {callback(data.results);});}}'),
],
]); ?>
And here is my api methods:
public function actionSelectItems($q = null){
Yii::$app->response->format = Response::FORMAT_JSON;
$out = ['results' => []];
if(!empty($q)){
$items = Security::find()->where(['like', 'title', $q])->all();
foreach ($items as $item){
$out['results'][] = ['id'=>$item->id, 'text'=>$item->title];
}
}
return $out;
}
public function actionInitItems($id = null){
Yii::$app->response->format = Response::FORMAT_JSON;
$adv = Adv::findOne($id);
$security = #json_decode($adv->security, true);
$out = ['results' => []];
foreach ($security as $item){
$text = Security::findOne($item)->title;
$out['results'][] = ['id'=>$item, 'text'=>$text];
}
return $out;
}
Is there some sort of settings or I missed something when handle http result?
When doing
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
$result = json_decode($response);
The response is
)]}'
["uvresp","03AJpayVHarkP_b40i5...stuff...VOrIy6m3ws",1,120]
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
The )]}' breaks things. I have no idea where that is coming from.
$g_recaptcha_response looks fine to me (what I am sending to google to verify).
The function to verify recaptcha
function verify_recaptcha ($g_recaptcha_response, $remote_address) {
# Verify captcha
$post_data = http_build_query(
array(
'secret' => 'secret',
'response' => $g_recaptcha_response,
'remoteip' => $remote_address
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $post_data
)
);
$context = stream_context_create($opts);
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
$result = json_decode($response);
return $result->success;
}
Thanks.
Ok my bad. The above code works, I had a problem further downstream (query was trying to use a column that did not exist).
For some reason this does not escape my slashes.
Whenever I manually do echo json_encode($relation, JSON_UNESCAPED_SLASHES) for example then it does work but it doesn't work with Laravel responses like below. Any fix or workaround?
return response()->json([
'card' => $card[0],
'company' => $company[0],
'identity' => $identity[0],
'haulier_declarations' => $relation,
], 200, [], JSON_UNESCAPED_SLASHES);
}
Try this :
$options = app('request')->header('accept-charset') == 'utf-8' ? JSON_UNESCAPED_UNICODE : null;
return response()->json([
'card' => $card[0],
'company' => $company[0],
'identity' => $identity[0],
'haulier_declarations' => $relation,
], 200, [], $options);
I am trying to call a custom action by ajax, but the response returned is 404, I am pretty sure its a routing issue, but I can't figure how to solve it.
here is my code:
action
public function actionGetOne($id){
$model = Driver::findOne($id);
if(!empty($model)){
$data = [];
$row = [
'id'=>$model->id,
'full_name'=>$model->full_name,
'email'=>$model->email,
'nationality_id'=>$model->nationality_id,
'current_location'=>$model->current_location,
'medical_check_id'=>$model->medical_check_id,
'img'=>$model->img,
'current_fleet_id'=>$model->current_fleet_id,
'availability'=>$model->availability
];
$data[] = $row;
echo json_encode(['driver-getOne'=>'success','data'=>$data]);
} else{
echo json_encode(['driver-getOne'=>'failure']);
}
}
ajax
$.ajax({
url:'<?= urldecode(Url::toRoute(['driver/get-one'])); ?>?id=<?= $id; ?>',
method:'post',
dataType:'json',
success:function(response){}
error:function(){
alert('target action is not found!');
}
}
backend/config/params.php
<?php
return [
'adminEmail' => 'admin#example.com',
'urlRules' => [
'' => 'site/index',
'login/' => 'site/login',
'signup/' => 'site/signup',
'<controller:[\w-]+>/<action:\w+>' => '<controller>/<action>',
'<controller:[\w-]+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:[\w-]+>/<id:\d+>' => '<controller>/view',
'<controller:[\w-]+>/create' => '<controller>/create',
'<controller:[\w-]+>/update/<id:\d+>' => '<controller>/update',
'<controller:[\w-]+>/delete/<id:\d+>' => '<controller>/delete',
'<controller:[\w-]+>/get-all' => '<controller>/get-all',
'<controller:[\w-]+>/get-one' => '<controller>/get-one',
'<controller:[\w-]+>/update-status' => '<controller>/update-status',
]
];
Change few things and try again.
Action:
public function actionGetOne($id)
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model = Driver::findOne($id);
if (empty($model)) {
return ['driver-getOne' => 'failure'];
}
return [
'driver-getOne' => 'success',
'data' => [[
'id' => $model->id,
'full_name' => $model->full_name,
'email' => $model->email,
'nationality_id' => $model->nationality_id,
'current_location' => $model->current_location,
'medical_check_id' => $model->medical_check_id,
'img' => $model->img,
'current_fleet_id' => $model->current_fleet_id,
'availability' => $model->availability
]],
];
}
Action should return something to properly finish response sequence otherwise unwanted things can happen. By setting response format you can get JSON encoded array automatically.
AJAX:
$.ajax({
url:'<?= Url::to(['driver/get-one', 'id' => $id]) ?>',
method:'post',
dataType:'json',
success:function(response){}
error:function(){
alert('target action is not found!');
}
}
Get your URL using proper syntax.
Params:
'urlRules' => [
'' => 'site/index',
'login' => 'site/login',
'signup' => 'site/signup',
'<controller:[\w-]+>/<id:\d+>' => '<controller>/view',
'<controller:[\w-]+>/<action:[\w-]+>/<id:\d+>' => '<controller>/<action>',
'<controller:[\w-]+>/<action:[\w-]+>' => '<controller>/<action>',
]
I'm assuming you are passing urlRules to components > urlManager > rules otherwise URL rules won't work.
I removed redundant rules. In general add general rules last and specific rules first.