'salesforce get token using jQuery ajax method

I have just intigrated the salseforce api using curl in php and its working fine but now i have to using the same thing with ajax so no curl is used here below is my code

var param = {
grant_type: "password",
client_id : "CLIENT_ID",
client_secret : "CLIENT_SECRET",
username:"USERNAME",
password:"PASSWORD"};
    $.ajax({
        url: 'https://test.salesforce.com/services/oauth2/token',
        type: 'POST',
        data: param,
        dataType: "json",
        crossDomain: true,
        contentType: "application/x-www-form-urlencoded",
        success: function (response) {
            console.log('Successfully retrieved ' + response);
            alert(JSON.stringify(response));
        },
        error: function (response) {
            alert(JSON.stringify(response));
        }

    });

when i alert the response than showing below response

enter image description here

and when inspect the response then showing below response

enter image description here

Please help me what's wrong and how to solve this problem

Thanks



Solution 1:[1]

This is not a good practice to expose this secrets in java script variables. Please have a look at my blog and try to authenticate using APEX which is server side validation. In my blog I have shown a secure way to connect with Salesforce API using Auth provider and named credientials where no one sees the password and not stored anywhere.

If you follow the approach authtication will be done by salesforce no extra code required you can call any Salesforce API. but it will be serverside only.

But if you want to do it from client side you can get help from here https://developer.salesforce.com/docs/atlas.en-us.ajax.meta/ajax/sforce_api_ajax_introducing.htm

https://avionsalesforce.blogspot.com/2022/01/salesforce-to-salesforce-connection.html

Sallesforce help document

https://help.salesforce.com/s/articleView?id=sf.named_credentials_about.htm&type=5

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Avijit Chakraborty