I have a FB app that enable the user to draw shapes and type text on a canvas. The app should have a feature to share what is on canvas on FB as custom story. I was able to do that using PHP SDK.
My question is can I do the same using only JavaScript SDK without any server side code?
Thanks,
Haider
My PHP code is below:
$imgDataBase64 = $_REQUEST["imgBase64"];
$img = str_replace('data:image/png;base64,', '', $imgDataBase64);
$img = str_replace(' ', '+', $img);
$imgData = base64_decode($img);
$pictName = tempnam(sys_get_temp_dir(),"hs").".png";
$ret = file_put_contents($pictName, $imgData);
if ($fbuser) {
try {
$access_token = $facebook->getAccessToken();
$imageURI = $facebook->api(
'me/staging_resources',
'POST',
array(
'file' => "#".$pictName.";type=image/png",
'access_token' => $access_token
)
);
$object = $facebook->api(
'me/objects/testapp:photo',
'POST',
array(
'access_token' => $access_token,
'object' => array(
'app_id' => xxxxxxxxxxxxxxx,
'type' => "testapp:photo",
'title' => "test",
'image' => array (
'url' => $imageURI['uri'],
'user_generated' => true
)
)
)
);
$action = $facebook->api(
'me/testapp:share',
'POST',
array(
'photo' => $object['id'],
'access_token' => $access_token
)
);
Related
I am working on wordpress website with custom code , i am using pixel your site plugin to fire the facebook events but it is not working on the custom events so i tried to fire it on my one
here is the Code :
In Main.js file
fbq('trackCustom', 'View Review Page' , {
content_ids: ALL_Salad_Items ,
content_category: 'Salad',
content_type: 'product' ,
value: Selected_Salad_Full_Price ,
currency: 'EGP',} ,
{eventID: 'lychee.23'}); // Facebook Event for Browser
//console.log("Current Browser is " + navigator.userAgent);
//Facebook Event for Server
$.ajax({
type:'POST' ,
url: $('meta[name=ajax_url]').attr('content'),
data:{
action: 'fb_review_your_salad_event' ,
content_ids: ALL_Salad_Items ,
content_category: 'Salad',
content_type: 'product',
value: Selected_Salad_Full_Price ,
currency: 'EGP',
em: current_logged_in_user_email,
fn: current_logged_in_user_fname ,
ln: current_logged_in_user_lname ,
ph: current_logged_in_user_phone,
country: 'EG' ,
event_source_url: window.location.href ,
user_agent : navigator.userAgent
}
});
in the function.php file here is the ajax request :
add_action('wp_ajax_nopriv_fb_review_your_salad_event', 'fb_review_your_salad_event');
add_action('wp_ajax_fb_review_your_salad_event', 'fb_review_your_salad_event');
function fb_review_your_salad_event(){
global $pixel_id, $token, $event_id;
$curl = curl_init();
//Parameters
//Parameters
$event_source_url = $_POST['event_source_url'];
$content_category = $_POST['content_category'];
$content_type = $_POST['content_type'];
$User_agent = $_POST['user_agent'] ;
$content_ids = $_POST['content_ids'];
$value = $_POST['value'];
$currency = $_POST['currency'];
$em = $_POST['em'];
$fn = $_POST['fn'];
$ln = $_POST['ln'];
$ph = $_POST['ph'];
$data = json_encode(array(
"data" => array(
array(
// "event_id" => "gc.2-".$event_id."-".$content_ids,
"event_name" => "View Review Page",
"event_time" => strtotime(date('Y-m-d H:i:s')),
"event_id" => 'lychee.23' ,
"custom_data" => array(
"content_ids" => $content_ids ,
"content_type" => $content_type ,
"content_category" => $content_category,
"value" => $value ,
"currency" => $currency
),
"user_data" => array(
"client_ip_address" => $_SERVER['REMOTE_ADDR'],
"client_user_agent" => $User_agent ,
"em" => $em ,
"ph" => $ph ,
"fn" => $fn ,
"ln" => $ln ,
"country" => "EG" ,
"ct" => "cairo"
),
"event_source_url" => $event_source_url,
"action_source" => "website"
),
),
// "test_event_code" => "TEST10756"
));
curl_setopt_array($curl, array(
CURLOPT_URL => "https://graph.facebook.com/v9.0/".$pixel_id."/events?access_token=".$token,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if($err){
return "cURL Error #:" . $err;
}else{
$response = json_decode($response,true);
var_dump($response);
}
wp_die();
}
it is currently working but gives me very low matching quality [Poor] despite of sending the advanced matching parameters to the server
Using Wordpress, I'm attempting to access files from one out of two file inputs using $_FILES but running into some problems:
To outline - I'm using a front-end form that has two file fields, both of which accept multiple files:
<form id="form" action="" method="post">
<input type="text" name="my_name">
<input type="file" name="reference_images[]" multiple>
<input type="file" name="photo_of_area[]" multiple>
</form>
The file inputs will be taking images, and I need to upload images from "reference_images" to one repeater field, ad "photo_of_area" to another repeater field. This form is posted via AJAX using FormData - the functions for this are below:
function saveForm(varform) {
blockUI();
jQuery.ajax({
type: "POST",
url: window.ajaxObject.ajaxUrl,
dataType: "JSON",
data: varform,
processData: false,
contentType: false,
cache: false,
success: onSuccesPing(),
crossDomain:true,
});
}
jQuery('#form').submit(function(event) {
event.preventDefault(); // Prevent form submitting as normal
var formData = new FormData(jQuery('#form')[0]);
formData.append("action", "messaging_post");
saveForm(formData);
});
I then have a function handle the messaging_post action which is below, this creates a new post with the form data, and loops over the attached images and injects them to my ACF repeater:
add_action( 'wp_ajax_messaging_post', 'messaging_post' );
add_action('wp_ajax_nopriv_messaging_post', 'messaging_post');
function messaging_post(){
if(isset($_POST['my_name'])) {
$name = sanitize_text_field($_POST['my_name']);
$new_post = array(
'ID' => '',
'post_type' => 'quote_requests',
'post_status' => 'publish',
'post_title' => $title,
'post_content' => '',
);
$post_id = wp_insert_post($new_post);
$post = get_post($post_id);
update_field('name', $name, $post_id); // Updates the ACF text field 'name' for the inserted post
// Works, but uploads files from BOTH file inputs to the single ACF repeater:
foreach($_FILES as $value){
for ($i=0; $i <count($value['name']); $i++) {
$errors= array();
$file_name = $value['name'][$i];
$file_size = $value['size'][$i];
$file_tmp = $value['tmp_name'][$i];
$file_type = $value['type'][$i];
$file_ext=strtolower(end(explode('.',$value['name'][$i])));
if(empty($errors)==true) {
$wordpress_upload_dir = wp_upload_dir();
$profilepicture = $wordpress_upload_dir['path'].'/';
move_uploaded_file($file_tmp, $profilepicture.$file_name);
} else{
print_r($errors);
}
$file_name_and_location = $profilepicture.$file_name;
$file_title_for_media_library = $value['name'][$i];
$fildename = $value['name'][$i];
$arr_file_type = wp_check_filetype(basename($fildename));
$uploaded_file_type = $arr_file_type['type'];
$attachment = array(
'post_mime_type' => $uploaded_file_type,
'post_title' => addslashes($file_title_for_media_library),
'post_content' => $fildename,
'post_status' => 'inherit',
'post_parent' => 0,
'post_author' => get_current_user_id(),
);
wp_read_image_metadata( $file_name_and_location );
$attach_id = wp_insert_attachment( $attachment, $file_name_and_location,true,false);
$attach_data = wp_generate_attachment_metadata($attach_id,$file_name_and_location );
wp_update_attachment_metadata( $attach_id, $attach_data );
$images[]= array("image" => $attach_id);
}
}
update_field('photo_area', $images, $post_id);
}
}
The above works, and populates the created post with the name from the form, but this attaches files from BOTH the reference_images and photo_of_area to the photo_area ACF repeater.
When trying to access $_FILES using a function such as the following:
foreach($_FILES["photo_of_area"] as $value){
for ($i=0; $i <count($value['name']); $i++) {
$errors= array();
$file_name = $value['name'][$i];
$file_size = $value['size'][$i];
$file_tmp = $value['tmp_name'][$i];
$file_type = $value['type'][$i];
$file_ext=strtolower(end(explode('.',$value['name'][$i])));
if(empty($errors)==true) {
$wordpress_upload_dir = wp_upload_dir();
$profilepicture = $wordpress_upload_dir['path'].'/';
move_uploaded_file($file_tmp, $profilepicture.$file_name);
} else{
print_r($errors);
}
$file_name_and_location = $profilepicture.$file_name;
$file_title_for_media_library = $value['name'][$i];
$fildename = $value['name'][$i];
$arr_file_type = wp_check_filetype(basename($fildename));
$uploaded_file_type = $arr_file_type['type'];
$attachment = array(
'post_mime_type' => $uploaded_file_type,
'post_title' => addslashes($file_title_for_media_library),
'post_content' => $fildename,
'post_status' => 'inherit',
'post_parent' => 0,
'post_author' => get_current_user_id(),
);
wp_read_image_metadata( $file_name_and_location );
$attach_id = wp_insert_attachment( $attachment, $file_name_and_location,true,false);
$attach_data = wp_generate_attachment_metadata($attach_id,$file_name_and_location );
wp_update_attachment_metadata( $attach_id, $attach_data );
$images[]= array("image" => $attach_id);
}
}
update_field('photo_area', $images, $post);
This doesn't seem to work and returns nothing.
I'm assuming that after going through FormData(), the files are now not accessible on the normal $_FILES['name_of_input'], and should rather have something else done with them?
I've also tried just appending the images to the FormData, but seemed to be having the same issue.
Would anyone be able to shed some light on how I could access $_FILES["photo_of_area"], and also $_FILES["reference_images"] independently of each other after being passed through FormData()? Or any alternative ways that I should look at to achieve the desired behaviour.
Ideally, I need to access images from each file input respectively.
Thanks!
I've managed to achieve this by changing my loop over the $_FILES array as such:
$photo_of_area = $_FILES["photo_of_area"];
foreach ($photo_of_area['name'] as $key => $value) {
$errors = array();
$file_name = $photo_of_area['name'][$key];
$file_size = $photo_of_area['size'][$key];
$file_tmp = $photo_of_area['tmp_name'][$key];
$file_type = $photo_of_area['type'][$key];
$file_ext = strtolower(end(explode('.',$photo_of_area['name'][$key])));
if (empty($errors) == true) {
$wordpress_upload_dir = wp_upload_dir();
$upload_dir_path = $wordpress_upload_dir['path'].'/';
move_uploaded_file($file_tmp, $upload_dir_path.$file_name);
} else {
print_r($errors);
}
$file_name_and_location = $upload_dir_path.$file_name;
$file_title_for_media_library = $photo_of_area['name'][$key];
$fildename = $photo_of_area['name'][$key];
$arr_file_type = wp_check_filetype(basename($fildename));
$uploaded_file_type = $arr_file_type['type'];
$attachment = array(
'post_mime_type' => $uploaded_file_type,
'post_title' => addslashes($file_title_for_media_library),
'post_content' => $fildename,
'post_status' => 'inherit',
'post_parent' => 0,
'post_author' => get_current_user_id(),
);
wp_read_image_metadata( $file_name_and_location );
$attach_id = wp_insert_attachment( $attachment, $file_name_and_location,true,false);
$attach_data = wp_generate_attachment_metadata($attach_id,$file_name_and_location );
wp_update_attachment_metadata( $attach_id, $attach_data );
$area_photos_array[] = array("image" => $attach_id);
}
update_field('photo_area', $area_photos_array, $post_id);
This successfully injects each image uploaded to a new row of the photo_area repeater inside the current post specified by $post_id.
I'm trying to make a "meal" in my DB, so in my website i made a form with a name, and a picture. This is the code of the form :
<?php
$new_meal_title = htmlentities($_POST["new_meal_title"]);
$new_meal_img = htmlentities($_POST["new_meal_img"]);
$data = array(
'new_meal_title' => $new_meal_title,
'new_meal_img' => base64_encode($new_meal_img)
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents(constant("API_URL")."/meal", false, $context);
if($result === FALSE){
var_dump($result);
}
$json = json_decode($result);
if($json->success == "true"){
header('Location: ../../');
return;
}
else{
echo $json->message;
}
header('Location: ../../');
?>
The form is sending data to my Node API. My Question is, how to save into a folder the image path through form in Javascript after it has been received in JSON.
Thanks for your help, i just had to change this line :
$new_meal_img = htmlentities($_POST["new_meal_img"]);
By
$new_meal_img = $_FILES['new_meal_img']["tmp_name"];
And
'new_meal_img' => base64_encode($new_meal_img)
By
'new_meal_img' => base64_encode(file_get_contents($new_meal_img))
I am having a problem getting a custom query to alphabetize. It keeps defaulting to displaying in the order of the date it was posted. Below is my php function.
function json_info2() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// get values for all three drop-down menus
$status = $_REQUEST['status'];
$industry = $_REQUEST['services'];
$state = $_REQUEST['state'];
// array of values for each of the three drop-downs
$statusAll = array('complete','incomplete');
$industryAll = array('mining','textile','machinery');
$statesAll = array('SC','TX','WA');
// set $statusArray dependent on whether or not "all" is selected in the dropdown menu
if($status == "all") {
$statusArray = array( 'key' => 'status', 'value' => $statusAll, 'compare' => 'IN');
} else {
$statusArray = array( 'key' => 'status', 'value' => $status, 'compare' => '=');
}
if($industry == "all") {
$industryArray = array( 'key' => 'industry', 'value' => $industryAll, 'compare' => 'IN');
} else {
$industryArray = array( 'key' => 'industry', 'value' => $industry, 'compare' => '=');
}
if($state == "all") {
$stateArray = array( 'key' => 'state', 'value' => $statesAll, 'compare' => 'IN');
} else {
$stateArray = array( 'key' => 'state', 'value' => $state, 'compare' => '=');
}
$pages = array(
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged,
'posts_per_page' => 5,
'meta_query' => array(
'relation' => 'AND',
$statusArray,
$industryArray,
$stateArray,
array(
'key' => '_wp_page_template',
'value' => 'template-individual-project.php',
'compare' => '='
)
)
);
// query results by page template
$my_query = new WP_Query($pages);
if($my_query->have_posts()) :
while($my_query->have_posts()) :
$my_query->the_post();
<li>
<?php the_title(); ?>
</li>
<?php
endwhile;endif;
wp_reset_query();
} // end of isset
?>
<?php
die();
}
add_action( 'wp_ajax_json_info2', 'json_info2' );
add_action( 'wp_ajax_nopriv_json_info2', 'json_info2' );
?>
This above function is called by the ajax function that follows:
function do_ajax() {
// Get values from all three dropdown menus
var state = $('#states').val();
var markets = $('#markets').val();
var services = $('#services').val();
$.ajax({
url: ajaxurl,
data: {
'action' : 'json_info2',
'state' : state,
'status' : markets,
'services' : services
},
success:function(moredata) {
// This outputs the result of the ajax request
$('#project-list').html( moredata );
$('#project-list').fadeIn();
}/*,
error: function(errorThrown){
var errorMsg = "No results match your criteria";
$('#project-list').html(errorMsg);
}*/
}); // end of ajax call
} // end of function do_ajax
Is there something simple that I'm missing here? I have a similar custom query on the page when it loads (although that initial load query doesn't have the select menu values as args), and they display in alphabetical order just fine. It's only after the ajax call to filter the list that they are no longer in order.
I have found the issue after googling the problem for quite a while. I read that some of the people who were having this problem found that their theme was using a plugin called Post Types Order. It overrides the ability to set the orderby arg.
I looked at the plugins, and sure enough, Post Types Order was there. Everything I read said that the problem could be solved by unchecking "auto sort" in the settings for the plugin. However, I did that, and orderby still didn't work. I had to completely deactivate the plugin to get orderby title to work.
Am using Yii and Activehighcharts to show charts.
http://www.yiiframework.com/extension/activehighcharts
controller is as follows
public function actionChartView(){
$dataProvider=new CActiveDataProvider('ChartData',array(
'criteria'=>array(
'condition'=>'dID=2',
'order'=>'time ASC',
),
'pagination'=>array(
'pageSize'=>50,
),
)
);
$p=$dataProvider->pagination;
$p->setItemCount($dataProvider->getTotalItemCount());
$p->currentPage=$p->pageCount-1;
if(isset($_GET['json']) && $_GET['json'] == 1){
$count = ChartData::model()->count();
for($i=1; $i<=$count; $i++){
$data = ChartData::model()->findByPk($i);
$data->data += rand(-10,10);
$data->save();
}
echo CJSON::encode($dataProvider->getData());
}
else{
$this->render('ChartView',array('dataProvider'=>$dataProvider,));
}
}
View as
$this->Widget('ext.ActiveHighcharts.HighchartsWidget', array(
'dataProvider'=>$dataProvider,
'template'=>'{items}',
'id'=>'Temperature',
'options'=> array(
'title'=>array(
'text'=>'Temperature'
),
'chart'=>array(
"zoomType"=>'x',
),
'xAxis'=>array(
'title' => array('text' => 'Time',),
'categories' => 'time',
'labels' => array(
'rotation' => -90,
'y' => 20,
),
),
'yAxis'=>array(
'title' => array('text' => 'DegC'),
),
'series'=>array(
array(
'type'=>'areaspline',
'name'=>'Temperature', //title of data
'dataResource'=>'data', //data resource according to datebase column
)
),
)
));
i need to update the chart in every 2 minutes with ajax.
also i need to get old data.
how to handle these scenarios.
in your ajax call success call back update the data in the chart using the api methods provided in highcharts documentation.
please refer this link it will help you to find a good solution.
Ok. To best answer your question i will try to clear things as much as possible.
First you need to create a view (a php file that will contain your highchart code)
Second you need to edit your Controller (let's assume siteController) and create an action to call the view you've just create. Inside that action you will need to connect and query the database.
See the below sample code:
siteController action:
public function actionAtencionesMensuales() {
$sql = Yii::app()->db->createCommand('
SELECT DISTINCT MONTH(hora) as mes, count(*) as total
FROM visitas
WHERE YEAR(hora)=YEAR(CURDATE())
GROUP BY MONTH(hora)')->queryAll();
$mes = array();
$total = array();
for ($i = 0; $i < sizeof($sql); $i++) {
$mes[] = $sql[$i]["mes"];
$total[] = (int) $sql[$i]["total"];
}
$this->render('my_view', array('mes' => $mes, 'total' => $total));
}
}
In the View:
<?php
$this->Widget('ext.highcharts.HighchartsWidget', array(
'options' => array(
'exporting' => array('enabled' => true),
'title' => array('text' => 'Mes'),
'theme' => 'grid',
'rangeSelector' => array('selected' => 1),
'xAxis' => array(
'categories' => $mes
),
'yAxis' => array(
'title' => array('text' => 'Cantidad')
),
'series' => array(
array('name' => 'Total', 'data' => $total = array_map('intVal', $total)),
)
)
));
?>
Within the series of the chart, it's better to use when calling the variable:
$total = array_map('intVal', $total)
Instead of just:
$total
Good luck :)