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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By ngrmm
      I have a page with a table. Each table row has a page-reference field and a checkbox.
      The Page sends emails to all users (page-refrence->email-field) and change the value of the checkbox in a row to 1.
      It works with this:
      <?php // event ID fron url query $eventID = $input->get('eventID','int'); // get event-page $event = $pages->get($eventID); // config $fromEmail = $event->event_mail_from; $fromName = $event->event_mail_from_name; $emailSubject = $event->event_subject; // email html body ob_start(); include('./_inc/emailbody.inc'); $emailBody = ob_get_clean(); // make event-page editable $event->of(false); // loop through table and send out emails foreach($event->event_clients_list as $event_table_row) { // get client page $clientPage = $event_table_row->client_name; // get client email $clientEmail = $clientPage->email; // if client isn't invited yet (checkbox not checked) if($event_table_row->client_invited == '') { // send email $m = new WireMail(); $m->to($clientEmail); $m->from($fromEmail, $fromName); $m->subject($emailSubject); $m->bodyHTML($emailBody); $m->send(); // mark client as invited $event_table_row->client_invited = 1; $event->save('event_clients_list'); } } ?> But i have to use a variable in my emailbody.inc which i'm able to get in the table-loop.
      So i do the including of the body inside my loop. But this doesn't work anymore. Page sends out the emails but is unable to change the value of the checkbox.
      I get no errors!
      I'm using ProTable
      <?php // event ID fron url query $eventID = $input->get('eventID','int'); // get event-page $event = $pages->get($eventID); // config $fromEmail = $event->event_mail_from; $fromName = $event->event_mail_from_name; $emailSubject = $event->event_subject; // loop through table and send out emails foreach($event->event_clients_list as $event_table_row) { // get client page $clientPage = $event_table_row->client_name; // get client email $clientEmail = $clientPage->email; // email html body ob_start(); include('./_inc/emailbody.inc'); $emailBody = ob_get_clean(); // make event-page editable $event->of(false); // if client isn't invited yet (checkbox not checked) if($event_table_row->client_invited == '') { // send email $m = new WireMail(); $m->to($clientEmail); $m->from($fromEmail, $fromName); $m->subject($emailSubject); $m->bodyHTML($emailBody); $m->send(); // mark client as invited $event_table_row->client_invited = 1; $event->save('event_clients_list'); } } ?>  
    • By Vigilante
      In general, is there an easy way to know which method should be used to access the API?
      For example, when _ini.php is used in the theme, it would seem you have to use wire()->addHookBefore(...). But on other sites where they used ready.php, I've seen it go straight to just doing $this->addHookAfter() even though there is no class or namespace set up in the ready.php file.
      So how do I know when I can do $this, or $wire, or wire() to access things? And any other variables I'm not aware of.
      Thanks!
    • By michelangelo
      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?
       

    • By VeiJari
      Hello forum,
      This is really a weird one, because front end editing works in a earlier website we did to a customer. 
      When I check the source code for current website it does initiate front end edit: 
      <span id=pw-edit-1 class='pw-edit pw-edit-InputfieldPageTitle' data-name=title data-page=1021 data-lang='1017' style='position:relative'><span class=pw-edit-orig>Tekijät</span><span class=pw-edit-copy id=pw-editor-title-1021 style='display:none;-webkit-user-select:text;user- select:text;' contenteditable>Tekijät</span></span>  But when I double click nothing happens (yes I'm 100% sure I'm superuser and logged in)
      I also tried to apply the front end with other methods than:
      $page->edit('title'); But didn't work either.
      We are using jquery 2.2.4, so it should not be a problem.
      Is this a bug related to current master or something else?
      Someone else having this problem as well?
    • By jom
      Hi everyone
      It seems that I don't fully understand the wireTempPath() function and I need some help.
      I use wireTempPath() to create a new location in assets/cache/WireTempDir and than copy a pdf from the assets/files/page folder to the new folder. I want the file to be accessible only for a limited time, that's why I use wireTempPath.
      The file seems to be copied to the right location, but gets deleted right afterwards, according to 
      As mentioned in the topic above, 
      $wireTempDir->setRemove(false); prevents the file to be deleted. But I like the file to be automatically deleted after a few days. So, how can I do that?
      My code so far (everything works, but the automatic removal of the tempDir folder):
      //generate and show download link $folder = time(); // timestamp as temporary folder $maxAge = (int) $settings->options_downloadlink_valid_hours * 3600; //tempDir wants maxAge as seconds $options = array( 'maxAge' => $maxAge ); $wireTempDir = wireTempDir($folder, $options); $wireTempDir->setRemove(false); $src_file = $page->ebook_download->filename; // Create a new directory in ProcessWire's cache dir if(wire('files')->mkdir($wireTempDir, $recursive = true)) { if(wire('files')->copy($src_file, $wireTempDir)){ //get subdirs from tempDir: $pos = strpos($wireTempDir, "WireTempDir"); $subdir = substr($wireTempDir, $pos, 100); $out .= "<p><a href='" . wire('pages')->get('template=passthrough')->httpUrl . "?file=" . $subdir . $page->ebook_download->basename . "' target='_blank'>$page->title</a></p>"; } } I appreciate any ideas - thanks!
      Oliver
×
×
  • Create New...