CB AutoAction and data attributes

4 months 3 weeks ago #329439 by activha
Replied by activha on topic CB AutoAction and data attributes
Ok I see...

But has Cb the same functionalities as joomla to get the tasks that are sent by the js file and how ??
Or do I have to write one autoaction per task ?

For instance
const getAutocompleteLocation = async (sendObject) => {
            try {
                  const response = await fetch ('index.php?option=com_comprofiler&view=pluginclass&plugin=cbautoactions&action=action&actions=296&format=raw', {
                        method: 'POST',
                        mode: 'same-origin',
                        credentials: 'include',
                        headers: {
                        'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(sendObject)
                  })

               const  data = await response.json();
               
               console.log(data)
               console.log(typeof(data))
               console.log(data.success)
               if (data.success === true) {
                  console.log(data.data[0].views, 'views')
                  
              
                  const previewLocations = data.data[0].views
                  
                  const listItems = previewLocations.map(location => {
                        console.log(location)
                        return `<li data-location-id=${location.id}>${location.first}</li>`
                  })
                  .join('')

                  ul.innerHTML = listItems
                  ul.removeAttribute('hidden')
                  console.log('listItems', listItems)

                  ul.addEventListener('click', e => {
                        if (!event.target.matches('li')) return
                        const li = e.target
                        const locationName = li.textContent
                        console.log('locationName', locationName)
                        const locationId = li.dataset.locationId
                        console.log('locationId', locationId)
                        
                        input.value = locationName
                        input.setAttribute('data-location-id', locationId)
                        ul.setAttribute('hidden', true)
                        
                  })
            
               }
                 

            } catch(e){
                  console.log(e)
            }
         }

Please Log in to join the conversation.

4 months 3 weeks ago #329442 by krileon
Replied by krileon on topic CB AutoAction and data attributes

But has Cb the same functionalities as joomla to get the tasks that are sent by the js file and how ??

Yes, use $input as noted in the Code parameter description. Example as follows.

From
if ($receivedData['task'] === 'getAutoCompleteLocationData') {
To
if ( $input->getCmd( 'task', '' ) === 'getAutoCompleteLocationData' ) {

From:
                    $query = $receivedData["query"];
                    $locationId = $receivedData["location_id"];
To:
                    $query = $input->getString( 'query', '' );
                    $locationId = $input->getString( 'location_id', '' );

I've no idea why you're using the following even in Joomla.

            $content = trim(file_get_contents("php://input"));
            $receivedData = json_decode($content, true);

You had access to $app->input to get request data.


Kyle (Krileon)
Community Builder Team Member
Before posting on forums: Read FAQ thoroughly + Read our Documentation + Search the forums
CB links: Documentation - Localization - CB Quickstart - CB Paid Subscriptions - Add-Ons - Forge
--
If you are a Professional, Developer, or CB Paid Subscriptions subscriber and have a support issue please always post in your respective support forums for best results!
--
If I've missed your support post with a delay of 3 days or greater and are a Professional, Developer, or CBSubs subscriber please send me a private message with your thread and will reply when possible!
--
Please note I am available Monday - Friday from 8:00 AM CST to 4:00 PM CST. I am away on weekends (Saturday and Sunday) and if I've missed your post on or before a weekend after business hours please wait for the next following business day (Monday) and will get to your issue as soon as possible, thank you.
--
My role here is to provide guidance and assistance. I cannot provide custom code for each custom requirement. Please do not inquire me about custom development.

Please Log in to join the conversation.

4 months 3 weeks ago - 4 months 3 weeks ago #329446 by activha
Replied by activha on topic CB AutoAction and data attributes

I've no idea why you're using the following even in Joomla.

$content = trim(file_get_contents("php://input"));
$receivedData = json_decode($content, true);

You had access to $app->input to get request data.


That's written by the dev that I hired for this job.... very difficult to find experts who knows CB... they write joomla only and I have to adapt each time :-(

Wish I could find a good dev team expert in CB and plugins...



if I add &format=raw at the end of the autoaction will it output a correct json or do I have to change it for &format=json at the end ?

I tried but the autoaction only sends back
<div class="cb_template cb_template_4d95f3"></div>
in this case

It seems like the js script sends requests looking like
{"task":"getAutoCompleteLocationData","query":"xxx"}
but the $input does not receive it in the autoaction when I try to
print_r($input);exit;

Any idea why ?

Please Log in to join the conversation.

4 months 3 weeks ago #329451 by krileon
Replied by krileon on topic CB AutoAction and data attributes

That's written by the dev that I hired for this job.... very difficult to find experts who knows CB... they write joomla only and I have to adapt each time :-(

Wish I could find a good dev team expert in CB and plugins...

They don't need to know CB or Joomla. It's all documented (and for what isn't they can just ask here how to do X in regards to CB) and has autocomplete. Any PHP dev with an IDE should be able to see that. You'd just need a quality developer experienced with PHP that's capable of learning, but don't expect much from a PHP developer if you're paying them less than $50 an hour.

if I add &format=raw at the end of the autoaction will it output a correct json or do I have to change it for &format=json at the end ?

Either should work fine. CB Auto Actions will force a JSON header when using JSON output.

It seems like the js script sends requests looking like

That's because you're converting the post body to a JSON string in your fetch. That explains why the PHP was so goofy accessing the request data. I've no idea what sendObject is in your JS, but it should either be a FormData object or a JS object. Example as follows.

const formData = new FormData();

formData.append( 'task', 'getAutoCompleteLocationData' );
formData.append( 'query', 'xxx' );

This shouldn't be a POST though. This really should be a GET, which the URL can be constructed with additional data using the below.

const url = new URL( 'index.php?option=com_comprofiler&view=pluginclass&plugin=cbautoactions&action=action&actions=296&format=raw' );

url.searchParams.set( 'task', 'getAutoCompleteLocationData' );
url.searchParams.set( 'query', 'xxx' );

There's also a bunch of debug code left in your JS. Specifically all the console.log calls.


Kyle (Krileon)
Community Builder Team Member
Before posting on forums: Read FAQ thoroughly + Read our Documentation + Search the forums
CB links: Documentation - Localization - CB Quickstart - CB Paid Subscriptions - Add-Ons - Forge
--
If you are a Professional, Developer, or CB Paid Subscriptions subscriber and have a support issue please always post in your respective support forums for best results!
--
If I've missed your support post with a delay of 3 days or greater and are a Professional, Developer, or CBSubs subscriber please send me a private message with your thread and will reply when possible!
--
Please note I am available Monday - Friday from 8:00 AM CST to 4:00 PM CST. I am away on weekends (Saturday and Sunday) and if I've missed your post on or before a weekend after business hours please wait for the next following business day (Monday) and will get to your issue as soon as possible, thank you.
--
My role here is to provide guidance and assistance. I cannot provide custom code for each custom requirement. Please do not inquire me about custom development.

Please Log in to join the conversation.

4 months 2 weeks ago - 4 months 2 weeks ago #329487 by activha
Replied by activha on topic CB AutoAction and data attributes
Well I guess I chose the wrong developer and now I am just trying to correct things myself... :-)

if I correct his code as follows, is it ok to get CB to send the appropriate json ?
I cannot succeed in getting a return
document.addEventListener('DOMContentLoaded', e => {
	const options = {
		enableHighAccuracy: true,
		timeout: 5000,
		maximumAge: 0
	}

	function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}

	const typeaheadLocation = document.querySelector('.typeahead__location')

	let input
	let ul
	if (typeaheadLocation) {
		input = typeaheadLocation.querySelector('input')
		ul = typeaheadLocation.querySelector('ul')
	}

	const getAutocompleteLocation = async (sendObject) => {
		try {
			const url = new URL( 'index.php?option=com_comprofiler&view=pluginclass&plugin=cbautoactions&action=action&actions=296&format=raw' );

			url.searchParams.set( 'task', 'getAutoCompleteLocationData' );
			url.searchParams.set( 'query', inputValue );
		
			  const response = await fetch ( url , {
					method: 'GET',
					mode: 'same-origin',
					credentials: 'include',
					headers: {
					'Content-Type': 'application/json'
					}
			  })				
	

		   const  data = await response.json();
	   
		   console.log(data)
		   console.log(typeof(data))
		   console.log(data.success)
		   if (data.success === true) {
			  console.log(data.data[0].views, 'views')
		  
	  
			  const previewLocations = data.data[0].views
		  
			  const listItems = previewLocations.map(location => {
					console.log(location)
					return `<li data-location-id=${location.id}>${location.first}</li>`
			  })
			  .join('')

			  ul.innerHTML = listItems
			  ul.removeAttribute('hidden')
			  console.log('listItems', listItems)

			  ul.addEventListener('click', e => {
					if (!event.target.matches('li')) return
					const li = e.target
					const locationName = li.textContent
					console.log('locationName', locationName)
					const locationId = li.dataset.locationId
					console.log('locationId', locationId)
				
					input.value = locationName
					input.setAttribute('data-location-id', locationId)
					ul.setAttribute('hidden', true)
				
			  })
	
		   }
		 

		} catch(e){
			  console.log(e)
		}
	 }

            
	if (typeaheadLocation) {
		  input.addEventListener('input', event => {
				const input = event.target
				const inputValue = input.value.trim()
				console.log(inputValue)

				const autoLocationObjectFormData = new FormData()
				autoLocationObjectFormData.append('task', 'getAutoCompleteLocationData')
				autoLocationObjectFormData.append('query', inputValue)


				getAutocompleteLocation(autoLocationObjectFormData)

		  })
	}
	document.addEventListener('click', e => {
		const typeaheadLocation = document.querySelector('.typeahead__location')
		if (!typeaheadLocation) return
		if (!e.target.closest('.typeahead__location')) {
			ul.setAttribute('hidden', true)
		}
	})
})



Thanks a lot for your help, I'm trying to find some other devs but am stuck on this bit

Also I have an issue with the php not returning the result in the autoaction.
for instance if I use :
if ( $input->get( 'task' ) === 'getAutoCompleteLocationData' ) {
			
				//print_r($input->getString( 'query' ));
						
                $curl = curl_init();
                $query = $input->getString( 'query' );
                curl_setopt_array($curl, array(
                    CURLOPT_URL => "https://dev.societeinfo.com/app/rest/api/v2/places.json/autocomplete?query={$query}&key={$api_key}",

                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => '',
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 0,
                    CURLOPT_FOLLOWLOCATION => true,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => 'GET',
                ));

                $response_location = curl_exec($curl);
                curl_close($curl);


                //TODO: Split the company name if the result false
                $location = $response_location;

				
               // return json_decode($response_location);
				return $location;
				
				print_r( $location );
				
				
                // Save the result
            }

The print_r displays the result but the return does not.
How can I get back the $location ?

I tried to look at the $action but did not see anything regarding the return.
My autoaction is only outputting json

Please Log in to join the conversation.

4 months 2 weeks ago - 4 months 2 weeks ago #329489 by krileon
Replied by krileon on topic CB AutoAction and data attributes
I cannot help you with custom coding. The issue is not with CB Auto Actions, but with your code. Both the JS and PHP have issues.

Your PHP also just looks like an HTTP request to an external service. You can probably use a Request action for that and eliminate the need for any custom PHP entirely. Example as follows.

Method: Get
URL:
https://dev.societeinfo.com/app/rest/api/v2/places.json/autocomplete
Body:
Key: key
Value: API_KEY_HERE
Key: query
Value: [get_query]

Note you'll need latest build released today as I removed the goofy response formatting in the Request action for JSON responses since that was added before Output parameters existed, but has no use now.


Kyle (Krileon)
Community Builder Team Member
Before posting on forums: Read FAQ thoroughly + Read our Documentation + Search the forums
CB links: Documentation - Localization - CB Quickstart - CB Paid Subscriptions - Add-Ons - Forge
--
If you are a Professional, Developer, or CB Paid Subscriptions subscriber and have a support issue please always post in your respective support forums for best results!
--
If I've missed your support post with a delay of 3 days or greater and are a Professional, Developer, or CBSubs subscriber please send me a private message with your thread and will reply when possible!
--
Please note I am available Monday - Friday from 8:00 AM CST to 4:00 PM CST. I am away on weekends (Saturday and Sunday) and if I've missed your post on or before a weekend after business hours please wait for the next following business day (Monday) and will get to your issue as soon as possible, thank you.
--
My role here is to provide guidance and assistance. I cannot provide custom code for each custom requirement. Please do not inquire me about custom development.
The following user(s) said Thank You: activha

Please Log in to join the conversation.

Moderators: beatnantkrileon
Time to create page: 0.238 seconds

Facebook Twitter LinkedIn