Jump to content
louisstephens

Saving Image from Ajax POST to page

Recommended Posts

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. 

Share this post


Link to post
Share on other sites
14 hours ago, louisstephens said:

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.

Hi Louis,

 

1- In the form, change the name of the input :

<!-- from -->
<input type="file" id="preview-name" name="preview-name">

<!-- to -->
<input type="file" id="preview_name" name="preview_name">

 

2- In your JS code, use FormData() and add the contentType prop to the $.ajax call (that's the key here) :

$('#submit-preview').click(function(e) {
    e.preventDefault();
    title = $("#preview").val();
    image = $('input[name=preview_name]').prop('files')[0]; // modified
    form_data = new FormData(); // added
    form_data.append('preview_name', image); // added
    form_data.append('title', title); // added
    console.log(title);
    console.log(image);
    
    $.ajax({
        type: 'POST',
        data: form_data,
        url: '/development/upload-preview/',
        contentType : false, // added
        processData : false, // added
        success: function(data) {
            console.log("Woo");
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert(xhr.responseText);
        }
    });
});

 

3- The ajax template file look good.

 

The main reason that WireUpload doesn't work here, is because it couldn't  find the right field name (form input name) :

$u = new WireUpload('preview_image');


 

 

 

 

  • Like 4

Share this post


Link to post
Share on other sites

You have officially saved my sanity flydev! Thank you so much. I had stared at/fiddled with this all day yesterday to no avail. 

  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By ICF Church
      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
    • By quickjeff
      Hi Guys, 
      I have been debugging a site for the last 2 hours and cannot solve the issue. 
      I have a site running on 3.0.148. 
      I installed the Kongondo Blog module and was updating the templates to include the website style. 
      Once everything was set and done, I checked the page tree to see an error appear. 
      Template must be assigned a name before 'filename' can be accessed
      The same error appears in templates. 
      Debugging Steps
      I checked the templates in the server to ensure I didnt accidentally delete the namespace.  Deleted cache in browser and server under assets Still no go. 
      Any help is appreciated. 
      Thanks! 
    • By Spyros
      Hello
      I'm having a strange issue with the $page->find(), for some reason I'm missing some of the pages from the results. I found then that I was missing all the pages with the same "PAGE NAME". Is it a bug or am I missing something?
      PS 
      If I change the "PAGE NAME" of one of the missing ones then I'm retrieving the page without any problem.
      Thank you
    • By Guy Incognito
      This short script loops through some images from an XML feed and pushes new ones to an image field. It all works perfectly, except for some reason the last image (only) in the loop each time doesn't receive the image description... can everyone spot why? TIA! 🙂 
      foreach ($propertyImages as $img) { $fileName = trim($img[0]); if ( !empty($fileName) ) { $imgPath = '../property_data/'.$fileName; if(file_exists($imgPath) && !in_array(strtolower($fileName),$currentImages)) { $p->property_images->add($imgPath); $p->save(); $newImg = $p->property_images->last(); $newImg->description = $img[1]; $p->save(); } } }  
    • By MateThemes
      Hello everyone!
      I am working with Processwire since some time. But some topics are quite hard for me.
      I have a Portfolio (Gallery) Page.
      I am build a template with Portfolio Index and pages with portfolio entries.
      Structure:
      Portfolio Index
      -- Portfolio Entry
      -- Portfolio Entry
      and so on.
      Portfolio Entry has an Image field with max 12 images and are accessible Templates. 
      Now I want to display the single Portfolio Entry on the Portfolio Index and Paginate them. In the index page all images of a single Entry page should be displayed (I should not be organized as albums, where a random image of the portfolio entry should be displayed). 
      I have no clue to achieve this. May someone could give me an advice.
      Thank you in advance!
×
×
  • Create New...