Jump to content

Saving Image from Ajax POST to page


louisstephens
 Share

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. 

Link to comment
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 5
Link to comment
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
 Share

×
×
  • Create New...