0

I am trying to enter data from a form into a database. The form works fine, but when I try to use Ajax to transfer the data to a php script for database insertion, the JSON is not sent. If I directly insert a var containing the JSON in the php script, it is successful. So I know the JSON is properly formatted. The jquery in the form is

    $("#up").click (function(e){
        e.preventDefault()
        theurl="ajaxPHPup.php";
        var formdata = JSON.stringify($("#theForm").serializeArray());
        console.log(formdata);
        $.ajax({
             type: "POST",
             url: theurl,
             data: formdata,

             dataType: "html",
             contentType : "application/json; charset=utf-8",
             success: function(data){
               $('#feedback').html(data);
                   console.log('submitted data:');
                   console.log(data);
             }
        });

    });

The php script is

<?php
session_start();
error_reporting (E-ALL);
require_once('dbaccess.php');
$getLayout = $fm->getLayout('ajaxtest');
$getFields = $getLayout->listFields();

$formdata = $_POST['formdata'];
//$formdata = '[{"name":"one","value":"11"},{"name":"two","value":"22"},{"name":"three","value":"33"},{"name":"four","value":"44"},{"name":"five","value":"55"}]';
$formdecode = json_decode($formdata, true);
$getdbData = $fm->newFindAllCommand('ajaxtest');
$gotdbData = $getdbData->execute();
if(FileMaker::isError($gotdbData)){
    echo 'ERROR - ' . $gotdbData->getCode() . ' ' . $gotdbData->getMessage();
    exit;
}

$record = $gotdbData->getFirstRecord();
$recID = $record->getRecordID();
//echo 'record id = ' . $recID . '<br>';

$feedback = '';
$change = $fm->newEditCommand('ajaxtest',$recID);
foreach($formdecode as $index){
    $change->setField($index['name'], $index['value']);
    $feedback .=$index['name'] . ' => ' . $index['value'] . '<br>';
}
$change->execute();
if(FileMaker::isError($change)){
    echo 'ERROR - ' . $change->getCode() . ' ' . $change->getMessage();
    exit;
}
echo $feedback;
?>

The feedback returned by the success routine is an empty string. It would appear that the problem is in the function call, but I have been unable to determine what exactly it is.

Doug Hemingway
  • 55
  • 1
  • 2
  • 8
  • I think your $_POST is empty, because php doesn't handle JSON requests like that, take a look here: https://www.geeksforgeeks.org/how-to-receive-json-post-with-php/ – i.brod Mar 26 '20 at 15:52
  • If you want to have `$_POST['formdata']` defined, you need to have that index in the object which you sent via the request. That is, you will have to send it this way: `data: { formdata }` - this will create a property in the object, and an index in the `$_POST` array, both named `formdata`. – Romi Halasz Mar 26 '20 at 16:01

0 Answers0