Jump to content

Search the Community

Showing results for tags 'ajax'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to ProcessWire
    • News & Announcements
    • Showcase
    • Wishlist & Roadmap
  • Community Support
    • Getting Started
    • Tutorials
    • FAQs
    • General Support
    • API & Templates
    • Modules/Plugins
    • Themes and Profiles
    • Multi-Language Support
    • Security
    • Jobs
  • Off Topic
    • Pub
    • Dev Talk

Product Groups

  • Form Builder
  • ProFields
  • ProCache
  • ProMailer
  • Login Register Pro
  • ProDrafts
  • ListerPro
  • ProDevTools
  • Likes
  • Custom Development

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests

  1. 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
  2. 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
  3. 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
  4. 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?
  5. 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.
  6. 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?
  7. 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?
  8. 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 !
  9. 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.
  10. 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
  11. 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
  12. 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.
  13. 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?
  14. 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?
  15. 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
  16. 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
  17. 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.
  18. Hello, After doing a deep dive into Processwire over the weekend (better late than never), I'm starting to layout an app to receive a migration of an existing app. I'm sure I'll have several questions, but here's my first: Question: I'm using the _main.php/regions template approach. However, I need to do some ajax calls for some html. How would I tell a page just to include only the needed template/fields? I can probably figure this out, but in the interest of time...Thanks!
  19. 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.
  20. 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 ?>
  21. Hi folks! For a website Iam working on I need to (pre)load a huge amount of images (100-500) from a folder in assets (wich I upload via FTP). To preload them I want to add them to the DOM inside a container, that I hide with css. This images will be use for a frame by frame animation (that animates with scrolling) so they should be loaded parallel and if the user clicks a cancel button, the loading should be canceled. (My website is using ajax to load pages with different animations, and the loading of the second animation waits till the loading of the first animation is loaded completly, wich I want to prevent). I want to use ajax to do this, so I can cancel the loading with xhr.abort(); Here is my code: var folder = '{$config->urls->assets}sequenzen/test/'; xhr = $.ajax({ url : folder, success: function (data) { $(data).find("a").attr("href", function (i, val) { if( val.match(/\.(jpe?g|png|gif)$/) ) { $(".preloader").append( "<img src='"+ folder + val +"'>" ); } }); } }); this will give me a 403 forbidden error. After some research I found out that I have to put a .htaccess in my assets folder. I also tried putting it in the sub folder "test", where the files are, but Iam still getting the error. Is there anything else Iam missing? Is there a configuration in PW i have to change to do that?
  22. Has anyone used pagination with ajax driven content? I'm using the MarkupPagerNav module to give me pagination, but my content is updated by an ajax post to refresh the body content of a table. The pagination links show a myproject/http404/?page=n for each link generated so they give a 404 page not found. I believe this is because the file containing my ajax code resides in the root of my project as a "web service" and does not have the access it needs, but I'm unsure really. If anyone can throw any light on this I would be very grateful. I include the code with my ajax below. <?php namespace ProcessWire; require_once ('./index.php'); // bootstrap ProcessWire if($config->ajax) { $pg = $pages->get("/single-use-carrier-bags/"); $selector = wire('input')->post('selector'); $mytableContent = ''; // hold the table markup // $retailer = $pg->children($selector); // for info. only $selector looks like this -> $retailer = $pg->children("sort=title, include=all, limit=10"); $pageinate = $retailer->renderPager(); echo $pageinate; foreach ($retailer as $r) { $mytableContent .= "<tr> <td><a href= '$r->url' target='_blank'>$r->title</a></td> <td>$r->category</td> <td>".numFormat($r->no_bags_issued)."</td> <td>".numFormat($r->gross_proceeds)."</td> <td>".numFormat($r->net_proceeds)."</td> <td>$r->other_use_net_proceeds</td> <td>".numFormat($r->amount_donated)."</td> <td>$r->good_causes_in_receipt</td> <td>".numFormat($r->no_paper_bags_issued)."</td> <td>".numFormat($r->no_bags_for_life)."</td> </tr>"; } echo $mytableContent; } ?>
  23. I have a table in my template that I would like to update using Ajax when a button is pressed. I am not sure how to go about this and hope somebody here could point me in the right direction. Here is my code for the table output. You can see I loop through the fields to output using a hard wired selector to list the retailer type. I have a button for Supermarkets that fires a js handler myFunc and I need to put the ajax there to call this page again with a param so I can then form the selector for supermarkets and update the table. When I get this working and understand how to do it in ajax I will code up a selector that is formed dependant on a bank of buttons and the table will update without the rest of the page - like magic! That's what ajax is for right?! Thanks for any help - Paul <button type="button" onclick="myFunc()" value="1" class="btn btn-primary">Supermarkets</button> <div class= "table-responsive"> <table class="table table-hover table-striped"> <thead> <tr> <th>Retailer</th> <th>No. bags issued</th> <th>Gross proceeds £</th> <th>Net proceeds £</th> <th>Other use of net proceeds</th> <th>Amount donated £</th> <th>Good causes in receipt of proceed</th> <th>No. of paper bags issued</th> <th>No. of bags for life</th> </tr> </thead> <tbody> <?php $pg = $pages->get("/single-use-carrier-bags/"); $retailer = $pg->find("category=DIY, sort=title, include=all"); foreach ($retailer as $r) { echo "<tr> <td><a href= '$r->url'>$r->title</a></td> <td>".numFormat($r->no_bags_issued)."</td> <td>".numFormat($r->gross_proceeds)."</td> <td>".numFormat($r->net_proceeds)."</td> <td>$r->other_use_net_proceeds</td> <td>".numFormat($r->amount_donated)."</td> <td>$r->good_causes_in_receipt</td> <td>".numFormat($r->no_paper_bags_issued)."</td> <td>".numFormat($r->no_bags_for_life)."</td> </tr>"; } ?> </tbody> </table> </div> </div> </div> <script type="text/javascript"> function myFunc() { } </script>
  24. hello, i have a _func.php file with this function. in the documentation i read that some api variables in functions are not available, so i use wire('pages'). function doSomething($u, $p) { $p = wire('pages')->get("id=$p"); $u = wire('pages')->get("id=$u"); $p->of(false); { ... populate repeater field stuff } $p->save(); } if i call this function in my home.php like doSomething(41,1093) (only for testing!) everything is fine, the function works, it add items to a repeater field. the german says "Wenn es dem Esel zu wohl ist, geht er aufs Eis", so i play around with ajax to fire up this function. $(document).ready(function() { $("#hit").click(function(){ $.ajax({ url: '<?= $config->urls->templates?>includes/_func.php/', type: 'post', data: {userID: "<?= $user->id ?>", pageID: "<?= $page->id ?>"}, success: function(output){ console.log(output); } }) }) }) i read something about variable scopes and i think i understand it a little bit. but i don't understand why doSomething(41,1093) works in home.php the ajax call runs into a Call to undefined function wire() ? also i tried if ($config->ajax) but no luck ... that's the relevant party of _func.php. function doSomething($u, $p) { $p = wire('pages')->get("id=$p"); $u = wire('pages')->get("id=$u"); $p->of(false); { ... populate repeater field stuff } $p->save(); } if(isset($_POST['userID']) && !empty($_POST['userID']) && isset($_POST['pageID']) && !empty($_POST['pageID'])) { $u = $_POST['userID']; $p = $_POST['pageID']; { ... } echo sendLike($u, $p); } where is my mistake? any ideas? thx
  25. Hello, I'm desperately trying to update my website to PW 3.0.62 and I'm facing issues to to module compatibility. I was stuck with Pages2Pdf which I managed to solve bu updating the module from Github, but now it's the Pages Web Service module... and this time, I don't know wht to do The Module is found there. But it is quite old and I can't find it in the modules catalogue... and my site is making quite a use of it (I can't think of a way to do otherwise, sorry...) After adding the FileCompiler=0 to the module pages, the error I'm stuck with is : Fatal error: Class 'WireData' not found in /home/celfred/PlanetAlert/site/modules/ServicePages/ServicePages.module on line 22 and I have no idea on what to do... I must admit I'm not a programmer but a middle-school teacher... (for your information, here's the site I'm talking about : http://planetalert.tuxfamily.org ) but I'm struggling hard to solve the different issues I have to face and I'm wlling to understand things. I have just spent many hours trying to make 2.8 work on my localhost (and it seems ok ) but I'd like to switch to 3.x to prepare the future If anyone had the will to spend a few minutes to try and help me, I would greatly appreciate. Thanks in advance ! If you need more information to understand my problem, feel free to ask.
×
×
  • Create New...