Carl Youngman
Carl Youngman

Reputation: 57

passing data with JSON

What I want to be abl e to do is passing the form data to a php file and then having the results passed back into app so that the user isnt directly accessing the php file at any point.

This is what I came up with but I cant get it too pass the data. I used chrome with -disable-web-security. It always returns false so I guess the data isnt being passed to the php file. Any help would be great. Also. when it forwards to the results page, it goes blank after a few seconds. thank you.

HTML

<form id="form"   method="POST"  data-ajax="false" data-transition="pop" data-direction="reverse">
            <fieldset>


            <label for="name" class="ui-hidden-accessible">Name</label>
            <input type="text" name="name" id="name" value=""  class="required" placeholder="Name"/>


            <label for="email" class="ui-hidden-accessible">E-Mail</label>
            <input type="email" name="email" id="email" value="" class="required" placeholder="E-Mail"/>


            <label for="memory" class="ui-hidden-accessible">Memory</label>
            <textarea name="memory" name="memory" id="memory"  class="required" placeholder="Your Memory..."></textarea>



            <label for="submit" class="ui-hidden-accessible">Submit</label>
            <input type="submit" name="submit" id="submit" value="SEND">

             </fieldset>
        </form>

JS

$(document).on('pagebeforeshow', '#formPage', function(){

$(document).on('click', '#submit', function() { // catch the form's submit event

    if($('#name').val().length > 0 && $('#email').val().length > 0 && $('#memory').val().length > 0){


        var that = $(this),
            contents = that.serialize();


        // Send data to server through ajax call
        // action is functionality we want to call and outputJSON is our data


        $.ajax({
            url: 'http://www....',
            dataType: 'json',
            type: 'post',
            data: contents,
            async: true,
            beforeSend: function() {
                // This callback function will trigger before data is sent
                $.mobile.showPageLoadingMsg(true); // This will show ajax spinner
            },
            complete: function() {
                // This callback function will trigger on data sent/received complete
                $.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
            },

            success: function(data) {
                console.log(data);


            },
            error: function (request,error) {
                // This callback function will trigger on unsuccessful action
                alert('Network error has occurred please try again!');
            }
        });


    } else {
        alert('Please fill all nececery fields');
    }
    return false; // cancel original event to prevent form submitting
});
});

PHP

header('Content-type: text/javascript');

$json = array(
'success'       => false,
'result'        => 0


);

if(isset($_POST['name'], $_POST['email'], $_POST['memory'])){

$name       = $_POST['name'];
$email      = $_POST['email'];
$memory     = $_POST['memory'];

$json['success'] = true;
$json['result']  = $name;

}

echo json_encode($json);

Upvotes: 0

Views: 1652

Answers (1)

Drew
Drew

Reputation: 4373

You are not serializing the form data correctly and the result is that the contents variable is empty.

Change this code:

  var that = $(this),
  contents = that.serialize();

To this:

 //var that = $(this),  // <-- delete this line
 contents = $('#form').serialize();

YOU ALSO NEED TO FIX ..

You haven't realized it yet but you have created a multiple click binding issue by placing your click handler in the bagebeforeshow event. In order to prevent that from occuring you need to

Change this code:

 $(document).on('pagebeforeshow', '#formPage', function(){

To this:

 $(document).on('pageinit', '#formPage', function(){

This way your $(document).on('click', '#submit', function() { is only ever bound once regardless of how many times a user leaves and returns to the '#formPage' page

EDITED

No, the data submitted to your backend PHP program via ajax is not json encoded. It is standard HTTP POST data and is accessed via $_POST (or $_REQUEST).

I have your code (with the changes I outlined in my answer above) working on my server. I have placed the two files I setup to test your code in a pastbin for your reference:

The php file:

(edit the path to the included javascript file for your environment)

sandbox_ajax_form.php

The javascript file:

(edit the path that the form data is sent to)

sandbox_ajax_form.js

Upvotes: 1

Related Questions