WordPress wp_localize_script : PHP variable not recognized by JS script - javascript

I am trying to modify a script (ajaxcalls.js) in my WordPress via my child theme. I created a duplicate of the file in the child theme (ajaxcalls_child.js).
I added the following code inside the function.php file in order to dequeue the old JS file, enqueue the new one and pass the variable ajaxcalls_vars which ajaxcalls_child.js uses:
<?php
//made sure here that the action execute after all the other scripts are loaded
add_action('wp_enqueue_scripts', 'wpestate_load_child_scripts', 100);
function wpestate_load_child_scripts() {
wp_dequeue_script('wpestate_ajaxcalls');
wp_enqueue_script('ajaxcalls_child', get_stylesheet_directory_uri().'/js/ajaxcalls_child.js', array('jquery'),'1.0', true);
wp_localize_script(‘ajaxcalls_child’, ‘ajaxcalls_vars’, array(
'contact_name' => esc_html__( 'Your Name','wprentals'),
'contact_email' => esc_html__( 'Your Email','wprentals'),
'contact_phone' => esc_html__( 'Your Phone','wprentals'),
'contact_comment' => esc_html__( 'Your Message','wprentals'),
'adv_contact_name' => esc_html__( 'Your Name','wprentals'),
'adv_email' => esc_html__( 'Your Email','wprentals'),
'adv_phone' => esc_html__( 'Your Phone','wprentals'),
'adv_comment' => esc_html__( 'Your Message','wprentals'),
'adv_search' => esc_html__( 'Send Message','wprentals'),
'admin_url' => get_admin_url(),
'login_redirect' => $login_redirect,
'login_loading' => esc_html__( 'Sending user info, please wait...','wprentals'),
'userid' => $userID,
'prop_featured' => esc_html__( 'Property is featured','wprentals'),
'no_prop_featured' => esc_html__( 'You have used all the "Featured" listings in your package.','wprentals'),
'favorite' => esc_html__( 'Favorite','wprentals').'<i class="fas fa-heart"></i>',
'add_favorite' => esc_html__( 'Add to Favorites','wprentals'),
'remove_favorite' => esc_html__( 'remove from favorites','wprentals'),
'add_favorite_unit'=> esc_html__( 'add to favorites','wprentals'),
'saving' => esc_html__( 'saving..','wprentals'),
'sending' => esc_html__( 'sending message..','wprentals'),
'reserve' => esc_html__( 'Reserve Period','wprentals'),
'paypal' => esc_html__( 'Connecting to Paypal! Please wait...','wprentals'),
'stripecancel' => esc_html__( 'subscription will be cancelled at the end of the current period','wprentals'),
'max_month_no' => intval ( get_option('wp_estate_month_no_show','') ),
'processing' => esc_html__( 'processing..','wprentals'),
'home' => get_site_url(),
'delete_account' => esc_html__('Confirm your ACCOUNT DELETION request! Clicking the button below will result your account data will be deleted. This means you will no longer be able to login to your account and access your account information: My Profile, My Reservations, My bookings, Invoices. This operation CAN NOT BE REVERSED!','wprentals'),
'adv_search_what_half' => $adv_search_what_half,
'adv_search_how_half' => $adv_search_how_half,
'adv_search_type' => $adv_search_type
));
}
Now after I visit my website, I can see that the old script has been replaced by the new one but I can see on the chrome console that ajaxcalls_vars is not defined as soon as the a function needs it in the new script.
Error on the chrome console
So the new script is there but my variable ajaxcalls_vars is not defined according to ajaxcalls_child.js, therefore, I think there is something wrong in the way I try to pass that variable to the new script.
After looking at similar issue, I understood other type of mistake and tried to improve that code up to the one I shared above. But still can not get it right.

Your single quotes around the first 2 args in wp_localize_script(‘ajaxcalls_child’, ‘ajaxcalls_vars’, array(... are not real single quotes. Try deleting them and replacing with the ' character wp_localize_script('ajaxcalls_child', 'ajaxcalls_vars', array(...
Once I did that, the object is available in the enqueued script (tested on xampp wp 5.0)

Related

Laravel 6.0 Stripe: Must provide source or customer

I'm trying to process a credit card payment and I get this error: Must provide source or customer.
I'm not sure what Stripe means by this and I've tried the solution posted here: Stripe: Must provide source or customer
public function store(Request $request)
{
try {
$charge = Stripe::charges()->create([
// 'amount' => getNumbers()->get('newTotal') / 100,
'currency' => 'UK',
'source' => $request->stripeToken,
'description' => 'Thank you for your purchase.',
'receipt_email' => $request->email,
'customer' => $request->email,
'metadata' => [
// 'contents' => $contents,
'quantity' => Cart::count(),
],
]);
Cart::destroy();
return redirect()->route('confirmation.index')->with('success_message', 'Thank you! Your payment has been successfully accepted!');
} catch (CardErrorException $e) {
return back()->withErrors('Error! ' . $e->getMessage());
}
}
As you can see, I do have a source and a customer. If I change the $customer property to equal something like 'person', Stripe will return this: No such customer: person
What exactly am I doing wrong here?
EDIT: The library I'm using is cartalyst/stripe-laravel: https://github.com/cartalyst/stripe-laravel
Thanks

Update text in block with Nodejs integration module in drupal 8

Below is information what I have done till now and what I am trying to do.
What I have done till now
Nodejs module and drupal 8 done. Example modules are working fine.
Created a simple module in drupal 8 consists of a form called simple
form. On its submit function, called nodejs module function to enqueue my message to the channel.
Javascript callback function created defined in nodejs enqueue message.
What I have been trying to acheive
When submitting a text form. Just to update the block in drupal 8.( Update the block content with hello world.)
Problem
My javascript callbacks associated with nodejs aren't being called.
Below are my codes.
Submit Function Code
public function submitForm(array &$form, FormStateInterface $form_state) {
/*$message->broadcast = TRUE;
* This would normally be replaced by code that actually does something
* with the title.
*/
$title = $form_state->getValue('title');
$message = (object) array(
'channel' => 'example',
'broadcast' => TRUE,
'callback' => 'example',
'data' => array(
'message' => 'Hello World'
),
);
nodejs_enqueue_message($message);
drupal_set_message(t('You specified a title of %title.', ['%title' => $title]));
}
Javascript callback code
(function ($) {
Drupal.Nodejs.callbacks.example = {
//grab the message and inject into the header
callback: function (message) {
console.log('simple example');
if(message.channel == 'example') {
$('#nodejs-selector').html(message.data.body);
}
}
};
})(jQuery);
Any help on this, I would be very grateful. I would love to provide more information on this, if anyone needed.
You should modify $message as
$message = (object) array(
'channel' => 'example',
'broadcast' => TRUE,
'callback' => 'example',
'data' => array(
'body' => 'Hello World'
),
);
To access the message body as message.data.body

How to use instafeed.js to get logged in users images

I'm building an application where users can click a button to show all of their Instagram images on a page, but in order to do that I need userId and accessToken. How do I get these?
NOTE: If it makes any difference: I'm not trying to get just my own images, but anyone who uses my app to log into their account.
I have this code:
<script>
var feed = new Instafeed ({
get: "user",
userId: ,
accessToken: ""
});
feed.run();
</script>
<div id="instafeed"></div>
And I get a verification code by clicking on a link (note I removed cliend_id and redirect_uri):
Get Instagram images
Then this returns a code like '1251251...' which I grab with GET, but after that what do I do? How do I get userId and accesToken from this?
I'm not sure if I'm on the right track, but any help would be appreciated!
Answering my own question, as I figured it out:
$url = 'https://api.instagram.com/oauth/access_token';
$data = array(
'client_id' => $clientId,
'client_secret' => $clientSecret,
'grant_type' => 'authorization_code',
'redirect_uri' => $redirectUri,
'code' => $code
);
// use key 'http' even if you send the request to https://...
$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($url, false, $context);
$clientId, $clientSecret and $redirectUri are taken from: https://instagram.com/developer/clients/manage/
$code is the code from your url and $result contains the userId and accessToken if successful.
Thanks to: How do I send a POST request with PHP?

Call a function in JS file from drupal

I have included a javascript in the module "myid" I've been developing in drupal by using this code:
function myid_init() {
drupal_add_js(drupal_get_path("module", "myid") . "js/myid.js");
}
This is my Javascript file "myid.js":
function myid_js_start(){
alert("hello world");
}
Below is the code that creates a button that invokes an alert function:
$form['add_button'] = array(
'#type' => 'button',
'#value' => 'Take a picture',
'#attributes' => array('onclick' => 'myid_js_start()'),
);
I dont know where did I go wrong. The button shows up but doesn't fire any alert function. Can anyone help me with this?
If you have followed the proper drupal directory structures and everything is where it supposed to be then it could be you are setting the attributes[onclick] as 'myid_js_start()'. Try doing it like
$form['add_button'] = array(
'#type' => 'button',
'#value' => 'Take a picture',
'#attributes' => array('onclick' => 'myid_js_start'),
);
Maybe that will solve it.
I don't have a drupal system setup at the moment to test your code. It could be something else but worth a try.
Attach the .js file to the form itself using #attach.
$form['#attached']['js'] = array(
drupal_add_js(drupal_get_path("module", "myid") . "js/myid.js"),
);

Posting a link with image and text to Facebook wall

I am trying to replicate the functionality to share a story on a Facebook wall similar to what this site has.
When you click on the share it should ask you to authenticate to facebook, if you are already authenticated it should show you the story to post to facebook.
I got the authentication part to work using the JavaScript SDK . I am not sure how to show the content to post to the wall.
Could anyone please provide an example.
Thanks!
<?php
# We require the library
require("facebook.php");
# Creating the facebook object
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
'cookie' => true
));
# Let's see if we have an active session
$session = $facebook->getSession();
if(!empty($session)) {
# Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
try{
$uid = $facebook->getUser();
# let's check if the user has granted access to posting in the wall
$api_call = array(
'method' => 'users.hasAppPermission',
'uid' => $uid,
'ext_perm' => 'publish_stream'
);
$can_post = $facebook->api($api_call);
if($can_post){
# post it!
# $facebook->api('/'.$uid.'/feed', 'post', array('message' => 'Saying hello from my Facebook app!'));
# using all the arguments
$facebook->api('/'.$uid.'/feed', 'post', array(
'message' => 'The message',
'name' => 'The name',
'description' => 'The description',
'caption' => 'The caption',
'picture' => 'http://i.imgur.com/yx3q2.png',
'link' => 'http://net.tutsplus.com/'
));
echo 'Posted!';
} else {
die('Permissions required!');
}
} catch (Exception $e){}
} else {
# There's no active session, let's generate one
$login_url = $facebook->getLoginUrl();
header("Location: ".$login_url);
}
?>
http://developers.facebook.com/docs/reference/api/post/

Categories

Resources