Search the Community
Showing results for tags 'Ajax'.
-
Hey all! This is a module to enhance forms built using the Pro FormBuilder module by providing the ability to submit them in place using AJAX and HTMX. FormBuilderHtmx works in harmony with FormBuilder by handling front-end rendering and AJAX and lets FormBuilder manage form configuration and processing. FormBuilderHtmx provides a drop-in replacement for the $forms->render() method and provides all native features and behavior (and adds a few extra superpowers to boot). Noteworthy features: Zero configuration, install and render AJAX powered FormBuilder forms immediately Render multiple forms on the same page. Supports both multiple instances of the same form or different forms. Each form is processed independently. Non-intrusive, can be used alongside FormBuilder's native rendering methods and does not modify core module behavior Perfect for forms embedded in popups and modals Does not conflict with styling and other JavaScript already in-place, only handles the form submission/response loop Automatically disables the `Submit` button on submission to prevent duplicate requests Provides the ability to add a custom 'spinner' shown when a form is being processed Gives you the ability to add additional HTML attributes to your FormBuilder <form> element. Add additional custom functionality using HTMX attributes, hook into form actions with your JavaScript, or even add AlpineJS directly to your forms. Compatible with FieldtypeFormSelect, let users choose which forms to embed, your code determines how they are rendered Uses HTMX, a stable, powerful, and tiny (14kb gzipped) library, installation documentation available here This module is BYOH (Bring Your Own HTMX) in that the HTMX library is not included or available within this module. This ensures long-term stability by not locking FormBuilderHtmx to external asset versioning. FormBuilderHtmx uses stable core HTMX features so use the library version that works for you and confidently add this module to both new, existing, and future ProcessWire applications. In some instances CSRF protection may need to be disabled to submit forms with this module. Just test your forms and you're good to go. Using this module is truly easy. <!-- Replace the native $forms->render() method with $htmxForms->render() --> <?php $htmxForm = $htmxForms->render('your_form_name') ?> <!-- Use native ProcessWire properties and methods as usual --> <?php echo $htmxForm->styles; echo $htmxForm->scripts; echo $htmxForm; ?> Presto. You can optionally include a helpful 'spinner' or activity animation that will be showed to users while their form request is being processed. Check out these ready-to-go examples you can use in your projects. <style> /* Add these styles to your CSS, the `.htmx-request` must be present as shown here. Be sure to include any CSS your 'spinner' may need, and style everything as desired */ .activity-indicator { display: none; } .htmx-request .activity-indicator, .htmx-request.activity-indicator { display: block; } </style> <!-- Optional second argument matches that of the $forms->render() method for pre-populated values The third argument is the CSS selector matching your 'spinner' element --> <?= $htmxForms->render('your_form_name', [], '#indicator-for-the-form') ?> <div id="indicator-for-the-form" class="activity-indicator"> <span class="spinner"></span> </div> Presto (again) Check out the documentation for detailed usage and other available features. Pull requests and issues filed on Github are welcome, or drop by here to get some help! Install as a ProcessWire module Install using Composer Download from the FormBuilderHtmx Github repository . Cheers!
- 26 replies
-
- 26
-
- formbuilder
- ajax
-
(and 1 more)
Tagged with:
-
Hello, I have a problem with all AJAX -requests getting 301 redirect. AFAIK this leads to the POST -data sent with the request getting cleared. Below I is an example about what I'm trying to do. My question is: Is there something I don't understand about Processwire or internet technology which is causing this behaviour?I have page with a button. When you click this button, an HTML overlay popup (done with Foundation and Reveal) with option to enter email is displayed (The content of this popup is a processwire template which is loaded with AJAX -request. Causes also 301 redirect, but this doesn't use POST -data, so I didn't realise the problem at this point) Then this data is sent as POST -request with payload to processwire for processing The processing is done by special API -template, which exists solely for this purpose of processing data. However the payload in the POST -request never reaches the API -template I believe this is because a 301 redirect happens before the the POST -request reaches the API -template Thanks for reading and special thanks for any answers! Example code: Popup (HTML & JavaScript): <!-- use onsubmit to override the standard 'sending form to self' -behaviour <form onsubmit="WEBSITE.dialog.download.mail($('#email').val(), event); "> <label>email:</label> <input id='email' name='email' type='email' value=''> <input type="submit" value="Send"> </from> The function which sends the POST -request to processwire template (which processes API requests) (the function is in separate .js file) // I've translated this from CoffeeScript to JS without testing, hope there's no errors dialog = { download: { mail: function (email, ev){ // Prevent default behaviour of submit -functionality ev.preventDefault(); // Success and error callbacks success = function(response){ console.log('success', response); } error = function(response){ console.log('error', response); } // Do ajax -request with jQuery request = $.ajax({ url: '/api/mailer/send/', method: "POST", data: {email: email}, success: success, error: error }); } } } I've also tried this with doing the request without jQuery, but result is the same. The API template (PHP): ?php // Redirect non-ajax calls // Get the API address from url $api_url = explode('/api/', $page->url); if(!isset($api_url[1])){ // This url is not in correct format, send error die(createJSONResponseError( 1, 'Invalid url format.' ) ); } switch ($api_url[1]): case 'mailer/send/': // This is where it stops every time, though I've checked from Chrome dev console that the email key/value pair exists (at least when request is made) if($input->post->email === null){ die(createJSONResponseError( 2, 'Insufficient params.' ) ); }else{ // Create the response $response = createJSONResponse( 'success', null ); } break; // Default action - needs to be last of the list default: // So this api does not exist, send error die(createJSONResponseError( 1, 'Unknown API.' ) ); break; endswitch; // Send the response die($response); ?> Here's how the responses are created (from a helper methods file): /** * Create JSON response for httpXMLRequest * * @param status - a string that represents the status of this operation. Recommended values: 'success' or 'error' * @param result - the data resulting this request. * * @return JSON object * */ function createJSONResponse($status, $result){ return json_encode( array( 'status' => $status, 'result' => $result ) ); } /** * Create JSON error response for httpXMLRequest * * @param code - error code * @param msg - error message * * @return JSON object * */ function createJSONResponseError($code, $msg){ return createJSONResponse( 'error', array( 'code' => $code, 'msg' => $msg ) ); }
-
Hi, here is a task thats new to me. And obviously i overlook some basics. So maybe someone is so kind to give me some advice on this... I have a page whichs collects some contact boxes straight away on page load. It is a multilanguage Site (default is in German, the screenshots shows the english version). The results are wrapped in a form, because the user is able to narrow the resulting contacts by a page reference language switcher (values are part of every contact entry)*. This is done with a javascript ajax request to avoid page reloads. TL;DR: While everything is fine on page load, as soon as i select a country to get the related contact boxes by a ajax call, the static translated strings within the target PHP file are not recognized, e.g. their translation fails. I assume i simply miss some basics here what and when things get parsed when doing such asynchron call. *) The language switcher values has nothing to do with the choosen user language. And for the brave ones... On Page load: The highlighted areas are static translated strings (s. below). All is fine on page load (whatever current user language). If the user selects a country within the language switcher, the form in submitted per JS, do a ajax call and query the results by the giving value of the select option (more details s. below). The result is valid and looks like this (here i narrowed the result to contacts related to germany): BUT: As you can see, the static translation strings (s. highlighted areas) are not translated (e.g. use the default site language). To give a brief overview how its done, here some excerpt screens. Form tag with action target: Javascript: And here is the processing target PHP file (excerpt): contacts-flatproducts.php Many thanks in advance, Olaf
-
Page Query Boss Build complex nested queries containing multiple fields and pages and return an array or JSON. This is useful to fetch data for SPA and PWA. You can use the Module to transform a ProcessWire Page or PageArray – even RepeaterMatrixPageArrays – into an array or JSON. Queries can be nested and contain closures as callback functions. Some field-types are transformed automatically, like Pageimages or MapMarker. Installation Via ProcessWire Backend It is recommended to install the Module via the ProcessWire admin "Modules" > "Site" > "Add New" > "Add Module from Directory" using the PageQueryBoss class name. Manually Download the files from Github or the ProcessWire repository: https://modules.processwire.com/modules/page-query-builder/ Copy all of the files for this module into /site/modules/PageQueryBoss/ Go to “Modules > Refresh” in your admin, and then click “install” for the this module. Module Methods There are two main methods: Return query as JSON $page->pageQueryJson($query); Return query as Array $page->pageQueryArray($query); Building the query The query can contain key and value pairs, or only keys. It can be nested and contain closures for dynamic values. To illustrate a short example: // simple query: $query = [ 'height', 'floors', ]; $pages->find('template=skyscraper')->pageQueryJson($query); Queries can be nested, contain page names, template names or contain functions and ProcessWire selectors: // simple query: $query = [ 'height', 'floors', 'images', // < some fileds contain default sub-queries to return data 'files' => [ // but you can also overrdide these defaults: 'filename' 'ext', 'url', ], // Assuming there are child pages with the architec template, or a // field name with a page relation to architects 'architect' => [ // sub-query 'name', 'email' ], // queries can contain closure functions that return dynamic content 'querytime' => function($parent){ return "Query for $parent->title was built ".time(); } ]; $pages->find('template=skyscraper')->pageQueryJson($query); Keys: A single fieldname; height or floors or architects The Module can handle the following fields: Strings, Dates, Integer… any default one-dimensional value Page references Pageimages Pagefiles PageArray MapMarker FieldtypeFunctional A template name; skyscraper or city Name of a child page (page.child.name=pagename); my-page-name A ProcessWire selector; template=building, floors>=25 A new name for the returned index passed by a # delimiter: // the field skyscraper will be renamed to "building": $query = ["skyscraper`#building`"] Key value pars: Any of the keys above (1-5) with an new nested sub-query array: $query = [ 'skyscraper' => [ 'height', 'floors' ], 'architect' => [ 'title', 'email' ], ] A named key and a closure function to process and return a query. The closure gets the parent object as argument: $query = [ 'architecs' => function($parent) { $architects = $parent->find('template=architect'); return $architects->arrayQuery(['name', 'email']); // or return $architects->explode('name, email'); } ] Real life example: $query = [ 'title', 'subtitle', // naming the key invitation 'template=Invitation, limit=1#invitation' => [ 'title', 'subtitle', 'body', ], // returns global speakers and local ones... 'speakers' => function($page){ $speakers = $page->speaker_relation; $speakers = $speakers->prepend(wire('pages')->find('template=Speaker, global=1, sort=-id')); // build a query of the speakers with return $speakers->arrayQuery([ 'title#name', // rename title field to name 'subtitle#ministry', // rename subtitle field to ministry 'links' => [ 'linklabel#label', // rename linklabel field to minlabelistry 'link' ], ]); }, 'Program' => [ // Child Pages with template=Program 'title', 'summary', 'start' => function($parent){ // calculate the startdate from timetables return $parent->children->first->date; }, 'end' => function($parent){ // calculate the endate from timetables return $parent->children->last->date; }, 'Timetable' => [ 'date', // date 'timetable#entry'=> [ 'time#start', // time 'time_until#end', // time 'subtitle#description', // entry title ], ], ], // ProcessWire selector, selecting children > name result "location" 'template=Location, limit=1#location' => [ 'title#city', // summary title field to city 'body', 'country', 'venue', 'summary#address', // rename summary field to address 'link#tickets', // rename ticket link 'map', // Mapmarker field, automatically transformed 'images', 'infos#categories' => [ // repeater matrix! > rename to categories 'title#name', // rename title field to name 'entries' => [ // nested repeater matrix! 'title', 'body' ] ], ], ]; if ($input->urlSegment1 === 'json') { header('Content-type: application/json'); echo $page->pageQueryJson($query); exit(); } Module default settings The modules settings are public. They can be directly modified, for example: $modules->get('PageQueryBoss')->debug = true; $modules->get('PageQueryBoss')->defaults = []; // reset all defaults Default queries for fields: Some field-types or templates come with default selectors, like Pageimages etc. These are the default queries: // Access and modify default queries: $modules->get('PageQueryBoss')->defaults['queries'] … public $defaults = [ 'queries' => [ 'Pageimages' => [ 'basename', 'url', 'httpUrl', 'description', 'ext', 'focus', ], 'Pagefiles' => [ 'basename', 'url', 'httpUrl', 'description', 'ext', 'filesize', 'filesizeStr', 'hash', ], 'MapMarker' => [ 'lat', 'lng', 'zoom', 'address', ], 'User' => [ 'name', 'email', ], ], ]; These defaults will only be used if there is no nested sub-query for the respective type. If you query a field with complex data and do not provide a sub-query, it will be transformed accordingly: $page->pageQueryArry(['images']); // returns something like this 'images' => [ 'basename', 'url', 'httpUrl', 'description', 'ext', 'focus'=> [ 'top', 'left', 'zoom', 'default', 'str', ] ]; You can always provide your own sub-query, so the defaults will not be used: $page->pageQueryArry([ 'images' => [ 'filename', 'description' ], ]); Overriding default queries: You can also override the defaults, for example $modules->get('PageQueryBoss')->defaults['queries']['Pageimages'] = [ 'basename', 'url', 'description', ]; Index of nested elements The index for nested elements can be adjusted. This is also done with defaults. There are 3 possibilities: Nested by name (default) Nested by ID Nested by numerical index Named index (default): This is the default setting. If you have a field that contains sub-items, the name will be the key in the results: // example $pagesByName = [ 'page-1-name' => [ 'title' => "Page one title", 'name' => 'page-1-name', ], 'page-2-name' => [ 'title' => "Page two title", 'name' => 'page-2-name', ] ] ID based index: If an object is listed in $defaults['index-id'] the id will be the key in the results. Currently, no items are listed as defaults for id-based index: // Set pages to get ID based index: $modules->get('PageQueryBoss')->defaults['index-id']['Page']; // Example return array: $pagesById = [ 123 => [ 'title' => "Page one title", 'name' => 123, ], 124 => [ 'title' => "Page two title", 'name' => 124, ] ] Number based index By default, a couple of fields are transformed automatically to contain numbered indexes: // objects or template names that should use numerical indexes for children instead of names $defaults['index-n'] => [ 'Pageimage', 'Pagefile', 'RepeaterMatrixPage', ]; // example $images = [ 0 => [ 'filename' => "image1.jpg", ], 1 => [ 'filename' => "image2.jpg", ] ] Tipp: When you remove the key 'Pageimage' from $defaults['index-n'], the index will again be name-based. Help-fill closures & tipps: These are few helpfill closure functions you might want to use or could help as a starting point for your own (let me know if you have your own): Get an overview of languages: $query = ['languages' => function($page){ $ar = []; $l=0; foreach (wire('languages') as $language) { // build the json url with segment 1 $ar[$l]['url']= $page->localHttpUrl($language).wire('input')->urlSegment1; $ar[$l]['name'] = $language->name == 'default' ? 'en' : $language->name; $ar[$l]['title'] = $language->getLanguageValue($language, 'title'); $ar[$l]['active'] = $language->id == wire('user')->language->id; $l++; } return $ar; }]; Get county info from ContinentsAndCountries Module Using the [ContinentsAndCountries Module](https://modules.processwire.com/modules/continents-and-countries/) you can extract iso code and names for countries: $query = ['country' => function($page){ $c = wire('modules')->get('ContinentsAndCountries')->findBy('countries', array('name', 'iso', 'code'),['code' =>$page->country]); return count($c) ? (array) $c[count($c)-1] : null; }]; Custom strings from a RepeaterTable for interface Using a RepeaterMatrix you can create template string for your frontend. This is usefull for buttons, labels etc. The following code uses a repeater with the name `strings` has a `key` and a `body` field, the returned array contains the `key` field as, you guess, keys and the `body` field as values: // build custom translations $query = ['strings' => function($page){ return array_column($page->get('strings')->each(['key', 'body']), 'body', 'key'); }]; Multilanguage with default language fallback Using the following setup you can handle multilanguage and return your default language if the requested language does not exist. The url is composed like so: `page/path/{language}/{content-type}` for example: `api/icf/zurich/conference/2019/de/json` // get contenttype and language (or default language if not exists) $lang = wire('languages')->get($input->urlSegment1); if(!$lang instanceof Nullpage){ $user->language = $lang; } else { $lang = $user->language; } // contenttype segment 2 or 1 if language not present $contenttype = $input->urlSegment2 ? $input->urlSegment2 : $input->urlSegment1; if ($contenttype === 'json') { header('Content-type: application/json'); echo $page->pageQueryJson($query); exit(); } Debug The module respects wire('config')->debug. It integrates with TracyDebug. You can override it like so: // turns on debug output no mather what: $modules->get('PageQueryBoss')->debug = true; Todos Make defaults configurable via Backend. How could that be done in style with the default queries? Module in alpha Stage: Subject to change This module is in alpha stage … Query behaviour (especially selecting child-templates, renaming, naming etc) could change
- 24 replies
-
- 29
-
Hi, I'm really struggling with this as it's something not in my wheelhouse. I'm creating a blog style page (a grid of cards) which has attributes. I have a snip of javascript which grabs values from checkboxes which are put into a value like the below: ?content=static_video&channel=facebook-ads_instagram-ads document.querySelector("form").onsubmit=ev=>{ ev.preventDefault(); let o={}; ev.target.querySelectorAll("[name]:checked").forEach(el=>{ (o[el.name]=o[el.name]||[]).push(el.value)}) console.log(location.pathname+"?"+ Object.entries(o).map(([v,f])=> v+"="+f.join("_")).join("&") ); document.location.href = location.pathname+"?"+ Object.entries(o).map(([v,f])=> v+"="+f.join("_")).join("&"); } As I'm currently refeshing the page on button click with those values the end result includes the location but can easily remove this. I then use this value in "input->get" to get the values which I then append to a find() rule. See code below: $selector = "template='adbank_pages',sort=published,include=all,status!=hidden"; // Get the channel and content inputs $channel = $input->get->channel; $content = $input->get->content; if($channel){ // Grab the channel string, explode into an array for checkbox checking and then replace _ with | to create or rules in the selector. $chanArray = explode("_", $channel); $chan = $channel = str_replace('_', '|', $channel); $selector = $selector .= ",ab_channels=$chan"; } if($content){ // Grab the content string, explode into an array for checkbox checking and then replace _ with | to create or rules in the selector. $contArray = explode("_", $content); $cont = $content = str_replace('_', '|', $content); $selector = $selector .= ",ab_content=$cont"; } if($input->get){ // If a valid input result $all = $pages->find($selector); } }else{ // If no input show them all $all = $page->children("template='adbank_pages',sort=-published,include=all,status!=hidden"); } $items = $all->find("limit=12"); // Limit the output and use pagination As mentioned above I currently refresh the page to adjust the $selector filter within the $all with a fallback $all if there are no results. I know I need to use AJAX to filter the content without refresh but I am really struggling with the set up. I have read multiple posts including the original by Ryan but still confused. If anyone can direct/help on this it would be appreciated. Thank you
- 4 replies
-
- ajax
- javascript
-
(and 1 more)
Tagged with:
-
Hello, since hours i am struggeling to get an ajax call to an page field working. i think im doing something fundamentally wrong. The Idea is to load some html markup for larger screen sizes. If i put a .php file with the markup outside the 'site' folder it works fine with a basic XMLHttpRequest. But if i want to have the markup stored in a textfield on my 'settings page' within the template folder i have no success. I tried to follow some tips from this thread as well: my settings.php looks like this: <?php if($config->ajax) { $json = array( 'id' => $page->id, 'title' => $page->title, 'markup' => $page->markup ); echo json_encode($json); return; } and my inline javascript like this ( wrapped in enquire.js): <script type="text/javascript"> enquire.register('screen and (min-width: 700px)', { match: function() { var xhr = new XMLHttpRequest(); xhr.onload = function(){ if(xhr.status === 200){ data = JSON.parse(xhr.responseText); document.getElementById('hero').innerHTML = data.markup; } } xhr.open('GET', 'settings.php', true); xhr.send(null); }, unmatch: function() { } }); </script> <section id="hero"> </section> Like this, i am just getting a 404 , and if i try with a path i get a 403 forbidden. Im entirely confused, maybe someone can help. Thanks a lot.
-
Hi ? Anyone else having this problem? Requirements: - Repeater (matrix & normal) with mutlilanguage fields (text, textarea…) - Backend language set to something other than default (ie. German) Reproduce: - Add a new repeater Item (ajax, I found no way to possible to disable it with matrix) (Notice how the default language tab is active instead of the backend language…) - Write something into the (default language) field - Try to save, if field is required, this will not work. If not required, then when reloading, the content will be inside the backend language field, instead of the default language field who was (presumably) active Analysis: When loading a new repeater element with ajax, the default langue tab is active, but the backend language inputfield is visible (with no visual indication). When writing into the field, it will populate the backend language. When manually clicking on the default language tab (which is already active), the field will switch to the actual default language field (which is [now] empty) (that can now be populated…) Also Notice, the labels of the elements to be added are in default language as well instead of the translated label (images instead of Bilder)… ProcessWire 3.0.148, Profields 0.0.5… Is it my system configuration, or does anyone else have the same issue? This is a screen recording of the problem: Issue: https://github.com/processwire/processwire-issues/issues/1179 Screen Recording 2020-02-25 at 14.18.31.mov
-
Hi there, I'm trying to get to work some AJAX call with vanilla Javascript, not jQuery. Anything seems to work so far, but the !$config->ajax seems to be ignored. To find out whats the problem by comparing both, jquery and plain javascipt, i built this template. commenting out //loadJquery(''); or loadVanilla(''); switches the two variants. (empty url variable means that the same pages will be loaded.) The problem: the pure Javascript function ("loadVanilla") is loading the full page content into the dc-container, which is wrong. The jQuery function ("loadJquery") only loads the part outside of the if(!$config->ajax): - which is as it should be. So - any help with this, what am i doing wrong? Thanks a lot - Matze <?php namespace ProcessWire; if(!$config->ajax): ?> (some static content)<br> <a id="loadlink" href="#">load</a><br> <?php endif; // end if not ajax ?> <span id="dc-container">(dynamic content)</span> <?php if(!$config->ajax): ?> <script src="http://code.jquery.com/jquery-3.3.1.min.js"></script> <script> var loadlink = document.getElementById('loadlink'); loadlink.addEventListener('click', function(event) { //loadJquery(''); loadVanilla(''); event.preventDefault() }); function loadVanilla(url) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("dc-container").innerHTML = 'loaded: ' + this.responseText + (' (by vanilla javascript)'); } }; xhttp.open("POST", "", true); xhttp.send(); } function loadJquery(url){ // Load content $.ajax({ type: "POST", url: url, data: { ajax: true }, success: function(data,status){ pageData = data; } }).done(function(){ // when finished and successful document.getElementById("dc-container").innerHTML = 'loaded: ' + pageData + ' (by jquery ajax)'; }); } </script> <?php endif; // end if not ajax ?>
- 10 replies
-
- javascript
- jquery
-
(and 1 more)
Tagged with:
-
Hello there, I am building my website, which has a dozen projects with 10 images each. Basically, I need a filtering system but built in the most efficient and user-friendly way. You can see below that the images flow sideways so being hidden, JS lazy loading was a good tool, but I just wanted to try AJAX. Is it fit for this purpose or it's more for dynamic content?
-
Hello everyone, I always wanted to try out an ajax autocomplete search function, but never knew where to start. Of course there is the Ajax Page Search module by soma, but it seems that it was build around the basic site profile. In my case I wanted something more custom and I discovered in this thread the jQuery Plugin Typeahead by RunningCoder, which seemed to be nice. After many hours figuring out, how to combine this Plugin with ProcessWire, I finally got it implemented and want to share my solution with anyone, who also struggles with this topic. 1. Set-Up Typeahead Download the Typeahead-Plugin from the website (I prefer via Bower) and include the following scripts and stylesheets in your templates: <html> <head> ... <!-- Optional CSS --> <link rel="stylesheet" href="/vendor/jquery-typeahead/dist/jquery.typeahead.min.css"> <!-- Required JavaScript --> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script src="/vendor/jquery-typeahead/dist/jquery.typeahead.min.js"></script> ... </head> As next step we need the JSON data. 2. Install Pages to JSON To get the necessary data of all pages as JSON, I use the module Pages to JSON, which provides an easy way to output pages as JSON objects. Of course you can achieve this without this module, but I am not very experienced with JSON, so this module was really helpful. After you downloaded and installed the module, you can configure in the module settings page, which fields you want to output. You can select between own and system fields. For my purpose I selected only title and url to be outputted. 3. Output JSON Now, that we have the module configured, we have to output our search suggestions as JSON. I did it in my template file search.php like this: <?php namespace ProcessWire; // Check if ajax request if($config->ajax) { $results = $pages->find("has_parent!=2"); // Find all published pages and save as $results header("Content-type: application/json"); // Set header to JSON echo $results->toJSON(); // Output the results as JSON via the toJSON function } else { // Your own front-end template } To sum up, we search the pages we want as search suggestions and save them in a variable. Then we output them with the toJSON-Function by the Pages to JSON-Module. All of this happens in a Ajax-Request, that is the reason why we check first, if the page is called via an Ajax request. 4. Insert Form We can now embed the HTML form anywhere you want. Either in an header-include or a specific template. Also you can use your own classes, for this example I used the Typeahead-demo-mark-up and extended it a little. <form id="searchform" method="get" action="<?= $pages->get("template=search")->url ?>"> <div class="typeahead__container"> <div class="typeahead__field"> <span class="typeahead__query"> <input id="q" name="q" type="search" placeholder="Search" autocomplete="off"> </span> <span class="typeahead__button"> <button type="submit"> <span class="typeahead__search-icon"></span> </button> </span> </div> </div> </form> The action-attribute in the form-tag is the url of your search-site. This attribute is of course necessary to know where the form redirects you and where the JSON data is located. 5. Initialize Typeahead As last step we have to initialize the Typeahead-plugin jQuery like this: $(document).ready(function() { var actionURL = $('#searchform').attr('action'); // Save form action url in variable $.typeahead({ input: '#q', hint: true, display: ["title"], // Search objects by the title-key source: { url: actionURL // Ajax request to get JSON from the action url }, callback: { // Redirect to url after clicking or pressing enter onClickAfter: function (node, a, item, event) { window.location.href = item.url; // Set window location to site url } } }); }); We save the action url of the form in a variable, then we initialize Typeahead by selecting the input-field inside the form. As the source we can pass the action url and I included the callback, to link the search results with the site urls. Now you should have a nice ajax autocomplete search form, which of course you can further style and configure. I hope I didn't forget anything, but if so, please let me know. Regards, Andreas
- 7 replies
-
- 16
-
- typeahead
- autocomplete
-
(and 2 more)
Tagged with:
-
I have been messing around with creating pages from ajax requests, and it has gone swimmingly thus far. However, I am really struggling with creating a page and saving an image via ajax. The form: <form action="./" role="form" method="post" enctype="multipart/form-data"> <div> <input type="text" id="preview" name="preview" placeholder="Image Title"> </div> <div> <input type="file" id="preview-name" name="preview-name"> </div> <div> <select id="select-tags" name="select-tags"> <?php $tags = $pages->find("template=tag"); ?> <option value="">Select Your Tags</option> <?php foreach ($tags as $tag) : ?> <option value="<?= $tag->name; ?>"><?= $tag->name; ?></option> <?php endforeach; ?> </select> </div> <div> <button type="button" id="submit-preview" name="submit" class="">Upload Images</button> </div> </form> The ajax in my home template: $('#submit-preview').click(function(e) { e.preventDefault(); title = $("#preview").val(); image = $("input[name=preview-name]"); console.log(title); console.log(image); data = { title: title, image: image //not sure if this is actually needed }; $.ajax({ type: 'POST', data: data, url: '/development/upload-preview/', success: function(data) { console.log("Woo"); }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); } }); }); And finally in my ajax template: $imagePath = $config->paths->assets . "files/pdfs/"; //was from an older iteration $title = $sanitizer->text($_POST['title']); $image = $sanitizer->text($_POST['image']); $p = new Page(); $p->template = "preview"; $p->parent = $pages->get("/previews/"); $p->name = $title; $p->title = $title; $p->save(); $p->setOutputFormatting(false); $u = new WireUpload('preview_image'); $u->setMaxFiles(1); $u->setOverwrite(false); $u->setDestinationPath($p->preview_image->path()); $u->setValidExtensions(array('jpg', 'jpeg', 'gif', 'png', 'pdf')); foreach($u->execute() as $filename) { $p->preview_image->add($filename); } $p->save(); I can complete the file upload but just using a simple post to the same page and it it works well, but I was really trying to work out the ajax on this so I could utilize some modals for success on creation (and to keep my templates a little cleaner). When I do run the code I have, a new/blank folder is created under assets, and a new page is created with the correct title entered. However, no image is being processed. I do get a 200 status in my console. I have searched google for help, but everything seems to be slightly off from my needs. If anyone could help point me in the right direction I would greatly appreciate it.
-
So I am using ajax to upload an image, but I am getting the error "Method WireUpload:: save does not exist or is not callable". I am not quite sure how to go about fixing this (at the moment). elseif($config->ajax && $input->urlSegment1 == "upload-preview") { $u = $config->paths->assets . "files/pdfs/"; $title = $sanitizer->text($_POST['title']); $p = new Page(); $p->template = "preview"; $p->parent = $pages->get("/previews/"); $p->name = $title; $p->title = $title; $p->save(); $p->setOutputFormatting(false); $u = new WireUpload('preview_image'); $u->setMaxFiles(1); $u->setOverwrite(false); $u->setDestinationPath($p->preview_image->path()); $u->setValidExtensions(array('jpg', 'jpeg', 'gif', 'png', 'pdf')); foreach($u->execute() as $filename) { $p->preview_image->add($filename); } $u->save(); } I compared my code to something I did previously (though previously I just posted to the current template file, not through ajax) which works, but this doesnt seem to be working. I have the _init.php file prepending as well. Does anyone have any ideas of what might be happening?
-
I just wanted to share that I added an AJAX-powered gallery to an artist website that I developed and host: https://jackpinecreations.com/gallery/ There were two things that frustrated me about creating this. Perhaps you can show me a better way. 1. After creating my processing script, which I placed under /templates/scripts/get-items.php, I realized that I would get a 403, due to ProcessWire's routing and security. This forced me to have to create a template and page for this little script. This was frustrating simply because it seemed unnecessarily confusing. But worse, see #2. 2. I usually use config.php to prepend and append each of my templates with a head.inc and foot.inc, which keeps my templates easy to use and I don't have to go and use the GUI to do so on each template separately. However, since I realized I needed to create a new template and page so as to access it, whenever I sent POST params to it, I would get the header and footer along with it!!! I could find no workarounds and had to remove the pre/append calls in config.php and use the GUI on each template individually. Code Below if you're interested: HTML and JavaScript (forgive my sad JavaScript skills, I know this can be tightened up) <!-- Begin Grid --> <div class="container mt-4"> <div id="gallery" class="row"> <?php foreach ($page->children("limit=9") as $child): ?> <div class="col-6 col-md-4 gallery-item"> <a href="<?= $child->url ?>" title="View <?= $child->title ?>"> <img class="gallery-item" src="<?= $child->item_featured_image->size(640, 640)->url ?>" alt="<?= $child->title ?> Image"> </a> </div> <?php endforeach; ?> </div> </div> <!-- End Grid --> <div class="center-block text-center"> <button id="get-more-items" type="button" name="get-more-items" class="btn-vintage">Load More</button> </div> <script type="text/javascript"> var buttonGetItems = document.getElementById("get-more-items"); var indexStart = 0; buttonGetItems.addEventListener("click", function() { indexStart += 9; $.ajax({ url: '<?= $pages->get(1186)->url ?>', type: "POST", dataType:'json', // add json datatype to get json data: ({page_id: <?= $page->id ?>, index_start: indexStart}), success: function(data){ console.log(data); if (data[1]) { //for each element, append it. $.each(data, function(key, value) { $("#gallery").append(value); }); } else { $("#get-more-items").after('<p class="center-block text-center">There are no more items to load.</p>'); $("#get-more-items").remove(); } } }); }); </script> Processing Script <?php $items_array = []; $i = 0; foreach ($pages->get($input->post->page_id)->children->slice($input->post->index_start, 9) as $child) { $i++; $items_array[$i] = "<div class='col-6 col-md-4 gallery-item'> <a href='$child->url' title='View $child->title'> <img src='{$child->item_featured_image->size(640,640)->url}' alt='$child->title Image'> </a> </div>"; } echo json_encode($items_array); I love ProcessWire for hundreds of reasons, but I've been using AJAX more and more, and I'm not liking having to create templates to access scripts. Any advice?
-
Hello, I'm facing a weird issue here. I have a page loaded with this code inside (my comments in line ends) : if ($session->allPlayers) { // Set in a head.inc file. I have also a $session->set('allTeams', $allTeams); in my head.inc $allPlayers = $session->allPlayers; } else { $allPlayers = getAllPlayers($user, false); $session->set('allPlayers', $allPlayers); } bd($session->getAll()); // HERE, I get a number of 11 variables which is what I expect In the same page, I have a link pointing to ajaxContent.php that loads stuff via Ajax. I just write this in my ajaxContent.php to test : bd($session->getAll()); // HERE, I get only 9 variables. All my newly set $session variables ($allTeams and $allPlayers) are not conveyed to ajaxContent.php ??? Would you have any idea why is that ??? Another thing : I have a $session->headMenu set in my head.inc, and this one works fine. I can retrieve it in my ajaxContent.php page. I've tried cleaning all caches but it doesn't change anything ? At first, I expected it to be a 15-minute update to my site... It turns out to be a 2-hour issue and I'm still stuck. Thanks for your ideas !
-
So I have a template called "development" where I am testing out a few ideas etc set up on a local mamp server. I also have a page called "ajax" using a template called ajax. From my development template, I am posting a form using ajax and all is working quite well: $('.test').click(function(event) { event.preventDefault(); redirectUrl = $(this).data('redirect'); var data = { firstName: $("#firstname").val(), lastName: $("#lastname").val(), email: $("#email").val(), phone: $("#phone").val(), redirectUrl: redirectUrl }; $.ajax({ type: "POST", url: "localhost:8888/sandbox/ajax/form/", data: data, success: function() { console.log(this.data); top.window.location = redirectUrl; }, failure: function() { console.log(this.data); } }); And in my ajax template: if($input->urlSegment == 'form'){ if ($_POST) { //handle the post } } The redirectUrl is a data attribute I added in to the button (that launches the form in a modal) that pulls in from a field in processwire. Everything works just fine locally, but when I export everything to a live site it fails. It will work 1 time and redirect, but if you go back to resubmit, it submits the data but won't redirect. Can anyone see any glaring issue here, or have a better way around this? ------------------------------ So, it turns out the request to /ajax/form/ was being canceled. It still handled the POST request, but never sent back a 200 to show "success". Adding in return false; at the end of my .onclick solved the issue. It is strange though as I have never had this issue before.
-
I have a PW site where I had been successfully uploading png and jpeg files. Recently the file and image file fields don't save. The upload status bar completes (100%) without error but when the page with the file field is saved the uploaded file name is missing from the refreshed page. This must be due to a site hosting change but I need more specific info like error details before I raise it with them. The php v5.4 config has file uploads enabled and safe mode is off. I have tried the following to fix this without success: I have read and tried the fixes to the similar posting from Soma: can't upload image/files problem Upgraded the PW site from 2.3 to 2.5.3. (no change) Turned on debug in config.php with no obvious error messages showing. Debugged core\WireUpload.php where I found that the recommended fixes from 1. wouldn't work because the file field is not using Ajax. Have you got any other suggestions?
- 43 replies
-
- 1
-
- ajax
- sys_get_temp_dir
- (and 4 more)
-
Hello. I have recently adopted PW markup regions and really like this way of working. However, I am also trying to learn how to use Ajax and I am not sure of a good way to use the two together. Has anyone got any experience, tips or hints on using them together? For ajax - I've used a simple scheme where I have a "webservice" template and page that handles Ajax requests and returns the appropriate content wrapped with some markup for the requesting page. I have markup regions enabled and all my pages (bar webservice) include a _main.php which brings in the headers, a default body and the footer. My javascript intercepts the page links and does my ajax call to webservice and that sends back the appropriate markup which is then placed by in the div #body defined in _main.php. Does this seem a reasonable way to work? I guess I am looking for some advice before I invest too much time going the wrong way! Any guidance, remarks, comments, or a nudge in the right direction greatly appreciated. Paul
-
In my frontend I would like to implement a small AJAX-solution, but it does´nt work. For example: template/js/ajax.js: contains jquery-ajax-snippet with click-function like this: $.post('ajax.inc', function(e) {}); template/ajax.inc: contains db-query with HTML-output template/home.php: contains div-element for the ajax-response, e.g. <div id='result'>...ajax-response...</div> It seems, PW does´nt allow database-requests via AJAX (jquery). I know the post from Ryan "How to work with AJAX driven content in ProcessWire". But this solution requires a completely new template-concept. I only need a simple solution for a small ajax-db-request. Thanks to all
-
So I was going to build a todo tracking app for myself to test/broaden my knowledge of processwire, and so far it has been taxing ?. My Site structure is: - Project One - Phase One - Task - Task - Task - Phase Two - Task - Task - Task So far it was pretty easy, I can easily foreach through the Project and get the phases with their tasks. However, it gets a bit muddled when I have more than one project as I was trying to have a dashboard where the content switches out to the selected project as opposed to accessing each project via their own url. How would yall handle this? My next hurdle is each task has a select field (for project status) that I want to update via ajax (for the smooth transitioning). Scenario: You finish a task, change the option from "new" to "completed", and an onclick changes the status drop down background to green (which I have working), but then posts/saves a field on the backend to the new option. I have a page called "Actions" set up with url segments using if ($config->ajax && $input->urlSegment1 == 'change-status') { //save update field on admin } However, I am a little fuzzy on how to actually pass the current page along with the new selected status to actually update the page (task). I guess I am not very far into my endeavor. Any help would be greatly appreciated.
-
Hi there, I ran into a problem posting form data via AJAX. Of course I did some research on the topic via Google, this forum and looking into ProcessWire's core code and found the following steps... Setting headers to 'X-Requested-With', 'XMLHttpRequest' Using a trailing slash ...but to no avail. As you can see in the following code I log the response, in this case just a var_dump() of wire("input")->post, but i just get response: object(ProcessWire\WireInputData)#240 (0) { } Here's my code in total. It's simplified, but should work, but for some reason does not. Could any of you point me towards the solution/my fallcy? Thanks in advance! <?php if (wire("config")->ajax) { if (wire("input")->post) { var_dump(wire("input")->post); } } else { ?> <div id="app"> <form action="./" method="post" v-on:submit.prevent="getFormValues"> <label><input type="radio" name="yes_no" id="yes" <?= ($page->yes_no == "1") ? "checked" : "" ?> value="1"/>Ja</label> <label><input type="radio" name="yes_no" id="no" <?= ($page->yes_no == "2") ? "checked" : "" ?> value="2"/>Nein</label> <button type="submit">Go</button> <p>{{ yes_no }}</p> </form> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script> new Vue({ el: '#app', data: { yes_no: '(unbeantwortet)' }, methods: { getFormValues: function (e) { this.yes_no = e.target.elements.yes_no.value; axios.post('./', { yes_no: this.yes_no }, { headers: { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/json' } }) .then(function (response) { console.log("response:", response.data); }) .catch(function (error) { console.log("error:", error); }); } } }); </script> <?php } ?> // edit: I forgot to mention that the POST request is sent (I can track it in developer tools) and it includes the data I'm intending to send. So I really assume it is a reception problem.
-
Output pure JSON for ajax calls in process module
gebeer posted a topic in Module/Plugin Development
Hello all, I'm pretty new to Process module development and couldn't find much related to my scenario. In my custom process module I have an execute function that returns data for AJAX requests. I would like to output pure JSON. Thus I need to alter the header to be 'Content-Type: application/json' and also not render all the admin theme output. How would I achieve that from within a process module? Or do I need to take care of that on the admin theme level? I have a custom admin theme running. Thank you. -
Sending ajax data from multiple page to one template
louisstephens posted a topic in API & Templates
So I have a project where multiple pages are sending POST data to 1 single template page. All was working well (well, at least with one ajax post), but now I have hit a stumbling block. I figured the "best" way to handle the request were to use url segments and then use the following in the status page: if ($config->ajax && $input->urlSegment1 == 'add-bookmark') { // some code here } However, this doesnt seem to really work (as I assume the the request isnt being posted to /status/ but rather to /status/add-bookmark/). What is the best way to actually handle this?- 2 replies
-
- ajax
- url segment
-
(and 2 more)
Tagged with:
-
Currently, I have a page set up listing all child pages using a foreach loop and outputting some information (thus far, it is all gravy). However, I ran into a slight problem. I have a "button" on each item being rendered that when clicked needs to send the page id to another page for processing via ajax. I thought I could just save the item id like : <?php $itemId = $item->id; ?> And then encoding it below in my javascript: var itemId = <?php echo json_encode($itemId); ?>; var data = { itemId: itemId, }; $.ajax({ type: "POST", url: "/intra/status/", data: data, success: function(){ console.log(itemId); } }); However, it is only posting the last page's id rendered by the foreach. Have I just overlooked something simple on this?
-
I just relaunched my portfolio website. It's my first ajax driven website using ProcessWire as a CMS. Its a showcase of some of my work as well as a digital playground to improve my coding skills. If you encounter any bugs or have feedback, feel free to share janploch.de
-
I'm trying to make an AJAX call from within a template to a php script within my templates folder, but I'm getting a 404 from all URLs. Is there a proper way to directly address scripts within PW templates? I've read it will work in the site root, but I'd rather keep all the code together if possible.