Viewed   117 times

Q.1 I would like to convert this form to ajax but it seems like my ajax code lacks something. On submit doesn't do anything at all.

Q2. I also want the function to fire on change when the file has been selected not to wait for a submit.

Here is JS.

$('#imageUploadForm').on('submit',(function(e) {
    e.preventDefault()
    $.ajax({
        type:'POST',
        url: $(this).attr('action'),
        data:$(this).serialize(),
        cache:false
    });
}));

and the HTMl with php.

<form name="photo" id="imageUploadForm" enctype="multipart/form-data" action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
    <input type="file" style="widows:0; height:0" id="ImageBrowse" hidden="hidden" name="image" size="30"/>
    <input type="submit" name="upload" value="Upload" />
    <img width="100" style="border:#000; z-index:1;position: relative; border-width:2px; float:left" height="100px" src="<?php echo $upload_path.$large_image_name.$_SESSION['user_file_ext'];?>" id="thumbnail"/>
</form>

 Answers

2

first in your ajax call include success & error function and then check if it gives you error or what?

your code should be like this

$(document).ready(function (e) {
    $('#imageUploadForm').on('submit',(function(e) {
        e.preventDefault();
        var formData = new FormData(this);

        $.ajax({
            type:'POST',
            url: $(this).attr('action'),
            data:formData,
            cache:false,
            contentType: false,
            processData: false,
            success:function(data){
                console.log("success");
                console.log(data);
            },
            error: function(data){
                console.log("error");
                console.log(data);
            }
        });
    }));

    $("#ImageBrowse").on("change", function() {
        $("#imageUploadForm").submit();
    });
});
Friday, August 12, 2022
2

I have worked with translations in my CMS and many times i require specific strings to be used in an otherwise static plain text as a javascript file. What i do:

en.php

return array(
   "id1"=>"translation 1",
   "id2"=>"translation 2"
);

HTML

...
$trans = require("en.php");
...
<input type="hidden" id="trans" data-trans='<?php echo json_encode($trans); ?>' />
...

JS

$(document).ready(function() {
   var id1 = $("#trans").data("trans")["id1"];   // contains the 'id1' string
});

This way your javascript would not need changing, which results many times in history caching related problems for your clients, as they need refreshing.

Sunday, October 2, 2022
 
dawid
 
2

Thanks for you help, I change my dynamic about the script so now, it works perfectly with what I have to do.

There is the script for my upload system :

<-- VIEW (upload_img)-->

<div id="container">
<div id="filelist"></div>
<a href="http://localhost:8888/myproject/#" id="userfile" name="userfile">[Select files]      </a>    
<a href="http://localhost:8888/myproject/images/index#" id="uploadfiles">[Upload files]</a
</div>

<-- CONTROLLER -->

function index(){
    if($this->_access())
    {
        $this->template->add_include('js/jquery.js')
                       ->add_include('js/browserplus.js')
                       ->add_include('js/plugins/plupload/plupload.full.js')
                       ->add_include('js/imgfunc.js');
        $this->template->view('upload_img');
    }
    else
    {
        redirect(site_url());
    }
}

function upload_image_spot()
{
    if($query = $this->images_model->upload_image_spot())
    {
        echo json_encode($query);
    }
    else
    {
        echo $this->upload->display_errors('', '');
    }
}

<-- MODEL -->

   function upload_image_spot()
{
    $config['upload_path'] = realpath(APPPATH. '../images/spots');
    $config['allowed_types'] = 'jpg|jpeg|tiff|png';
    $config['max_size'] = 3062;
    $config['encrypt_name'] = TRUE;
    $this->load->library('upload', $config);
    if($this->upload->do_upload('file')) 
    // file means the file send to the website for upload, this is the name of field for Plupload script
    {
    $data_img = $this->upload->data();
    $copies = array(
            array('dir' => 'images/spots/large/', 'x' => 1000, 'y' => 600),
            array('dir' => 'images/spots/thumb/', 'x' => 100, 'y' => 60)
    );

    $this->copies($data_img,$copies);

    return 'whatever'; // Not real data, I don't wanna post them here
    }
}

<-- JS-SCRIPTS -->

First of all include :

-jQuery

-browserPlus

-Plupload

(Plupload Script)

Now add this script in an empty file:

var uploader = new plupload.Uploader({
    runtimes : 'gears,html5,flash,silverlight,browserplus',
    browse_button : 'userfile',
    container : 'container',
    max_file_size : '3mb',
    url : 'yourUploadFunctionCI',
    flash_swf_url : 'plugins/plupload/js/plupload.flash.swf',
    silverlight_xap_url : 'plugins/plupload/js/plupload.silverlight.xap',
    filters : [
        {title : "Image files", extensions : "jpg,jpeg,JPG,JPEG,tiff,png"},
    ]
});

uploader.bind('Init', function(up, params) {
});

$('#uploadfiles').click(function(e) {
    uploader.start();
    e.preventDefault();
});

uploader.init();

uploader.bind('FilesAdded', function(up, files) {
    $.each(files, function(i, file) {
        $('#filelist').html("");
        $('#filelist').append(
            '<div id="' + file.id + '">' +
            file.name + ' (' + plupload.formatSize(file.size) + ') <b></b>' +
        '</div>');
    });

    up.refresh();
});

uploader.bind('UploadProgress', function(up, file) {
    $('#' + file.id + " b").html(file.percent + "%");
});

uploader.bind('Error', function(up, err, msg,file) {
    $('#filelist').append("<div>Error: " + err.code +
        ", Message: " + err.message +
        (err.file ? ", File: " + err.file.name : "") +
        "</div>"
    );
    console.log(msg,up,err);
    up.refresh();
});

uploader.bind('FileUploaded', function(up, file,response) {
    $('#' + file.id + " b").html("100%");
    var data = jQuery.parseJSON(msg.response);
    console.log(data);
});

Do your own customization and that's it, no need extra script like you can see on website like copy/paste all script from a php file to a controller, just add 'file' inside do_upload and everything's gonna work fine !

Have a nice day guys, hope it's help.

Simon

Friday, December 2, 2022
 
3

Please Try :

I have modify your code.

Jquery (added FormData() and append)

function apfaddpost() {
    var fd = new FormData();
    fd.append( "main_image", $('#main_image')[0].files[0]);
    fd.append( "action", 'apf_addpost');      
   //Append here your necessary data
    jQuery.ajax({
        type: 'POST',
        url: apfajax.ajaxurl,
        data: fd, 
        processData: false,
        contentType: false

        success: function(data, textStatus, XMLHttpRequest) {
            var id = '#apf-response';
            jQuery(id).html('');
            jQuery(id).append(data);
            resetvalues();
        },

        error: function(MLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }

    });
}

in function.php

I have added file upload code

/******FILE UPLOAD*****************/
function upload_user_file( $file = array() ) {    
    require_once( ABSPATH . 'wp-admin/includes/admin.php' );
    $file_return = wp_handle_upload( $file, array('test_form' => false ) );
    if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
        return false;
    } else {
        $filename = $file_return['file'];
        $attachment = array(
            'post_mime_type' => $file_return['type'],
            'post_title' => preg_replace( '/.[^.]+$/', '', basename( $filename ) ),
            'post_content' => '',
            'post_status' => 'inherit',
            'guid' => $file_return['url']
        );
        $attachment_id = wp_insert_attachment( $attachment, $file_return['url'] );
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
        wp_update_attachment_metadata( $attachment_id, $attachment_data );
        if( 0 < intval( $attachment_id ) ) {
          return $attachment_id;
        }
    }
    return false;
}

now modify your function apf_addpost() in function.php

function apf_addpost() {
     foreach( $_FILES as $file ) 
     {  
          if( is_array( $file ) ) {
                $attach_id =upload_user_file();  //Call function 
                update_post_meta($pid,'_thumbnail_id',$attach_id);
          }
     }

}
Saturday, December 3, 2022
 
szg
 
szg
1

you can use following code :

var form = new FormData($('#form_step4')[0]);
form.append('view_type','addtemplate');
$.ajax({
    type: "POST",
    url: "savedata.php",
    data: form,
    cache: false,
    contentType: false,
    processData: false,
    success:  function(data){
        //alert("---"+data);
        alert("Settings has been updated successfully.");
        window.location.reload(true);
    }
});

where savedata.php is the file name in which you can do the the DB things

Friday, December 16, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :