-1

Hi Everyone I have the following due to some situation on one of my projects. I'm working with angular-xeditable, it has a method onbefore save which should returns a string in case I want the from to maintain opened(editable) and true in case I want to form to be closed(not editable).

Now the problem, below you will find my code for one angular function

self.validateBeforeSave = function(data, id){
          var current_id = id;
          $http.post('data/functions.php', {
                action : 'updateQuotasDisease',
                sqlPeriod : data.period,
                sqlDiseaseCode : data.disease_code,
                sqlTargetCountry : data.target_country,
                sqlTargetSpecialty : data.target_specialty,
                sqlChartsAmount : data.charts_amount,
                sqlAmount : data.amount,
                sqlStatus : data.status
              })
              .success(function(response) {
                if(response == 'quota-exists'){
                  $("#"+current_id).css("background-color", "#ffc4c4");
                  swal("That quota already exists!", "", "error");
                  return "error-msg";
                }
                else{
                  $("#"+current_id).css("background-color", "#ffffff");
                  return true;
                }
              })
              .error(function(response) {
                console.log('Error: ' + response);
            });


        };

This code is being called from this HTML, but basically what matters is the need of a return from previous functions of true or "string", you can find onbeforesave="$ctrl.validateBeforeSave($data, line.id)" from there I'm calling the previous function.

<table class="table general-tables table-responsive" ng-show="$ctrl.VisibleQuotasDisease">
                <thead>
                    <tr>
                        <th>Actions</th>
                        <th>Period</th>
                        <th>Disease code</th>
                        <th>Target country</th>
                        <th>Target specialty</th>
                        <th>Charts amount</th>
                        <th>Amount</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="line in $ctrl.quotasDisease" id="{{line.id}}">
                        <td style="white-space: nowrap">
                            <!-- onaftersave="$ctrl.saveRowDisease($data, line.id, line) validateBeforeSave"  -->
                            <form editable-form name="rowform" onbeforesave="$ctrl.validateBeforeSave($data, line.id)" ng-show="rowform.$visible" class="form-buttons form-inline" shown="inserted == line">
                                <button type="submit" ng-disabled="rowform.$waiting" class="btn btn-xs btn-primary">
                                    <i class="fa fa-2x fa-save"></i>
                                </button>
                                <button type="button" ng-disabled="rowform.$waiting" ng-click="rowform.$cancel()" class="btn btn-xs btn-default">
                                    <i class="fa fa-2x fa-close"></i>
                                </button>
                            </form>
                            <div class="buttons" ng-show="!rowform.$visible">
                                <button class="btn btn-xs btn-warning" ng-click="rowform.$show()">
                                    <i class="fa fa-2x fa-edit"></i>
                                </button>
                                <button class="btn btn-xs btn-danger" ng-click="$ctrl.removeRowDisease($index, line)">
                                    <i class="fa fa-2x fa-trash-o"></i>
                                </button>
                            </div>  
                        </td>
                        <td>
                            <span editable-text="line.period" e-class="period-inputs" e-name="period" e-form="rowform" e-maxlength="7" e-required>
                                {{line.period}}
                            </span>
                        </td>
                        <td>
                            <span editable-text="line.disease_code" e-name="disease_code" e-form="rowform" e-maxlength="2" e-required>
                                {{line.disease_code}}
                            </span>
                        </td>
                        <td>
                            <span editable-text="line.target_country" e-name="target_country" e-form="rowform" e-maxlength="2" e-required>
                                {{line.target_country}}
                            </span>
                        </td>
                        <td>
                            <span editable-text="line.target_specialty" e-name="target_specialty" e-form="rowform" e-maxlength="4" e-required>
                                {{line.target_specialty}}
                            </span>    
                        </td>
                        <td>
                            <span editable-text="line.charts_amount" e-name="charts_amount" e-form="rowform"  e-onkeypress="return onlyInt(event)" e-required>
                                {{line.charts_amount}}
                            </span>
                        </td>
                        <td>
                            <span editable-text="line.amount" e-name="amount" e-form="rowform"  e-onkeypress="return onlyInt(event)" e-required>
                                {{line.amount}}
                            </span>
                        </td>
                        <td>
                            <span editable-text="line.status" e-name="status" e-form="rowform"  e-onkeypress="return onlyInt(event)" e-required>
                                {{line.status}}
                            </span>
                        </td>
                    </tr>
                </tbody>
            </table>

Finnaly I want to do the question how can I do a return from inside the success section of $http post or how can I workaround to solve this situation.

Thanks in advance.

Just as another piece of code here the php function that I'm calling

if($request -> action == 'updateQuotasDisease'){
        $period_sql = $request -> sqlPeriod; 
        $disease_code_sql = $request -> sqlDiseaseCode;
        $target_country_sql = $request -> sqlTargetCountry; 
        $target_specialty_sql = $request -> sqlTargetSpecialty;
        $charts_amount_sql = $request -> sqlChartsAmount; 
        $amount_sql = $request -> sqlAmount;
        $status_sql = $request -> sqlStatus;

        $existing_record = connDB() -> getOne("SELECT count(*) FROM quota_period WHERE period_field = '$period_sql' AND disease_code_numeric = '$disease_code_sql' AND targeted_country = '$target_country_sql' AND targeted_specialty_numeric_code = '$target_specialty_sql' AND amount = $amount_sql AND patient_cases_amount = $charts_amount_sql AND status = $status_sql;");
        if($existing_record < 1){
            connDB() -> query("UPDATE quota_period SET period_field = '$period_sql', disease_code_numeric = '$disease_code_sql', targeted_country = '$target_country_sql', targeted_specialty_numeric_code = '$target_specialty_sql', patient_cases_amount = $charts_amount_sql, amount = $amount_sql, status = $status_sql WHERE period_field = '$period_sql' AND disease_code_numeric = '$disease_code_sql' AND targeted_country = '$target_country_sql' AND targeted_specialty_numeric_code = '$target_specialty_sql';");
        }
        else{
            echo "quota-exists";
        }
    }

1 Answers1

-2

First of all, your return is returning only to success call/caller. It can't be caught outside from success.

The second thought is from the ajax call. http post from angular was written to be always asynchronous. So, your function will never wait for the ajax request be completed.

But you can use the $q module to make the function will "wait" and receive the result to return it.

It's something like this:

function() {
    var deferred = $q.defer();

    $http.post('data/functions.php', arguments);
    .success(function(response) {
        //your code

        //resolve the promise
        deferred.resolve('request successful');
    })
    .error(function(data,status,headers,config){
        //reject the promise
        deferred.reject('ERROR');
    });

    return deferred.promise;
}

You only may to ensured the result which you want from deferred.promise (which I don't know that).

You can see a bit more in these links above:

To then() or to success() in AngularJS

How to $http Synchronous call with AngularJS

how to make synchronous http request in angular js

Community
  • 1
  • 1
Gabriel Heming
  • 1,100
  • 10
  • 30
  • Doesn't $http.post return a promise? If it does, why would you need $q? – Kevin B Mar 13 '17 at 20:10
  • @KevinB you're right. But I think you don't get the point. The `$q` module is used to ensure the wait of request completion. How could you reference a promise created by $http inside the $http. Do you got it? – Gabriel Heming Mar 13 '17 at 20:19
  • Why would you need to access it inside the $http? You simply `.then(() => 'request successful')` to replicate what you did. (and a second callback to handle error, etc) – Kevin B Mar 13 '17 at 20:34
  • Well, I'm not a specialist in angular. I've just read, tried and tested. That's worked. So, why couldn't you answer that before? Or a high reputation doesn't allow to answer or just allow to be senseless? – Gabriel Heming Mar 13 '17 at 20:38
  • I find answering duplicates to be a waste of (my) time, so i dupe closed instead. – Kevin B Mar 13 '17 at 20:40
  • 1
    See [Why are angular $http success/error methods deprecated? Removed from v1.6?](http://stackoverflow.com/questions/35329384/why-are-angular-http-success-error-methods-deprecated-removed-from-v1-6/) – georgeawg Mar 13 '17 at 21:47
  • 1
    See [Is this a “Deferred Antipattern”?](http://stackoverflow.com/questions/30750207/is-this-a-deferred-antipattern). – georgeawg Mar 13 '17 at 21:50
  • 1
    See [Avoid the $q Deferred Anti-Pattern](http://stackoverflow.com/documentation/angularjs/4379/angular-promises-with-q-service/26209/avoid-the-q-deferred-anti-pattern#t=201703132151056398723). – georgeawg Mar 13 '17 at 21:52
  • @GabrielHeming Thanks for your answer it worked!! Sorry if I created a duplicate question I'm not really clear on $q service so a question directly to my scenario clarified a lot to me. – Mati Pereyra Mar 14 '17 at 13:31
  • @MatiPereyra Now I'm concerned about the problems, thanks to georgeawg. Try out what he's referring. – Gabriel Heming Mar 14 '17 at 13:44