I have a form that creats a json array from user input data.

Array
(
    [full_name] => First Name + Last Name
    [company_name] => Company Name
    [email] => Email
    [free_trial] => trial (Yes/No)
    [quota] => quota 
    [contract] => 0 (0/1)
    [per_gb] => cost per gb
    [per_month] => contract length in months
    [wanaccel] => No (Yes/No)
)

I need to send that to a php curl file so that it can be sent to an ip address.

How do I populate the curl data array from that json file?

Here is where I am starting with the curl page.

<?php

$url = '#';

$data = array(
    'full_name'    => $_POST["full_name"],
      'company_name' => $_POST["company_name"],
      'email'        => $_POST["email"],
      'free_trial'   => $_POST["free_trial"],
      'contract'        => $_POST["contract"],
      'wanaccel'     => 'No',
      'per_month'     => $_POST["per_month"],

);

    $data_string = json_encode($data);
    $post = curl_init('localhost');
    curl_setopt($post, CURLOPT_VERBOSE, true);
    curl_setopt($post, CURLOPT_POST, count($data));
    curl_setopt($post, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($post, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($post, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($post, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);
    $result = curl_exec($post);
    curl_close($post);
        echo "here is the result".$result." |\n";
        echo ( $result );
print_r($data);

?>

Any thoughts?
Thanks so much!

I have a form that creats a json array from user input data.
I need to send that to a php curl file so that it can be sent to an ip address.
How do I populate the curl data array from that json file?

Hello,

if remote expects json data, as it seems from the header set in the curl request, then just submit the json string as you are already doing. Use curl_error() if it seems that does not work:

You should also change this:

curl_setopt($post, CURLOPT_POST, count($data));

To:

curl_setopt($post, CURLOPT_POST, TRUE);

It should not make much difference as probably PHP will cast the integer to TRUE and curl, once CURLOPT_POSTFIELDS are set, will send a POST request anyway.

Here's an example through a test API:

<?php

$data = ['msg' => 'hello', 'token' => mt_rand(1000, 9999)];
$data_string = json_encode($data);

$post = curl_init('http://jsonplaceholder.typicode.com/posts/');

curl_setopt($post, CURLOPT_VERBOSE, TRUE);
curl_setopt($post, CURLOPT_POST, FALSE);
curl_setopt($post, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($post, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($post, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

$result = curl_exec($post);

curl_close($post);

echo "RESULT:" . PHP_EOL . $result . PHP_EOL;

Thanks for the response.
Maybe I should break down my situation a little further.

I have a form that on submit the data goes to a js file that creates a json object string.
In that js file I have it passing the string to a curl file.

Here is the js file

(function( $ ) {
    "use strict";

    var _handler = 'curl.php';

    $( document ).ready( function() {
        var $form         = $( '#mainPanel' ),
            $first_name   = $form.find( '[data-itemid="1"]' ),
            $last_name    = $form.find( '[data-itemid="2"]' ),
            $company_name = $form.find( '[data-itemid="4"]' ),
            $email        = $form.find( '[data-itemid="6"]' ),
            $free_trial   = $form.find( '[data-itemid="10"]' ),
            $contract     = $form.find( '[data-itemid="11"]' ),
            $per_gb       = $form.find( '[data-itemid="24"]' ),
            $per_month    = $form.find( '[data-itemid="15"]' ),
            $quota        = $form.find( '[data-itemid="17"]' ),
            $quota_monthly = $form.find( '[data-itemid="16"]' ),
            $submit       = $( '#wpe_btnOrder' );

        $submit.on( 'click', function( _event ) {
            var _monthly = $per_month.val().toLowerCase() == 'month-to-month (no contract)"',
                _data = {
                'full_name':    $first_name.val() + ' ' + $last_name.val(),
                'company_name': $company_name.val(),
                'email':        $email.val(),
                'free_trial':   $free_trial.val(),
                'quota':        _monthly ? $quota_monthly.val() : $quota.val(),
                'contract':     $contract.val().toLowerCase() == 'yes' && !_monthly ? 1 : 0,
                'per_gb':       $per_gb.val(),
                'per_month':    _monthly ? 1 : 12 * parseInt( $per_month.val().replace( ' Year', '' ) ),
                'wanaccel':     'No'
            };
            _event.preventDefault();

            setTimeout( function() {
                if( $form.find( '.has-error' ).length == 0 ) {
                    $.post(
                        _handler,
                        JSON.stringify( _data )
                    );
                    console.log( _data );
                }
            }, 50 );
        } );

    } );
})( jQuery );

Would I still setup the php file like you posted above?

Member Avatar for diafol

Could I suggest that you don't use $ prefix for general variables in js / jQ. It's confusing issues you may have.

Okay, maybe you want to do this inside your javascript:

var data = {'data' : JSON.stringify( _data )};
...
$.post(
      _handler,
      data
  );

Like this in the PHP side you can write:

$data = json_decode($_POST['data'], TRUE);

Sanitize and encode again and finally send the request through curl.

OK, I think the best way to go would be to just use php to get the form data and send as this is getting out of my league.

How would I pull data from the form and put that data into the correct array value?
Does something like this make sense?

  $data = array(
      'full_name'    => $entry['2.3'].' '.$entry['2.6'],
      'company_name' => $entry['5'],
      'email'        => $entry['3'],
      'free_trial'   => $entry['8'], // should be 'Yes' or 'No'
      'quota'        => $size,
      'contract'       => $entry['11'],
      'per_gb'       => $entry['32.2'],
      'per_month'    => $entry['35'],
      'wanaccel'     => (strlen($entry['9.1']) > 0) ? 'Yes' : 'No',
    );

If 2.3 in $entry['2.3'] represents the index key sent by the POST request, and so it is the name of an input field:

<input type="text" name="2.3">

then PHP will translate the dots into underscores, so you can match it by doing $_POST['2_3']. But I'm a bit lost, I am not following your issue. Maybe the AJAX does not send data? Do you see anything in the console log?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.