function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Steve CairneySteve Cairney 

Javascript button giving the wrong alert.

Hi, I have a very simple button that sends infomation to a webservice.

What I'm trying to do is have an if / else statement that will display an alert with whether the submission was a success or failure.

The code is really quite simple, but it's displaying the wrong alert on a record that I know is a success and a record that I know fails.

Here's the code (note the first alert is just so I can see the inital response from the webservice

If it's a Success, it will return 

User-added image

If it fails, it will return

User-added image
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/29.0/apex.js")}

var json = sforce.apex.execute("ItsApprovedWebServices","GetBookingDetails",{id:"{!ItsApproved_Booking__c.Id}"});

var authorizationToken = sforce.apex.execute("ItsApprovedWebServices","Login",{userName: 'xxxx'});

var result = sforce.apex.execute("ItsApprovedWebServices","PostBooking",{json: json, authorizationToken: authorizationToken});

alert(result); //if correct returns "Success", if incorrect, returns a long error message

if (result == "Success") {
alert("OK, Booking sent to ItsApproved - http:www.google.com");
}
else { 
alert("Error! Call Cestrian and quote '{!ItsApproved_Booking__c.Name}'");
}
I'm getting the second alert for both scenarios.

What could be wrong in the code?
 
Best Answer chosen by Steve Cairney
Naval Sharma4Naval Sharma4

Hi Steve,

Based on your first post on this question, I think it's returning an array.

So you need to check like this.
if(result[0].indexOf("Success") != -1)
   alert('success'); 
else 
   alert('fail');


 

All Answers

Agus AndrésAgus Andrés
Hi,

I think the problem is in your comparison (result == "Success"), first of all are you sure result is a string? Try to do this

if(string(result) === "Success"")...
Steve CairneySteve Cairney
Hmm, In order to do that wouldn't I need to declare a string var somewhere?
Steve CairneySteve Cairney
Also, yes, I'm sure that the json returns a string
Balu_SFDCBalu_SFDC
Hi ,

Is your Method returing the string value as "Success"?  i think in your case the method is retunring different value.please share your Class.

here is my code.

{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/29.0/apex.js")} 

var result = ""+sforce.apex.execute( "MyWSClass", "WSMethod", {param:"{!Account.Id}"}); 
if (result == 'Success') { 
    alert("Success............"); 
 //your logic

else { 
    alert("Error!..........."); 
}
========================
Webservice:

global class MyWSClass{

    Webservice static string WSMethod(string prm) {
        if(prm != null) {
            try {
                //your logic here
                return 'Success';
            }
            catch(Exception e){
                return 'Error';
            }
        }
        else {
            return 'Error';
        }
    }
}
 
Steve CairneySteve Cairney
Here's the class
 
global with sharing class ItsApprovedWebServices {

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Description : Web Service to login to ItsApproved
    // Called From : "Test Submit Booking" botton on ItsApproved Booking Page
    // Returns     : Authorization Token (for use in subsequent web service calls to Its Approved)
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    webservice static String Login(String userName) {
      HttpRequest req = new HttpRequest();
      HttpResponse res = new HttpResponse();
      Http http = new Http();

      req.setEndpoint('http://removed');
      req.setMethod('GET');
      req.setTimeout(60000);
      //req.setHeader('Content-Type','application/json');
      //req.setBody('username'+EncodingUtil.urlEncode(userName, 'UTF-8'));
      //req.setBody(username);

  //    try {
          res = http.send(req);
                    
  //    } catch(System.CalloutException e) {
   //       System.debug('Callout error: '+ e);
   //       System.debug(res.toString());
   //   }
   
      return res.getHeader('Authorization-Token');
    }
    
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Description : Web Service to create representation of Booking in JSON format
    // Called From : "Test Submit Booking" botton on ItsApproved Booking Page
    // Returns     : Complete Booking as a JSON object
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    webservice static String GetBookingDetails(ID id) {
    JSONGenerator jsonGenerator = JSON.createGenerator(true);
          
      ItsApproved_Booking__c booking = [SELECT Id, Booking_Title__c, Customer_Reference__c, Incharge_Date__c FROM ItsApproved_Booking__c WHERE Id = :id];
    
      jsonGenerator.writeStartObject(); // Booking
      jsonGenerator.writeStringField('CompanyId', '798365d8-4278-4b16-a330-c4a3a9e1f91f');
      jsonGenerator.writeNumberField('UserId', 84);

      jsonGenerator.writeStringField('BookingTitle', booking.Booking_Title__c);
      jsonGenerator.writeStringField('CustomerReference', booking.Customer_Reference__c);
      jsonGenerator.writeStringField('CustomerBookingId', booking.Id);
      jsonGenerator.writeDateTimeField('InchargeDate', booking.Incharge_Date__c);
      
      List<ItsApproved_Product__c> products = [SELECT Id, IAProduct__c, Booking_Reference__c FROM ItsApproved_Product__c WHERE Booking_Reference__c = :Id];

      jsonGenerator.writeFieldName('Products');
      jsonGenerator.writeStartArray(); // Products
      for(ItsApproved_Product__c p: products)
      {
        List<IA_Product__c> IAProducts = [SELECT Id, Code__c FROM IA_Product__c WHERE Id = :p.IAProduct__c];

        jsonGenerator.writeStartObject(); // Products
        jsonGenerator.writeStringField('ProductionCode', IAProducts[0].Code__c);           
        jsonGenerator.writeStringField('CustomerProductReference', IAProducts[0].Code__c);           

        List<ItsApproved_Design__c> designs = [SELECT Id, Artwork_Title__c FROM ItsApproved_Design__c WHERE Product_Reference__c = :p.Id];

        jsonGenerator.writeFieldName('Designs');
        jsonGenerator.writeStartArray(); // Designs
        for(ItsApproved_Design__c d: designs)
        {
          jsonGenerator.writeStartObject();
          jsonGenerator.writeStringField('CustomerDesignId', d.Id);           
          jsonGenerator.writeStringField('DesignName', d.Artwork_Title__c);           

          List<ItsApproved_Delivery__c> deliveries = [SELECT Id, IADepot__c, Quantity__c FROM ItsApproved_Delivery__c WHERE ItsApproved_Design__c = :d.Id];

          jsonGenerator.writeFieldName('Deliveries');
          jsonGenerator.writeStartArray(); // Deliveries
          for(ItsApproved_Delivery__c del: deliveries)
          {
            List<IADepot__c> IADepots = [SELECT Id, Depot_Code__c FROM IADepot__c WHERE Id = :del.IADepot__c];

            jsonGenerator.writeStartObject(); // Deliveries
            jsonGenerator.writeStringField('DeliveryId', del.Id);           
            jsonGenerator.writeStringField('DepotCode', IADepots[0].Depot_Code__c);
            jsonGenerator.writeNumberField('Quantity', del.Quantity__c);
            jsonGenerator.writeEndObject(); // Deliveries
          }
          jsonGenerator.writeEndArray();  // Deliveries

          jsonGenerator.writeEndObject(); // Designs
        }
        jsonGenerator.writeEndArray(); // Designs

        jsonGenerator.writeEndObject(); // Products
      }
      jsonGenerator.writeEndArray(); // Products

      jsonGenerator.writeEndObject(); // Booking
        
      return jsonGenerator.getAsString();        
    }
    
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Description : Web Service to send complete Booking Details to Its Approved
    // Called From : "Test Submit Booking" botton on ItsApproved Booking Page
    // Returns     : 
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    webservice static String PostBooking(String json, String authorizationToken)
    {   
      // Now send the data to Its Approved
      HttpRequest req = new HttpRequest();
      HttpResponse res = new HttpResponse();
      Http http = new Http();

      req.setEndpoint('http://removed');
      req.setMethod('POST');
      req.setHeader('Content-Type','application/json');
      req.setHeader('Authorization-Token', authorizationToken);
      req.setBody(json);
      req.setTimeout(60000);

  //    try {
          res = http.send(req);
                    
  //    } catch(System.CalloutException e) {
   //       System.debug('Callout error: '+ e);
   //       System.debug(res.toString());
   //   }
      
      //return res.toString();  
      return res.getBody(); 
    }
}

 
Agus AndrésAgus Andrés
Then you will need to provide an onSuccess and onFailure callback method, something like:

sforce.apex.execute("ItsApprovedWebServices","Login",{userName:'xxxx'}, {onSuccess: function(result){//alert success}},{onFailure: function(error){//alert error}});
Agus AndrésAgus Andrés
Also, you should change the name of your var result or you could have troubles inside the onSuccess callback
Balu_SFDCBalu_SFDC
Hi Stave,

i you abserved the method "PostBooking" is returing res.getBody();....
webservice static String PostBooking(String json, String authorizationToken){
-----------------
---------------
res.getBody();// means the condiation in script is always false
}
So try to return Success /Error string like below
res.getStatus()
 
Balu_SFDCBalu_SFDC
Or try below Method
if(res.getstatuscode() ==200){
return 'Success';
}
else
{
return 'Error';
}
See below link for more details.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_restresponse.htm%23apex_System_RestResponse_methods

 
Steve CairneySteve Cairney
I think the problem here is that the class will return a 200 OK regardless.

How can I test this with string length?

For example, we know that if there is an error it will return a long string. We tried this but couldn't get the right results.
Steve CairneySteve Cairney
I've just edited my original code to this (to see if length will work)
 
if (result.length < 20) {
alert("OK, Booking sent to ItsApproved - http:www.google.com");
}
else { 
alert("Error! Call Cestrian and quote '{!ItsApproved_Booking__c.Name}'");
}

And now the records are returning the first alert, not the second one!
Balu_SFDCBalu_SFDC
Steve,

res.getBoday() method will return more repsopnse(string length).so 1st is always true..
in which condition you want to make success? login is sueecess you want get success page right?
try my code and see it will work..

webservice static String PostBooking(String json, String authorizationToken){
-----------------
------------your code---
res.getBody();// means the condiation in script is always false
if(res.getStatusCode() == 200)// it's for success login
return 'Success';
}
// if any exception
else {
return 'Error';
}

 
Steve CairneySteve Cairney
I can confirm that when using

return res.toString();

in the class it will return OK 200 regardless. So we need to look at how to use 

return res.getBody();
Steve CairneySteve Cairney
Sorry Balu, I posted the above before seeing your question

to give an error,  res.getBody(); must return a value that does NOT say "Success". Anything else means that it will have failed (regardless of the 200)
Balu_SFDCBalu_SFDC
Can you put system.debug('Responce:::::'+res.getBody()); before return res.getBody(); and share the debug here...
Naval Sharma4Naval Sharma4

Hi Steve,

Based on your first post on this question, I think it's returning an array.

So you need to check like this.
if(result[0].indexOf("Success") != -1)
   alert('success'); 
else 
   alert('fail');


 
This was selected as the best answer
Balu_SFDCBalu_SFDC
Hi Steve,

try below code this will work for you  in .
webservice static String PostBooking(String json, String authorizationToken)
    {   
      // Now send the data to Its Approved
      HttpRequest req = new HttpRequest();
      HttpResponse res = new HttpResponse();
      Http http = new Http();

      req.setEndpoint('http://removed');
      req.setMethod('POST');
      req.setHeader('Content-Type','application/json');
      req.setHeader('Authorization-Token', authorizationToken);
      req.setBody(json);
      req.setTimeout(60000);

  //    try {
          res = http.send(req);
                    
  //    } catch(System.CalloutException e) {
   //       System.debug('Callout error: '+ e);
   //       System.debug(res.toString());
   //   }
      
      //return res.toString();     
string isSuccess,isErrors;
        JSONParser parser = JSON.createParser(res.getBody());
        while(parser.nextToken() != null) {
            if((parser.getCurrentToken() == JSONToken.FIELD_NAME)) {
                if(parser.getText() == 'success') {
                    parser.nextToken();
                    isSuccess = parser.getText();
                }
                if(parser.getText() == 'errors') {
                    parser.nextToken();
                    isErrors = parser.getText();
                }
            }
        }
        System.debug('JSON Response Success :' + isSuccess);
        System.debug('JSON Response Errors :' + isErrors);
return isSuccess;
}

change the code in Script as well like 
if (result == "true") {
alert('Ok..')
}
else{
alert('Error');
}
Steve CairneySteve Cairney
Thanks all, Naval hit the nail on the head, it was actually returning an array.