returning useful json encoded message from editor - without throwing an error

returning useful json encoded message from editor - without throwing an error

crush123crush123 Posts: 417Questions: 126Answers: 18
edited October 2015 in Editor

I have an editor instance for registering contact emails.
In my ajax page, i have a conditional php block which will run if a certain field value is met, and this block will call a function subscribing the contact details to my mailchimp list.

This works ok, but I need to trap any errors which may occur.

If i tried echoing the output variable to my ajax result but this throws an error.

here is a snippet to try and explain...

if ( ! isset( $data['fieldErrors'] ) && isset($_POST['action']) && $_POST['action'] === 'create' ) {
$active = $_POST['data']['contacts']['Active'];
$email = $_POST['data']['contacts']['EmailAddress1'];
$firstname = $_POST['data']['contacts']['FirstName'];
$lastname = $_POST['data']['contacts']['LastName'];
$contactid = ltrim($data['row']['DT_RowId'],'row_');//newly created ID
  if ($active == 1) {
     include_once ("../mailchimp-api/mailchimp_subscribe.php");
     $subscriberesult = subscribe($api_key, $list_id, $email, $firstname, $lastname, $contactid);
 }


echo json_encode( $data );
echo json_encode( $subscriberesult );

}

I guess i just want to call the $subscriberesult from my main page, maybe using editor.on( 'close', function (), but i am not clear on how to do that

Grateful for any advice on how i can output my $subscriberesult response.

This question has accepted answers - jump to:

Answers

  • allanallan Posts: 61,439Questions: 1Answers: 10,053 Site admin

    Two json_encode()'s is not going to give you valid JSON - it would give you something like:

    {
      ...
    }
    {
      ...
    }
    

    which of course is not valid.

    Perhaps you might want to consider doing:

    $data['subscripeResult'] = $subscriberesult;
    echo json_encode( $data );
    

    That would at least give you valid JSON, but I'm not sure if that is what was causing the error you were seeing as you don't actually say what the error is.

    Allan

  • crush123crush123 Posts: 417Questions: 126Answers: 18
    edited October 2015

    Thanks for the reply Allan,

    I think I am making some progress, my code is now

    if ( ! isset( $data['fieldErrors'] ) && isset($_POST['action']) && $_POST['action'] === 'edit' ) {
    //when in edit and there are no errors, check the value of the 'Active' field
    // if active is true, we want to subscribe the contact to the mailchimp list via the api, updating existing where applicable
    $active = $_POST['data']['contacts']['Active'];
    $email = $_POST['data']['contacts']['EmailAddress1'];
    $firstname = $_POST['data']['contacts']['FirstName'];
    $lastname = $_POST['data']['contacts']['LastName'];
    $contactid = ltrim($data['row']['DT_RowId'],'row_');
     if ($active == 1) {
         include_once ("../mailchimp-api/mailchimp_subscribe.php");
         $data['subscriberesult'] = subscribe($api_key, $list_id, $email, $firstname, $lastname, $contactid);
     }
    

    }

    which parses correctly

    On my main page, i am just trying to return the result to the console for now, but the json returned is undefined, - if i check the network preview, the subscriberesult object is not there - can you help me with the syntax to return the subscriberesult object ?

    editor.on( 'close', function () {//redraws the table after edit window is closed 
      table
        .ajax.reload( null, false ) // user paging is not reset on reload
        $.getJSON('/ajax/contacts.php', function(data) {    
        console.log(data.subscriberesult);
        });
      } );
    
  • crush123crush123 Posts: 417Questions: 126Answers: 18

    I am guessing that because I have already run data->post, to get the values to pass into my php condition, then $data.subscriberesult is not in the json ?

  • allanallan Posts: 61,439Questions: 1Answers: 10,053 Site admin

    I'm not quite understanding that code - you appear to have:

    1. Editor submits (which itself makes an Ajax request)
    2. You then call ajax.reload() to reload the DataTable
    3. At the same time you make the $.getJSON call

    So you have three Ajax requests - that doesn't sounds like too great a solution to my mind. You should really only need one - the Editor submission. That should contain the data for the DataTable update and also contain any additional payload required.

    Without seeing the full PHP I'd just be guessing though.

    Allan

  • crush123crush123 Posts: 417Questions: 126Answers: 18
    edited November 2015

    There is only one ajax request, - which was created through editor.
    To that, i appended some php to use the posted values from the editor instance.

    here is the ajax page, (shortened as it is too long to post) and I will try and upload it to my testing server later

    the relevant code block is at the bottom, beginning with ...if ( ! isset( $data['fieldErrors'] )...

    <?php
    
    // DataTables PHP library
    include( "../DataTables-1.10.5/extensions/Editor-PHP-1.4.2/php/DataTables.php" );
    
    // Alias Editor classes so they are easy to use
    use
    DataTables\Editor,
    DataTables\Editor\Field,
    DataTables\Editor\Format,
    DataTables\Editor\Join,
    DataTables\Editor\Upload,
    DataTables\Editor\Validate;
    
    // Build our Editor instance and process the data coming from _POST
      $editor = Editor::inst( $db, 'contacts', 'ContactID' );//table name and PKey(defaults to ID)
    
            ...
    
      $editor->field(
            ...
    )
    ->leftJoin('companies','companies.CompanyID', '=','contacts.CompanyID')
    ->leftJoin('members','members.ContactID', '=','contacts.ContactID')
    ->leftJoin('members AS members_1','members_1.CompanyID', '=','companies.CompanyID');
    
    $data = $editor
    ->process( $_POST )
    ->data();
    
    
    if ( ! isset( $data['fieldErrors'] ) && isset($_POST['action']) && $_POST['action'] === 'edit' ) {
    //when in edit and there are no errors, check the value of the 'Active' field
    // if active is true, we want to subscribe the contact to the mailchimp list via the api, updating existing where applicable
    $active = $_POST['data']['contacts']['Active'];
    $email = $_POST['data']['contacts']['EmailAddress1'];
    $email2 = $_POST['data']['contacts']['EmailAddress2'];
    $firstname = $_POST['data']['contacts']['FirstName'];
    $lastname = $_POST['data']['contacts']['LastName'];
    $contactid = ltrim($data['row']['DT_RowId'],'row_');
     if ($active == 1) {
         include_once ("../mailchimp-api/mailchimp_subscribe.php");
         $data['subscriberesult'] = subscribe($api_key, $list_id, $email, $firstname, $lastname, $contactid);
     }
    }
    
    
    echo json_encode( $data );
    ?>
    
  • allanallan Posts: 61,439Questions: 1Answers: 10,053 Site admin

    I'm afraid I don't understand how there can be only one request when your code shows that there is the Editor request, ajax.reload() and then $.getJSON(). That looks like three individual Ajax requests unless I'm misunderstanding?

    However, as I say, I am somewhat guessing without being able to see the full page, so I'm not 100% use of what is happening.

    Allan

  • crush123crush123 Posts: 417Questions: 126Answers: 18

    ..I see

    I'm obviously going about this all wrong. - though from your explanation, it looks like the main problem is my attempt to do the extra stuff with the editor on close function.

    I have the editor instance for data insert/update working fine.

    At this point, i was doing the ajax.reload on editor close, as it was the only way i could work out how to redraw the table to apply the conditional class...

    createdRow: function ( row, data, index ) {
            if ( data.members.Complimentary == '1' || data.members_1.Complimentary == '1') {
                $('td', row).addClass('lightgreen');
            }
        },
    

    As i am updating the mailchimp function if (and only if) the active bool is set to true, I wanted to retrieve the result of that function when it ran, hence the next call.

    I can't submit the full code page as it is too many characters.

    I will try and get around to uploading the pages and sending a link

  • allanallan Posts: 61,439Questions: 1Answers: 10,053 Site admin

    At this point, i was doing the ajax.reload on editor close, as it was the only way i could work out how to redraw the table to apply the conditional class...

    Okay - I can see why you might want to do that. However, I would suggest that you use rowCallback rather than createdRow if the data might be updated and the class needs to change. That will avoid the need to reload the entire table.

    Allan

  • crush123crush123 Posts: 417Questions: 126Answers: 18
    edited November 2015

    Thanks Allan,

    i have now edited the row callback to do this, and I now save one of the ajax calls

    I think I was trying to do everything in one go, so here is my new approach.

    for an edit,i have looked at using modifier() to retrieve the data from the row currently being edited.
    I am presuming that if there any errors (validation etc) that these will be triggered before the editor.on close is fired. Then i use the row data with a new ajax page

    editor.on( 'edit', function ( e, type ) {
    var modifier = editor.modifier();
    
    if ( modifier ) {
        var data = table.row( modifier ).data();
        var active = data.contacts.Active;
        var email = data.contacts.EmailAddress1;
        var firstname = data.contacts.FirstName;
        var lastname = data.contacts.LastName;
        var contactid = data.contacts.ContactID;
        if (active == 1) {
            //alert(firstname+' '+lastname);
            $.ajax ({
            url: '/ajax/ajax_mailchimp_subscribe.php',
            data: {
                Email: email,
                FirstName: firstname,
                LastName: lastname,
                ContactID: contactid                
                },
            method :'POST',
                //dataType: 'json',
                //http://learn.jquery.com/ajax/jquery-ajax-methods/
                 success: function(data) {
                     alert(data)
                  },
                  error: function(e) {
                      console.log('Error!', e);
                  }
            } );    
        }
    }
    

    Looking promising so far, so I think this will work for rows being edited, but can you advise what i can do for create ?

  • allanallan Posts: 61,439Questions: 1Answers: 10,053 Site admin
    Answer ✓

    Fantastic - thanks for the link.

    Use:

    editor.on( 'submitSuccess', function ( e, json, data ) {
      console.log( json.subscriberesult );
    } );
    

    You already have the property in the JSON returned from the edit, so there is no need for another Ajax request to get it - just access the JSON returned using submitSuccess.

    Allan

  • crush123crush123 Posts: 417Questions: 126Answers: 18
    edited November 2015

    Thanks Allan.

    I no longer need subscriberesult, i am just using the data from the editor to process the mailchimp subscription.

    It's working well, and I am happy with it.

    Only one further question.

    At the moment, on submitSuccess, the code to update the subscription is fired if the active field is true. which is fine, but if i am editing a name or other field, i only want to fire the subscription code if active is true AND it has been changed, (ie it was false before the edit)

    is there an easy way to do that ?

    editor.on( 'submitSuccess', function ( e, json, data ) {
        var active = data.contacts.Active;
        var email = data.contacts.EmailAddress1;
        var email2 = data.contacts.EmailAddress2;
        var firstname = data.contacts.FirstName;
        var lastname = data.contacts.LastName;
        var contactid = data.DT_RowId.substring(4);
        if (active == 1) {
            //alert(firstname+' '+lastname);
            $.ajax ({
            url: '/ajax/ajax_mailchimp_subscribe.php',
            data: {
                Email: email,
                Email2: email2,
                FirstName: firstname,
                LastName: lastname,
                ContactID: contactid                
                },
            method :'POST',
                dataType: 'json',               
                 success: function(mcdata) {
                     //console.log('Success!', mcdata);
                     $('.modal-title').html('Mailchimp Status Update for '+firstname+' '+lastname);
                     arrayKey1Exists = 'email1' in mcdata;
                     arrayKey2Exists = 'email2' in mcdata;
                     if (arrayKey1Exists == true) {//mailchimp will return 'email1' as part of the array if successful
                     //alert(mcdata);(//shows object if dataType is json, comment out dataType to show string
                        $('.modal-body').html(mcdata.email1.email+' has been successfully subscribed on Mailchimp');
                     } 
                     if (arrayKey2Exists == true) {//mailchimp will return 'email2' as part of the array if successful
                     //alert(mcdata);(//shows object if dataType is json, comment out dataType to show string
                        $('.modal-body').append('<br>'+mcdata.email2.email+' has been successfully subscribed on Mailchimp');
                     }
                     if (arrayKey1Exists == false && arrayKey2Exists == false) {
                        $('.modal-body').html('Unfortunately, the mailchimp update has failed<br>Error Code:'+mcdata.code+'<br>Error Message:'+mcdata.name);
                     }
                     $('#mcresultModal').modal('show');
                  },
                  error: function(e) {
                      console.log('Error!', e);
                  }
            } );    
        }
    

    } );

  • allanallan Posts: 61,439Questions: 1Answers: 10,053 Site admin
    Answer ✓

    AND it has been changed

    You could use the form-options's submit option to submit only changed values. Otherwise you would need to query the database to see if the value has changed or not.

    Allan

This discussion has been closed.