0

  $("#nonjstest").click(function() { 
     $.ajax({
            url:"https://petstore.swagger.io/v2/pet/findByStatus?status=sold",
            type: "GET",
            contentType:"application/json",
            success: function(data){
              alert(data[0].id) 
            }
          })
  
   })

Here, I am passing the required parameters directly in the URL status=sold. I want to pass them via a variable instead, but it's not working. I've tried the following:

var requiredata = ["status=sold"]


   $("#nonjstest").click(function() { 
     $.ajax({
            url:"https://petstore.swagger.io/v2/pet/findByStatus",
            type: "GET",
            data: requiredata,
            contentType:"application/json",
            success: function(data){
              alert(data[0].id) 
            }
          })
  
   })

The request itself is successful, but nothing is returned, meaning, the parameters are not passed correctly. What is the problem with the way I'm passing the Array string?

I've tried stringifying the data, but it didn't work either.

Why is it not working? How do I pass the array string data with a variable?

1 Answer 1

1

Try sending the params as an object instead of as an array:

    var requiredata = {
      status: 'sold'
    };


   $("#nonjstest").click(function() { 
     $.ajax({
            url:"https://petstore.swagger.io/v2/pet/findByStatus",
            type: "GET",
            data: requiredata,
            contentType:"application/json",
            success: function(data){
              alert(data[0].id) 
            }
          })
  
   });

Another option would be to pass the params as a string but it's worse because you have to pass it already encoded.

Check the docs for more information.

Sign up to request clarification or add additional context in comments.

2 Comments

It worked, but why? The requirement was an Array string, not JSON object?
The data config of the ajax admits an object, a string of an array, but if you pass an array jquery will pick the index as the param key, in your code it sent 0: "status=sold". I encourage you to check the docs for more information. And pleasse if I solved your question consider marking my answer as the accepted answer. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.