Liam G
Liam G

Reputation: 791

HTML Submit form to PHP but need to use Javascript for some parsing

So I have a form on a web page and I need to send the data to a php file. That much is okay - BUT there is a part of the form that can be added dynamically (using JavaScript) and so I need JavaScript to get this data and convert it to JSON (or any other format) and send to to the PHP file, preferably using POST.

My question is; how can I submit the form to PHP and then parse the specific area with JavaScript and then send that to the PHP form? Below is what I have:

<form id="dataForm" action="summary.php" method="post" onSubmit="parseData(this)">
    <div className="actorDivHTML">
        <div className="actorInfoDiv"> //can be added dynamically
            //dynamic <input className="actorInfo"> goes here
        </div>
    </div>
</form>

JavaScript (in a seperate file called "scripts.js" - declared at top of HTML page)

function parseData( form ) {
        var form = formID;

        //list of divs with this class name - dynamically added
        var infoDivs = form.getElementsByClassName( "actorInfoDiv" );
        var info = [];

        //loop through each div and append the raw data
        for ( i = 0; i < infoDivs.length; i++ ) {
            info.push( [ ...infoDivs[ i ].getElementsByClassName( "actorInfo" ) ] );
        }

        //extract the value of the input from the raw data
        var extractedInfo = [];
        for ( j = 0; j < info.length; j++ ) {
            var ind = [];
            for ( k = 0; k < info[ j ].length; k++ ) {
                ind.push( info[ j ][ k ].value );
            }
            extractedInfo.push( ind );
        }

        //  $.post('/summary.php',{array: JSON.stringify(extractedInfo)}); - first attepmt
        console.log( extractedInfo );

        //POST to PHP
        request = new XMLHttpRequest();
        request.open( "POST", "summary.php", true );
        request.setRequestHeader( "Content-type", "application/json" );
        request.send( JSON.stringify( extractedInfo ) );
    }

And the PHP file - which obviously doesn't get the JSON data as I would like

//gets all other form data
$str_json = file_get_contents( 'php://input' );
print_r( $str_json );
//continues to get all other form data

Happy to clarify and post more code!

Cheers!

EDIT1 - K3lly:

So my HTML file now looks like this:

<form id="dataForm" onSubmit="onSub()">
<input type="submit" name="submit_button" value="Submit">
<script src="https://code.jquery.com/jquery-1.10.2.js">
    function onSub(){
    $("#dataForm").submit(function(event){
    event.preventDefault();
    var data = $("#dataForm").serializeArray();
    //POST to PHP
    $.ajax({
       type: "POST",
       url: "summary.php",
       data: JSON.Stringify(data),
       success: function(response){
           //Do whatever you want when form is sent.
       },
       dataType: "JSON"
    });
}); 
}
</script>

And PHP:

echo json_decode($_POST);

However, when the submit button is clicked the URL shows all the form data like GET would and the summary.php page is never loaded? The URL also doesn't show any of the dynamically added inputs.

EDIT 2 - k3lly:

    $("#dataForm").submit(function(event){
    event.preventDefault();
    //var serData = $("#dataForm").serialize();
    var test = $("#title").val();
        var serData = 'test1='+test;
    //POST to PHP
    $.ajax({
       type: "POST",
       url: "summary.php",
       data: serData,
       success: function(response){
           //Do whatever you want when form is sent.
       },
       dataType: "JSON"
    });

In the PHP file:

$test = $_POST["test1"];
echo $test;

There is no output. What am I doing wrong?

Upvotes: 0

Views: 272

Answers (2)

qelli
qelli

Reputation: 2077

Since you are using jQuery as far I can see in your code, the solution to do this is a lot simpler.

Your JavaScript code will be as simple as:

$("#dataForm").submit(function(event){
        event.preventDefault();
        var data = $("#dataForm").serializeArray();
        //POST to PHP
        $.ajax({
           type: "POST",
           url: "summary.php",
           data: JSON.Stringify(data),
           success: function(response){
               //Do whatever you want when form is sent.
           },
           dataType: "JSON"
        });
}); 

After this, just make sure to read your POST data correctly with json_decode() in PHP. Try some debbuging first to see what you are getting server-side by echoing the entire POST result.

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44087

If you're passing the data via your JavaScript's XMLHttpRequest, then you don't need the form to be submitted - add an event listener and use preventDefault through JavaScript, and use document.getElementById to get the form:

<form id="dataForm">
    <!-- Your form data here
</form>

JS:

function parseData() {
    var form = formID;

    //list of divs with this class name - dynamically added
    var infoDivs = form.getElementsByClassName( "actorInfoDiv" );
    var info = [];

    //loop through each div and append the raw data
    for ( i = 0; i < infoDivs.length; i++ ) {
        info.push( [ ...infoDivs[ i ].getElementsByClassName( "actorInfo" ) ] );
    }

    //extract the value of the input from the raw data
    var extractedInfo = [];
    for ( j = 0; j < info.length; j++ ) {
        var ind = [];
        for ( k = 0; k < info[ j ].length; k++ ) {
            ind.push( info[ j ][ k ].value );
        }
        extractedInfo.push( ind );
    }

    //  $.post('/summary.php',{array: JSON.stringify(extractedInfo)}); - first attepmt
    console.log( extractedInfo );

    //POST to PHP
    request = new XMLHttpRequest();
    request.open( "POST", "summary.php", true );
    request.setRequestHeader( "Content-type", "application/json" );
    request.send( JSON.stringify( extractedInfo ) );
}

document.getElementById("dataForm").addEventListener("submit", e => {
    e.preventDefault();
    parseData();
});

Upvotes: 0

Related Questions