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 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!
  2. 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
  3. Just found http://intercoolerjs.org/ It does declarative ajax. Frontend wizardry without writing javascript. I'm impressed.
  4. 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 ?
  5. 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?
  6. hi i want to post variables to a page via ajax to get result from my database depenting my post value so my ajax is: var clickval = clickelement.value; var dataval = "city=" + clickval; $.ajax({ type: 'POST', url: "*MY PAGE SMART URL*", // e.g. http://my_domain/my_page.... data: dataval, dataType: 'text', //or json, i try both complete: function(data, status){ alert(data.responseText); } }); and in php page: $getcity = $input->post->city; echo "value = ".$getcity; just to show my post value... and my alert is "value = ". $getcity is empty and $input has no value inside and it seems like post is never be done, but i have no error in my console... can anyone help me?
  7. Hello, I try to realize some booking form via jQuery.post method. It works to send the data to the book.php file. Whats next ? How to handle the data right. this is the JS code jQuery.post("./book.php",{ xx_name: name, xx_email: email, xx_date: date, xx_time: time, xx_message:message, xx_contact: contact}, function(data) { jQuery(".book_online_form .returnmessage").append(data);//Append returned message to message paragraph if(jQuery(".book_online_form .returnmessage span.book_error").length){ jQuery(".book_online_form .returnmessage").slideDown(500).delay(2000).slideUp(500); }else{ jQuery(".book_online_form .returnmessage").append("<span class='book_success'>"+ success +"</span>") jQuery(".book_online_form .returnmessage").slideDown(500).delay(4000).slideUp(500); setTimeout(function(){ $.magnificPopup.close() }, 5500); } if(data==""){ jQuery(".book_online_form")[0].reset();//To reset form fields on success } }); It works for me i get the data but what now ? how to handlte this right ? this is the post.php <?php include("./index.php"); // include header markup $sent = false; $error = ''; $emailTo = 'my@email.here'; // or pull from PW page field // sanitize form values or create empty $form = array( 'fullname' => $sanitizer->text($input->post->name), 'email' => $sanitizer->email($input->post->email), 'comments' => $sanitizer->textarea($input->post->message), ); print "CONTENT_TYPE: " . $_SERVER['CONTENT_TYPE'] . "<BR />"; $data = file_get_contents('php://input'); // Dont really know what happens but it works print "DATA: <pre>"; var_dump($data); var_dump($_POST); var_dump($form); print "</pre>"; if($input->post->submit) { $name = $_REQUEST['xx_name']; echo "Welcome 1". $name; // DONT WORK }else{ echo "Something is wrong on the submit "; } if( $_REQUEST["xx_name"] ) { $name = $_REQUEST['xx_name']; echo "Welcome 2". $name; // WORK } I have attached the output. how to act with the pw $input->post->submit and the form array for example ??
  8. 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
  9. 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
  10. 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.
  11. There seems to be a problem with loading required javascript files for inputfields when a field is loaded via AJAX. For example, if I set the visibility of an Page reference field that uses asmSelect, the inputfield UI doesn't load (it's just a plain multi-select) and I'm seeing a JS error "$select.asmSelect is not a function". When ajax loads the fieldtype, it seems as though it's not loading jquery.asmselect.js Do these core inputfields need to be updated? How to write new inputfields so that the required js in included correctly when the field is loaded by AJAX? Has anyone found a solution to this? Thanks guys! -Brent edit: here's the announcement about these new AJAX options. It says that "The AJAX-driven features should now work with all core input fields (yes, even including files/images, repeaters (!), PageTable, asmSelect, and so on)." but it's not working for me in the Reno, or default theme. I'm working with the latest dev version of PW (2.6.17)
  12. 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 ) ); }
  13. 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
  14. 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!
  15. 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.
  16. 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
  17. 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
  18. 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.
  19. 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
  20. 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?
  21. 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
  22. Hi! Just started to dig into PW and since I have a small project starting I wonder that how does PW support dynamic forms out-of-the-box? Or perhaps through some module(s)? I'm creating a form(for visitors) that has options such as shape > size > color > availability/product which filter values for the last filter/select option (in this case availability). And is there any form field dependency implemented or is this just a matter of e.g. jquery events that trigger AJAX or visibility when field value is changed?
  23. 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?
  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...