atomaprchya
atomaprchya

Reputation: 175

PHP is not recieving JSON data from jQuery

I am trying to use ajaxFIleUpload in my website. I am not recieving JSON data send by JavaScript to PHP. I am stuck at this point. File Uploading is ok but i am not able to recieve any post values. My jQuery function is

$(function() {

    $(document).on("submit", "#upload_file", function(e) {

        e.preventDefault();

        $.ajaxFileUpload({
            url             :base_url + 'payments/uploadPaymentSlip/',
            secureuri       :false,
            fileElementId   :'userfile',
            type        : 'POST',
            data: { paymentFormInputAmount: 'asdasd' },
            success : function (data, status)
            {
                if(data.status != 'error')
                {
                    $('#files').html('<p>Reloading files...</p>');
                    //refresh_files();
                    $('#files').val('');
                }
                alert(data.msg);
            },
           dataType: 'json'
        });

    });
});

My PHP Function is

function uploadPaymentSlip() {
    $status = "";
    $msg = "";
    $file_element_name = 'userfile';

    $status = "error";
    // checking whether json value shows in php or not
    // $_POST['paymentFormInputAmount'] is also not working
    $msg = $_POST['paymentFormInputAmount'];

    if ($status != "error") {
        $config['upload_path'] = realpath( APPPATH . '../uploads/paymentSlip' );
        $config['allowed_types'] = 'gif|jpg|png|doc|txt';
        $config['max_size'] = 1024 * 8;
        $config['encrypt_name'] = TRUE;

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload($file_element_name)) {
            $status = 'error';
            $msg = $this->upload->display_errors('', '');
        }
        else {
            $data = $this->upload->data();
            // $file_id = $this->files_model->insert_file($data['file_name'], $_POST['title']);
            if($file_id) {
                $status = "success";
                $msg = "File successfully uploaded";
            }
            else {
                unlink($data['full_path']);
                $status = "error";
                $msg = "Something went wrong when saving the file, please try again.";
            }
        }
        @unlink($_FILES[$file_element_name]);
    }

    echo json_encode(array('status' => $status, 'msg' => $msg));
}

Upvotes: 1

Views: 125

Answers (1)

alpakyol
alpakyol

Reputation: 2459

type: 'json' must be type: 'POST'

and you should add:

contentType: 'json',
dataType: 'json'

as parameter to $.ajaxFileUpload

contentType means you are sending your data as json.

dataType means you are expecting result as type of json.

Upvotes: 1

Related Questions