PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 8, 2022

[FIXED] How to convert this curl cmd to jQuery $.ajax()

 September 08, 2022     ajax, api, curl, jquery, json     No comments   

Issue

I'm trying to make a api call with jquery ajax.

curl --request POST \
--url https://test.stytch.com/v1/passwords/strength_check \
-u 'PROJECT_ID:SECRET' \
-H 'Content-Type: application/json' \
-d '{
    "password": "jvx-kbj4nbj7ZKP9ncv"
}'

I tried ajax like this, but it is not working:

$.ajax({
url: "https://test.stytch.com/v1/passwords/strength_check",
beforeSend: function(xhr) { 
  xhr.setRequestHeader("Authorization", "Basic " + btoa("PROJECT_ID:SECRET")); 
},
type: 'POST',
dataType: 'json',
contentType: 'application/json',
processData: false,
data: '{"password":"jvx-kbj4nbj7ZKP9ncv"}',
success: function (data) {
  alert(JSON.stringify(data));
},
error: function(){
  alert("Cannot get data");
}
});

What am I wrong ? Thanks


Solution

var url = "https://test.stytch.com/v1/passwords/strength_check";

var xhr = new XMLHttpRequest();
xhr.open("POST", url);

xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "Basic UFJPSkVDVF9JRDpTRUNSRVQ=");

xhr.onreadystatechange = function () {
   if (xhr.readyState === 4) {
      console.log(xhr.status);
      console.log(xhr.responseText);
   }};

var data = `{
    "password": "jvx-kbj4nbj7ZKP9ncv"
}`;

xhr.send(data);


Answered By - Joukhar
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing