3

Problem:

I have a variable which is encoded in JSON and I'm stuck trying to figure out how this variable can be sent to a PHP page using jQuery/AJAX.

This is what I have tried so far.

  1. The file is uploaded using http://blueimp.github.io/jQuery-File-Upload/
  2. It gets processed by jQuery according to the JS code below.

JS code:

<script>    
    $(function () {
        'use strict';
        // Server-side upload handler:
        var url = 'process.php';

        $('#fileupload').fileupload({
            url: url,
            autoUpload: true,
            acceptFileTypes: /(\.|\/)(txt)$/i,
            maxFileSize: 5000000, // 5 MB               
            done: function (e, data) {

                setTimeout(function(){
                    $("#loading").html("Loading...");}, 1000);

                var formUrl = 'exec.php',

                // You'll have to re-encode to JSON, probably:
                formPerspective = JSON.stringify(data.result.formPerspective),

                // This is the newly added value ( Maybe this needs JSON aswell? )
                formTxtfile = JSON.stringify(data.result.formTxtfile),

                // Generate the form
                $form = $('<form action="'+ formUrl +'" method="post"></form>')
                        .append('<input type="hidden" name="Perspective" value="' + formPerspective + '">')
                        .append('<input type="hidden" name="Datafile" value="' + formTxtfile + '">')
                        .append('<input type="hidden" name="form_submitted">');

                // Submit the form
                $form.submit();
            },

            progressall: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('#progress .progress-bar').css(
                    'width',
                    progress + '%'
                );
            }
        }).prop('disabled', !$.support.fileInput)
            .parent().addClass($.support.fileInput ? undefined : 'disabled');
    });
</script>
  1. As you can see, it calls the PHP handler which is according to the code below.

PHP code:

<?php
    session_start();

    $folder      = 'upload';

    if (!empty($_FILES))
    {
        // Set temporary name
        $tmp    = $_FILES['files']['tmp_name'];

        // Set target path and file name
        $target = $folder . '/' . $_FILES['files']['name'];

        // Upload file to target folder
        $status = move_uploaded_file($tmp, $target);

        if ($status)
        {
            // Set session with txtfile name
            $_SESSION['txtfile']    = $_FILES['files']['name'];

            $text_file    = file('upload/' . $_SESSION['txtfile']);

            foreach ($text_file as $line_number => $line)
            {               
                if (strpos($line, "\t") === 0)
                {
                    // Remove commented column names and first \t
                    $dimensions = explode("\t", preg_replace("#\t/.+#", '', substr($line, 1)));
                }               
            }

            // Set dimensions
            $_SESSION['dimensions'] = str_replace('\n', '', $dimensions);

            $jsonReturn = array(
                'formPerspective'   => $_SESSION['dimensions'],
                'formTxtfile'       => $_SESSION['txtfile']
            );

            // Convert to JSON
            $encode = json_encode($jsonReturn);

            echo $encode;
        }
    }
?>

Desired solution:

I would like to take the information in $encode and send it using POST to the page "oe.lc". On OE.lc the variable is picked by using:

$_POST["Perspective"]

In addition, OE.lc checks if a form is submitted using:

$_POST["form_submitted"]

The JS should redirect to OE.lc upon submission (now it redirects to explorer.php).

Any ideas?

2
  • Ideas for what? What is the problem? No question or problem description here... Commented Nov 19, 2013 at 12:11
  • I want the array in $encode to be sent to "oe.lc" through JS. The array should be sent as a POST variable so it can be picked up by oe.lc. Commented Nov 19, 2013 at 12:14

2 Answers 2

2

Try to simply echo the $encode and then exit the script by using die();

Edit: You said you would like to add extra values to the form, first you need to change the php file that determines the return to Javascript in JSON:

$jsonReturn = array(
    'formPerspective' => $dimensions,
    'formTxtfile' => $_SESSION['txtfile'],
);

// Convert to JSON
$encode = str_replace('\n', '', json_encode($jsonReturn));

// The above will print out the following when echoed:
// {'formPerspective':["legs","skincover","weight","intelligence","speed"], 'formTxtfile': 'Not sure what this holds as data'}

die($encode);

The data should then be in data.result in the done callback you configured.

You probably want to forward the browser to oe.lc, how about you generate a form and submit that?

Edit: We should add our newly accuired value here:

$('#fileupload').fileupload({
        // ...
        done: function (e, data) {
                // Determine the url:
            var formUrl = 'http://oe.lc',

                // You'll have to re-encode to JSON, probably:
                formPerspective = JSON.stringify(data.result.formPerspective),

                // This is the newly added value ( Maybe this needs JSON aswell? )
                formTxtfile = JSON.stringify(data.result.formTxtfile),


                // Generate the form
                $form = $("<form action='"+ formUrl +"' method='post'></form>")
                        .append("<input type='hidden' name='Perspective' value='" + formPerspective + "'>")
                        .append("<input type='hidden' name='Datafile' value='" + formTxtfile + "'>")
                        .append("<input type='hidden' name='form_submitted'>")
                        .appendTo('body');

                // Submit the form
                $form.submit();
        },
        // ...
    });

Please let me know if that works for you!

Sign up to request clarification or add additional context in comments.

14 Comments

yeah! sending the form values would be better so that they can be retrieved in oe.lc page +1
I think we are on the right way, only one detail remains. I need to include another form input. This value is generated in process.php as $_SESSION['txtfile'], how can I return both this value and the $encode back?
Yes, you can add that to the initial $encode, I'll update my answer to reflect this for you.
Sorry, that's obvious, my bad! JSON.stringify() is only supported by major browsers, what browser are you using? You could try implementing json2.js from github.com/douglascrockford/JSON-js ( from json.org ), this adds the JSON object, and thus the JSON.stringify() method, to browsers that do not support it.
Try adding the form to the body before submit .appendTo('body'); FF could have an issue with that. I updated the code above.
|
0

Here is the complete code (not working in Firefox though):

<script>    
    $(function () {
        'use strict';

        // Server-side PHP upload handler
        var url = 'process.php';

        // File upload handler
        $('#fileupload').fileupload({
            url: url,
            dataType: 'json',
            autoUpload: true,
            acceptFileTypes: /(\.|\/)(txt)$/i,
            maxFileSize: 5000000, // 5 MB               
            done: function (e, data) {

                // Output alert message
                setTimeout(function(){
                    $("#loading").html("Loading...");}, 1000);

                // Form destination
                var formUrl = 'test.php',

                // Variables to be sent with the form
                formPerspective = data.result.formPerspective,
                formTxtfile = data.result.formTxtfile,

                // Generate the form
                $form = $("<form action='"+ formUrl +"' method='post'></form>")
                        .append("<input type='hidden' name='Perspective' value='" + formPerspective + "'>")
                        .append("<input type='hidden' name='Datafile' value='" + formTxtfile + "'>")
                        .append("<input type='hidden' name='form_submitted' value='true'>")
                        .appendTo('body');

                // Submit the form
                $form.submit();
            },

            // Progress indicator
            progressall: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('#progress .progress-bar').css(
                    'width',
                    progress + '%'
                );
            }
        }).prop('disabled', !$.support.fileInput)
            .parent().addClass($.support.fileInput ? undefined : 'disabled');
    });
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.