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 there, I have a globally declared variable where I want to store a mapping table. var _Pagelist=new Map(); The following Ajax call doesn't seem to set _Pagelist above. I think I have set the context parameter correctly to 'this'. I've scoured through Stackoverflow and JQuery documentation but I can't figure out what is wrong. Any pointers would be much appreciated. Thanks if (!pagelist){ SearchWaitDisplay(true); $.ajax({ url: '/site/pagelist.php', context : this , success: function(result) { //here this._Pagelist is null, can't refer to This._Pagelist for (var x=0;x<result.length;x++) { this._Pagelist.set(result[x].id, result[x].url); //This will throw an error as _Pagelist is NULL. }; window.localStorage.setItem('pagelist', JSON.stringify(_Pagelist)); //The following will not update _Pagelist. Next 2 lines are just test code. this._Pagelist = result; window._Pagelist = result; SearchWaitDisplay(false); }, error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status + ' ' + thrownError); } }); } else { //InitialiseSearchField(autocompletelist); }
  2. Module: http://modules.processwire.com/modules/ajax-intercooler-js/ Repo: https://bitbucket.org/pwFoo/ajaxintercoolerjs AjaxIntercoolerJS module features integrates IntercoolerJS async CCS ("loadCSS") and JavaScript load / update optional disable async css / js handling for blocks, sidebar, ... Intercooler X-IC response header support support / hook $session->redirect multiple X-IC-Trigger handling multiple X-IC-Script handling Usage Basics It's a autoload module, but you need to enable it inside of your templates, because scripts and dependencies ("JqueryCore") have to be loaded too. You can enable / load it global inside of the TemplateFileHelper controller "_layout.php" $ic->enable(); Some changes are needed to your main template "_layout.tpl". <!-- IntercoolerJS needs a target with ID "pageContent" for (async) page content --> <div id="pageContent"><?=$pageContent?></div> And your navigation links need some IntercoolerJS attributes like that. <a href="..." ic-get-from='/url-to-load' ic-target='#sidebar'>...</a> Your just use and hook MarkupSimpleNavigation. $nav = $modules->get('MarkupSimpleNavigation'); $opts = array( 'show_root' => true, 'item_tpl' => "<a href='{url}' ic-get-from='{url}' ic-target='#pageContent' ic-push-url=true>{title}</a>", 'item_current_tpl' => "<a href='{url}' ic-get-from='{url}' ic-target='#pageContent' ic-push-url=true>{title}</a>", ); // optional modify a specific link to use another target. For example "#sidebar" $nav->addHookAfter('getTagsString', null, function($event) { $link = $event->arguments[1]; if ($link->title == 'sidebar') { $event->return = "<a href='{$link->url}' ic-get-from='{$link->url}' ic-target='#sidebar'>{$link->title} (sidebar)</a>"; } }); // render and set as _layout.tpl template var $layout->set('navigation', $nav->render($opts)); Disable CSS refresh (remove "current" styles and load the new one) The current loaded page css shouldn't removed if the sidebar is updated. So it's possible to disable the asyncHandler inside of the "sidebar" template. $ic->asyncHandler(false); Quick and dirty FrontendUser integration You just need a PW template file like that. $fu = $modules->get('FrontendUser'); $fu->login(); $button = $fu->form->fhSubmitBtn; $button->attr('ic-post-to', $page->url); $button->attr('ic-target', '#pageContent'); if (!empty($_GET['logout'])) { $fu->logout($page->url); } // Workaround until IntercoolerJS 1.0.1 release if ($input->post['ic-trigger-name']) { $input->post[$fu->form->fhSubmitBtn->name] = $input->post['ic-trigger-name']; } $processed = $fu->process($page->url); if ($processed && !$user->isGuest()) { // $processed == false if login failed (not submitted / login successful == true) echo "Hello $user->name!"; echo "<a href='$page->url?logout=1'>Logout</a>"; } else { echo $fu->render(); } X-IC Response Headers /** * Set x-ic-trigger response header * @param array $array One or more events with related data arrays */ public function trigger($array) { $json = json_encode($array); header('x-ic-trigger: ' . $json); } /** * Set x-ic-script response header * @param string $js Valid javaScript code */ public function script($js) { header('X-IC-Script: ' . $js); } /** * Stop current / parent element Intercooler polling */ public function cancelPolling() { header ('x-ic-cancelPolling: true'); } /** * Resume current / parent element Intercooler polling */ public function resumePolling() { header ('x-ic-resumePolling: true'); } /** * Set current / parent element Intercooler polling interval * @param string $interval */ public function setPollInterval($interval) { header ('x-ic-setPollInterval: ' . $interval); } /** * Set x-ic-refresh response header * @param string $pathCsv Comma separated paths to refresh. */ public function refresh($pathCsv) { header('x-ic-refresh: ' . $pathCsv); } /** * Set x-ic-open response header * @param string $url New window / tab address */ public function open($url) { header('x-ic-open: ' . $url); } /** * Set x-ic-redirect response header * @param string $url Redirect destination address */ public function redirect($url) { header('x-ic-redirect: ' .$url); } Wrapper for X-IC-Trigger Add a event trigger with event name ($event) and parameters array ($array). "addTrigger()" method is a wrapper for usage with multiple event triggers. Native method for a single execution is method "trigger()" $ic->addTrigger($event, $array); Wrapper for X-IC-Script String of javascript code for client side execution. "addScript()" method is a wrapper for multiple usage of "script()" method. $ic->addScript($javascript); $session->redirect is hooked! The module hooks $session->redirect() method for ajax calls. It's needed to execute redirects by IntercoolerJS X-IC-Redirect for ajax calls. Used for the FrontendUser integration.
  3. I'm new to processwire and i'm looking for a solution to handle post requests with inputfields. At the moment my code looks like this: class InputfieldTest extends Inputfield { ... public function init() { if($this->config->ajax && $this->input->InputfieldTest){ header('Content-Type: application/json'); echo "{'test':'test'}"; exit; } } ... } And then there is a JS file with: var testdata = { InputfieldTest: 'InputfieldTest' }; testdata[$('#testa-tokenname').text()] = $('#testa-tokenvalue').text(); $.ajax({ url: "http://bla.at/processwire/page/edit/?id=1816&InputfieldTest=1", data: testdata, type: 'POST', success: function(json) { alert(json); } }); Everything works fine with a GET request, but with the POST i just get the message {"error":false,"message":"AJAX Page not saved (no changes)"} Any ideas? Or is it all wrong and i should use a different approach?
  4. I pushed an initial (testing) version of TemplateFileHelper to bitbucket. https://bitbucket.org/pwFoo/templatefilehelper/src/ The autoload module extends TemplateFile instances with API vars $layout and $view $layout -> global layout instance of TemplateFile to set layout placeholders ($layout->set(...) or global scripts / styles. $view -> current page instance of TemplateFile to set the current page placeholders and current page scripts / styles. load() method Load a template / view with additional controller (php) file as subTemplate. Returns a TemplateFile object to render / output Each sub-template controller have access to API Vars and $subTemplate (current TemplateFile instance, $subTemplate->set('placeholder', 'My value...')). Load site/templates/chunks/test1.php controller and site/templates/chunks/test1.tpl view: $part = $view->load('chunks/test1'); echo $part->render(); chunks/test1 example <?php // chunks/test1.php - controller $subTemplate->set('var1', "Subtemplate variable output..."); <!-- chunks/test1.tpl - view --> <div><?=$var1?></div> scripts / styles properties FilenameArray like $config->styles | scripts. It should help to organize scripts / styles with ajax in mind (global / current page only). // current page script $view->scripts->add('js-file.js'); // global / layout script $layout->scripts->add('js-file.js'); You have to handle the output yourself by two foreach loops inside your _layout.php / _layout.tpl files (non ajax calls scripts and styles should be in layout head section). foreach ($layout->scripts as $globalScript) { ... } foreach ($view->scripts as $currentPageScript) { ... } IntercoolerJS module will take care about async / ajax handling of (custom page) scripts and styles. hook Page::render hook after page render to load and add the global layout. The current page template (PW template file == controller) just handle the currents page code / view. Global layout / controller / view is moved to separate files (default: _layout.php controller and _layout.tpl view). Just use $layout->set(...) to fill the _layout.tpl placeholder variables inside the _layout.php controller file. configurable module Some settings are available... Global layout (view + controller) file name (default: "_layout") Current page content variable (used inside of the _layout.tpl view to output current page content, default: "currentPageContent") View file extension (default: ".tpl") Controller file extension (default: ".php") It will be a dependency of the planned IntercoolerJS module which adds ajax page calls, async scripts / styles handling (current page scripts and styles...) and need a defined template handling to work...
  5. I have a single-page website with a contact form: <div id="wrap_form"> <form id="inquire" action="" class="uk-form"> <div class="uk-grid uk-grid-collapse"> <input type="text" id="i_name" name="name" class="uk-width" placeholder="Your Name" maxlength="250" required /> <input type="text" id="i_phone" name="phone" class="uk-width" placeholder="###-###-####" pattern="^[2-9]\d{2}-\d{3}-\d{4}$" required /> <input type="text" id="i_email" name="email" class="uk-width" placeholder="Email" pattern="/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/" maxlength="250" /> <input type="text" id="i_zipcode" name="zipcode" class="uk-width" placeholder="Zip Code" pattern="\d{5}-?(\d{4})?" /> <select name="scope" id="i_scope" class="uk-width" multiple required> <option value="" disabled>Representing...</option> <option value="residential">Residence</option> <option value="commercial">Business</option> </select> <textarea name="message" id="i_message" class="uk-width" placeholder="Message" rows="4" required></textarea> <input type="submit" name="submit" id="submit" class="uk-button uk-width" value="Send" /> <!--button type="submit" name="submit" id="submit" class="uk-button uk-width">Send <i class="fa fa-send"></i></button--> </div> </form> </div> Above is from contact.php template partial included in my _main.php output, which includes this script in the body closing: $(function() { $('.error').hide(); $("#inquire").submit(function(e) { e.preventDefault(); // validate and process form here $('.error').hide(); //var name = $("input[name='name']").val(); var name = $("input#i_name").val(); if (name == "") { $("label#name_error").show(); $("input[name='name']").focus(); return false; } //var phone = $("input[name='phone']").val(); var phone = $("input#i_phone").val(); if (phone == "") { $("label#phone_error").show(); $("input[name='phone']").focus(); //return false; } //var email = $("input[name='email']").val(); var email = $("input#i_email").val(); //var zipcode = $("input[name='zipcode']").val(); var zipcode = $("input#i_zipcode").val(); //var scope = $("select[name='scope']").val(); var scope = $("select#i_scope").val(); if (scope == "") { $("label#scope_error").show(); $("select[name='scope']").focus(); //return false; } //var message = $("textarea[name='message']").val(); var message = $("textarea#i_message").val(); if (phone == "") { $("label#message_error").show(); $("textarea[name='message']").focus(); //return false; } var dataString = 'name=' + name + '&phone=' + phone + '&email=' + email + 'zipcode=' + zipcode + 'scope=' + scope + 'message=' + message; //alert (dataString); return false; $.ajax({ type: "POST", url: "./inquiries/", data: dataString, success: function() { $('#wrap_form').html("<div id='inquired'></div>"); $('#inquired').html("<h3>Inquiry submitted!</h3>") .append("<p>Thanks, " + name + "! We will be in touch soon.</p>") .hide() .fadeIn(1500, function() { $('#inquired p').append(" <i class='fa fa-check' style='color:green'></i>"); }); } }); //return false; }); }); I tried submitting directly to a php file in templates which is forbidden so I saw that this worked for someone and no longer get an error; the form seems to submit from the frontend, however nothing results from it in the admin. Here's my inquiries.php template file: <?php $mailTo = $pages->get('/contact/')->contact_email; // sanitize form values or create empty $data = array( 'name' => $sanitizer->text($input->post->name), 'phone' => $sanitizer->text($input->post->phone), 'email' => $sanitizer->email($input->post->email), 'zipcode' => $sanitizer->text($input->post->zipcode), 'scope' => $sanitizer->text($input->post->scope), 'message' => $sanitizer->textarea($input->post->message), ); $error = ''; if($input->post->submit) { $up = $pages->get('/inquiries/'); $up->title .= "+"; $up->save(); $msg = "Name: $data[name]\n" . "Phone: $data[phone]\n" . "Email: $data[email]\n" . "Zip Code: $data[zipcode]\n" . "Job Type: $data[scope]\n" . "Message: $data[message]"; $p = new Page(); $p->title = date('Y/m/d H:i:s'); $p->parent = $pages->get('/inquiries/'); $p->template = 'inquiry'; $p->message = $msg; $p->save(); } I added the inquiries title appendage bit just for testing, but it just doesn't happen. How can I make this work/better test?
  6. Just found http://intercoolerjs.org/ It does declarative ajax. Frontend wizardry without writing javascript. I'm impressed.
  7. I'm looking to do a specific type of module. I want to use the field-typemulti fieldtype. So what I want to accomplish is the first field part stores a category (movies, books, etc.). The Second input field would need to be an AJAX lookup that would let me choose the ID of that book so I can take it and save it into my post. So let's just say the thing I'm pulling from is IMDB, I'll choose the movie category, then On the lookup get a list of movies based on a search. IF you can point me and help me out with this i'd greatly appreciate it!
  8. I have a parent page containing a list of it's children. When you click on one of the children the page opens up in a modal box trough ajax. So far so good. But if i directly load the page through the url (parent/child) i get the child page. Is there a way of loading the parent page instead with the child page opened inside the modal box? I was first thinking of using URLSegments so it would load the parent page with the child name as segment however since the segment is an actual page it will load the page instead. Any ideas?
  9. Hi I'm having a torrid time with some Ajax code and a custom PHP script. I'll try to explain what I'm trying to do. I have a form with a single email field. I validate the email field and if it's okay, I then make an Ajax call to my custom PHP script which needs to do some ProcessWire stuff to the user with that email address. What I'm finding is, if I put my PHP code inside the templates folder, it is not executing at all. From what I've read, ProcessWire denies access to PHP files in this directory. So I've then tried putting the PHP file in the root of my site, outside of PW. It then can see and execute the PHP file. The issue then is that i can't access the PW commands to make the changes to the user. At least, I don't think I can from outside of PW. Any help gratefully received!
  10. Hello, I have a PHP script being called by AJAX request. At this moment everything work perfectly, but my script is in the root directory, bootstraping PW. request = $.post('/public_html/pw/contactus.php', serializedData); My question is, it is possible to put this PHP script in my templates directory and call it from there ? (if I hardcode the path I get a 403 HTTP error and doing that can cause problem between dev environment and production); How I should code my path in the Javascript code ?
  11. Let's say I have 500 Eventpages or more with differen content fields(date, title, textarea etc..). I would display all events in a list like this: $events = $pages->find("template=event, limit=10"); echo "<div class='event-container'>"; foreach($events as $event){ echo "<div class='event-detail'> <h1>$event->title</h1> <p>$event->short_description</p> </div>"; } echo "<a class='load-more'>LOAD MORE</a>"; echo "</div>"; Now I want to make the load-more link to display 10 or 20 more events without reloading the page and showing a loading gif/text while its rendering the other events, when clicking on it . How can i achieve this? I know that i could use pagination for displaying this heavy amount of results but the customer doesn't want that because it don't fit in the design of the website. Can I probably achieve a combination with Pagination and Ajax, or are there other ways to do it?
  12. Hi all, A question regarding security/best-practice concerning a simple front-end login through AJAX calls. My plan is to use this kind of module inside a small AngularJS architecture to update the entire application when someone is logged in/out. * I've made a simple HTML form in which the user can login by typing his/her username and password in the corresponding fields. After submitting the form, these values are fetched with jQuery. Then an Ajax GET request is made with these values to a page which has access to the Processwire API. This page checks if these values (after sanitization) correspond to an existing user in the CMS. If the user and password matches, the user is logged in, and a success message is being returned. If the user and password mismatches, an error message is being returned. * I don't know much about encryption, therefore I highly doubt if this a 'safe' way of doing things. Hopefully someone can give me some pointers on this! best, berechar
  13. Hello, i am trying to built a contact form using Ajax. here is my code <form method="post" action="<?=$config->urls->root;?>subscribe/contact.php" id="contactForm1"> <input type="text" id="fullname" name="fullname" class="textbox" placeholder="Your name" required=""> <input required="" type="email" id="email" name="email" class="textbox" placeholder="Your email" > <input type="submit" value="Send"> </form> here is my Java Script <script> $(function() { var frm = $('#contactForm1'); frm.submit(function (ev) { ev.preventDefault(); var fullname = $('#fullname').val(); var email = $('#email').val(); $.ajax({ type: 'post', url: frm.attr('action'), data: 'fullname=' + fullname+'&email=' + email, success: function(results) { if(results==1) { $("#suscess").show(); } if(results==2) { $("#fail").show(); } } }); // end ajax }); }); </script> and here is my PHP file <?php $emailTo = "myemail@domain.com"; // sanitize form values or create empty $form = array( 'fullname' => $sanitizer->text($input->post->fullname), 'email' => $sanitizer->email($input->post->email), ); $msg = "Full name: $form[fullname]\n" . "Email: $form[email]" ; if(mail($emailTo, "Website contact form submission", "$msg", "From: $form[email]")) { echo "1"; }else{ echo "2" } ?> the error i am getting is on $sanitizer->text mail( Undefined variable: email i am thinking may be this PHP file in root/subscribe thats why processwire variables are not loading. also i can't access the PHP from Template folder. how to fix this issue. Thanks
  14. I know how to create pages with the API. I need help with the form itself. Here's what I'm working with so far, hacked together from examples found in this forum: <?php $upload_path = $config->uploadTmpDir; $out = ''; // create a new form field (also field wrapper) $form = $modules->get("InputfieldForm"); $form->action = "./"; $form->method = "post"; $form->attr("id+name",'upload-form'); // create file field $field = $modules->get("InputfieldFile"); $field->label = "Audio File"; $field->attr('id+name','audio'); $field->description = "Upload your track(s)"; $field->destinationPath = $upload_path; $field->extensions = "mp3"; $field->maxFiles = 10; $field->maxFilesize = 2*1024*1024; // 5mb $field->required = 1; $form->append($field); // append the field // oh a submit button! $submit = $modules->get("InputfieldSubmit"); $submit->attr("value","Upload"); $submit->attr("id+name","submit"); $form->append($submit); // form was submitted so we process the form if($input->post->submit) { // user submitted the form, process it and check for errors $form->processInput($input->post); if($form->getErrors()) { // the form is processed and populated // but contains errors $out .= $form->render(); } else { // do with the form what you like, create and save it as page // or send emails. to get the values you can use // $email = $form->get("email")->value; // $name = $form->get("name")->value; // $pass = $form->get("pass")->value; // // to sanitize input // $name = $sanitizer->text($input->post->name); // $email = $sanitizer->email($form->get("email")->value); $out .= "<p>You submission was completed! Thanks for your time."; } } else { // render out form without processing $out .= $form->render(); } $content .= $out; That outputs the form but I can't drag & drop or input more than one file, and when I submit it says "Missing required value". I need to at least create one or more pages from the form submission, i.e., one per file uploaded. If possible I'd like to be able to set the title and description for each file/page as well.
  15. Hello, I need to connect two PW sites, both with rather big pagetrees. When adding a page to site A, the editor should be able to select one or more related pages from site B (one is an editorial news site, the other a product cataloque) My idea was to build an API for site B which writes JSON data of the applicable pages and feed that into my custom inputfield which would be heavily influenced by PageListSelect. Now my questions: Has anyone built something similar? Since this would be my first custom field / inputfield, where should I look for help? Does this sound like a reasonable approach or are there other ways to connect two PW sites? Thanks for any help, thomas
  16. Hi, I'm about to start developing a website in Processwire but did a bit of research and could'nt find any way to create a form with confirmation message loaded by AJAX when a form is submitted + validated. Is that possible? I think of something similar to Contact Form 7 for WP (when the visitor submits the form it should get validated and if every field validates and email gets sent the visitor gets a message like "Thank you for your message!" without page reload). Is that possible to do this in Processwire or anything thats on the Feature list? From what i can understand theres three modules (Form builder, Form Template Processor and Mailer and Simple Contact Form) that can create forms and also a API-function to call and create the form manually. Is there any of the above which supports ajax submit with "Thank you"-message on the same page without reloading the page on submit? Seems pretty basic, but maybe i've missed something. Thank you!
  17. I'm having problem with setting global session variable in $config->ajax block. To be more clear, here is example: This will not work: if($config->ajax) { $_SESSION["TEST"] = "test" } and then after "normal " page rendering with no ajax I get nothing when trying to get session variable: echo($_SESSION["TEST"]); // produces no output however, if I set variable outside $config->ajax block: if($config->ajax) { // this is left blank to better describe context } else { $_SESSION["TEST"] = "test"; } and then after "normal " page rendering with no ajax - I get what I expect: echo($_SESSION["TEST"]); // produces "test" as output. So, what I want is set some global session variable inside ajax call and then reuse it's value during any page reload. It's late and I probable miss something.
  18. Hi folks, I am using AJAX on a site I am building, specifically PJAX, and I have built all this locally and it has all been working great with no problems. Upon pushing this from local to remote the AJAX is failing to retrieve my pages, and thus falling back to the normal page loading. I have had a look at the Network tab in Google devtools to find out more and it looks like the request goes through but the PJAX url call (for example: http://www.juleslister.co.uk/projects/photography?_pjax=%23pjax) is returning as a 301 error. I have a screenshot of the Network issue here: http://i.imgur.com/oC2ZPce.png Any thoughts? Many thanks, R
  19. Hi folks, I'm building a fairly simple site using PW but I am also working with AJAX driven content (as noted by @ryan here: https://processwire.com/talk/topic/225-how-to-work-with-ajax-driven-content-in-processwire/) and everything works fine except for the change of body classes per page. So, for example, in the head.inc I have the following: <body class="<?php echo $page->name; ?>"> which is useful as it means I can create page specific styles etc. However, as the head and foot remain constant if an AJAX request is called using the following, for example: <?php if(!$config->ajax) include('./head.inc'); ?> the body class fails to update for obvious reasons. Is there any way round this so the body class is updated per ajax call, if you know what I mean? This may be a global AJAX question and not a PW specific question but thought I would ask all the same. Thanks, R
  20. This is a site for composer, conductor, and NYU composition professor Louis Karchin. http://louiskarchin.com/ The site is based around the works which are presented as a filterable datatable, with inline audio player (soundmanager2).. There is some ajax happening on the works page to pull up details about a work in a popup. a lot of the initial work was importing from the original site as well as from CSV files of the works, so there were various custom import/api scripts used to get all the data in.. As with other recent sites, this site has a admin docs section for reference, as well as inline docs on the edit page, using a simple module based on Nik's page references tab. also this uses the configurable widgets system: and i have an admin page for backups, though the backups run automatically on a cron (using the SmartBackup script): this site benefited from a lot of modules, namely: AdminCustomFiles AdminCustomPages PageDocsTab AdminPageSelectEditLlinks AIOM+ FieldtypeDataStructure FieldTypeTemplates InputfieldSelectExtended HannaCode ProcessRedirects ProcessDiagnostics Profields Table Formbuilder Procache Lister Pro
  21. The current default for the Comments module seems to be... 1.) User enters name, email and comments 2.) User hits submit 3.) Page is refreshed 4.) Thank-you message or error message returned How do we avoid step 3, the page refresh? Is it possible with the standard commenting system? Some sort of AJAX must be involved, but I don't know if it's possible to modify the current comments system to accommodate this. Any pointers much appreciated.
  22. Hello, I have a new project in which people from site A should have the possibility to post a "news" which should automatically appear in site B. I think it's not possible to merge two PW installations by bootstraping site B to site A. Don't ask why both pages are not in the same installation ;-) My idea is to use a hook and post the data via ajax to a script which bootstraps site B. Then I post the data into that installation. To be capable to update the news simultanious in both installations I would use an unique field in both installations which will be the "id". Has anyone some better ideas or hints?
  23. Hi guys ! First real project with ProcessWire, and I can say I adopted the platform. It's incredibly fun to work with ! I'm currently making a Google Maps interface, in which I can add branch offices in the backend as pages. Each pages have data : title, latitude longitude etc. and compare it with the user geoloc or a geocoded address. At first, I fetch the childrens ID, latitude and longitude, json_encode them in an array. Then, I find the 3 nearest offices and play with data until I need to get the rest of the data matching the IDs, so I can show detailed profiles of the 3 nearest offices. I'm currently debugging with static data, and I get a 500 internal server error on MAMP... but I don't know, it seems my setup is not showing PHP errors properly. Here is my Javascript function (executed on dom ready elsewhere) : File main.js : function fetchOfficeData() { $.ajax({ url: 'http://127.0.0.1:8888/site/ajax/fetchoffice.php', type: "POST", dataType:'json', data: ({id: 1013}), success: function(data){ console.log(data); } }); } File fetchoffice.php : //Format to fetch the office with the ID $sel_id = 'id=' . (string)$_POST[id]; $result = $page->child($sel_id)->title; echo json_encode($result); But I get an error and I suspect it's because I cannot use selectors in my AJAX page because it's not in my template. I'm able to output $sel_id, or anything else for that matter, but using $page->child... doesn't work. Is it possible to put this code inside my template so the selectors work ? Another solution could be to fetch all the data of all the offices and put them in the json_encode array at the beginning... there will be 30 offices max... but I don't feel like it's the right thing to do. Thank you very much in advance
  24. I am trying to do frontend page creation via AJAX but when the form is loaded into an element, things like CKeditor and proper image uploading do not work. It seems javascript should be re-initialized on the elements that got added to the DOM after the initial page has loaded, but I don't know how to do this (if that is even what should be done in the first place)? I got it working fine without AJAX, via a regular template. But when I move the code to a file that is called by AJAX, javascript breaks on the form hence things like CKeditor don't work. Here's what's in HEAD of the main template: <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title><?php echo $headline; ?></title> <link rel="stylesheet" href="<?php echo $config->urls->templates;?>css/foundation.css" /> <script src="<?php echo $config->urls->templates;?>js/vendor/modernizr.js"></script> <!-- Somatonic page edit script --> <script> <?php $jsConfig = $config->js(); $jsConfig['urls'] = array( 'root' => $config->urls->root, 'admin' => $config->urls->admin, 'modules' => $config->urls->modules, 'core' => $config->urls->core, 'files' => $config->urls->files, 'templates' => $config->urls->templates, 'adminTemplates' => $config->urls->adminTemplates, 'adminTemplates' => $config->urls->adminTemplates, ); ?> var config = <?php echo json_encode($jsConfig); ?>; </script> <?php //$config->styles->prepend($config->urls->adminTemplates . "styles/main.css?v=2"); //$config->styles->append($config->urls->adminTemplates . "styles/inputfields.css"); //$config->styles->append($config->urls->adminTemplates . "styles/ui.css?v=2"); $config->scripts->append($config->urls->JqueryUI . "JqueryUI.js"); $config->scripts->prepend($config->urls->JqueryCore . "JqueryCore.js"); $config->scripts->append($config->urls->adminTemplates . "scripts/inputfields.js"); foreach($config->styles->unique() as $file) echo "\n\t<link type='text/css' href='$file' rel='stylesheet' />"; foreach($config->scripts->unique() as $file) echo "\n\t<script type='text/javascript' src='$file'></script>"; ?> </head> It loads all the necessary script for frontend page creation. And here is the template that does the form processing: if ($command == "template_selection") { // Selected template ID $id = htmlspecialchars($_POST['template_id']); $page = $pages->get($id); $template = $page->template; foreach($template->fields as $field){ echo $field->label . ": "; //echo $field->type . "<br/>"; echo $page->get($field->name) . "<br/>"; } // make a form $form = $modules->get('InputfieldForm'); $form->method = 'post'; $form->action = './'; // add the page's fields to the form $form->add($page->getInputfields()); // add a submit button to the form $submit = $modules->get('InputfieldSubmit'); $submit->name = 'submit'; $form->add($submit); // process the form if it was submitted if($input->post->submit) { $form->processInput($input->post); $page->save(); echo '<p>saved</p>'; } // render the form output echo $form->render(); die; } This template works properly when not called by AJAX, but, again, when I call it with an AJAX request, the javascripts don't work. Is there any way I can make this work?
  25. I'm using the delayed output template structure the way Ryan recommends. That means I have a _main.php file with all of my HTML markup and each page has a template that outputs to a variable that is echo'd in _main.php. Now I doing some very basic ajax testing, to figure out how this fits into the Processwire workflow. I'm already running into an issue: the file that handles the ajax request is not only outputting the data I'm requesting, but it's also outputting the complete _main.php markup into the ajax container where only the result of my ajax request should be going. Here what I've got: _main.php (greatly simplified) <html> <body> <!-- template output goes here --> <p><?php echo $bodycopy; ?></p> <p>This line will unfortunately also be output to the ajax container</p> </body> </html> ajax_test.php template <?php ob_start(); ?> <?php ?> <form method="post" enctype="multipart/form-data"> <div id="enter_template_container"> <input type="text" name="select_template" id="select_template"/> </div> <p> <a href="#" class="button" id="button_select_template">Search</a> </p> </form> <div id="placeholder_template"></div> <?php $bodycopy .= ob_get_clean(); front.js /** Simple ajax test: search templates **/ var show_template = function(template) { // Ajax data = { template_search: template, command: 'show_template' // add a unique command value to every ajax call so we can identify what function to call in function.php }; $.post("../functions/", data, function (response) { // Add form $('#placeholder_template').html(response); }).fail(function() { // Just in case posting your form failed alert( "Posting failed." ); }); } $('#button_select_template').on('click', function() { var template = $('#select_template').val(); show_template(template); }); functions.php template (yes I have a Wordpress background ;-)) /** Simple ajax test: search templates **/ if ($command == "show_template") { $template = $templates->get(htmlspecialchars($_POST['template_search'])); foreach($template->fields as $field){ echo $field->name . "<br/>"; } } Functions.php does the ajax output which is placed in a div with "placeholder_template" ID in a template called ajax_test.php. The problem is that all the contents of _main.php are also put into that div, not just the output generated by functions.php. What is the best way to counter this behavior? Is it a good idea to add "die;" at the end of the functions.php template for instance? What's the best way to deal with this?
×
×
  • Create New...