How can i print JSON with console.log - ajax

I am writing a program with php laravel and react.js. But i am very new to these. Anyway in react, i am sending a API request with ajax.
like this:
const sendquery = {
"async": true,
"crossDomain": true,
"url": url,
"method": "POST",
"headers": {
"Authorization": "Bearer " + tkid,
"Accept": "application/json",
"Content-Type": "application/json",
},
"processData": false,
"data": query
};
$.ajax(sendquery).done(function (response) {
console.log('Survey Request :' + response);
});
There are another API requests that are printing nicely when i console.log() because they are in array type. But this must be json. I tested API with Postman everything is OK. But still i have output like this:
Survey Request :[object Object]
Can anyone please help ?

You can try with JSON.stringify(response) but note that it doesn't work with all the types, see JSON.stringify doesn't work with normal Javascript array, for example.

To get json
console.log(JSON.stringify(response));
To get structured JSON
console.log(JSON.stringify(response, undefined, 2));

Another option apart from what #Beris Demiray wrote is to write:
console.log('Survey Request :', response);
Meaning to put the object as a second parameter in the log.
This will give you an object that you'll can open in the debugger.
The reason why this option is better because JSON.stringify doesn't stringify all objects, and this lets you look into all objects.

Use the JSON.parse function like as below:
JSON.parse(response, null, 2)

The best way is pass the display string in the first argument and the object as second
console.log('Survey Request', response);

use console.dir(object:any) like this ->
$.ajax(sendquery).done(function (response) {
console.dir(response);
});

While i acknowledge all answers above, it's important to point out why you seem to be getting that result on the console.
When you do this:
console.log('Survey Request :' + response);
You are basically trying to concatenate a primitive value 'Survey Reguest :' with a complex value response, which is an object. Javascript cannot convert an object response to a primitive value. By simply replacing the + with a , signifies that you are sending the response object as a separate argument. Javascript then logs the arguments separately to the console.

Related

How can I save a response of HTTP GET Request in variable?

Here is my API code
#GetMapping("/api/test")
public String test() {
return "hello";
}
Then I will send request to this API by using ajax.
function test() {
$.ajax({
type: "GET",
url: "/api/test",
success: function(response) {
}
})
}
I want to save the value of ajax call response (In this case "hello") in variable. Please let me know how to do it.
Several ways of doing it !
As far as only a String message is concerned you can just store it like below
`var myResponse=response;`
Alternatively, you can also access values if response is an object (JSON reponse I mean)
for e.g. `var resp=response.message; //Assuming message is a key in response JSON`
For testing, use alert(response) or console.log(response) to see how your response is coming and manipulate accordingly !
Feel free to refer this link for detailed Ajax walkthrough https://www.tutorialspoint.com/jquery/jquery-ajax.htm
Hope these helps!

Shopify order API returns OK but does not update order using JS

I'm trying to create an order using JS. I've authenticated my app and have a function that POST's to orders.json. I see a status code of 200, indicating that the request submitted OK (right?) but the order itself never gets created. I've heard something about disabling cookies in my request, but I don't know how to do that, so if that's what I need to do please let me know.
I'm putting up my entire function, since I'm new to this entire thing and it seems that it's probably the structure of my request, not the API call. I'm seeing the "Error" log in the console, so clearly the error function is running.
function submitShuffle(prodid)
{
console.log(prodid);
var params = {
"order": {
"line_items": [
{
"variant_id": prodid,
"quantity": 1
}
]
}
};
$.ajax({
type: 'POST',
url: 'https://<my-usrnam>:<my-pass>#toyboxshufflesandbox.myshopify.com/admin/orders.json',
dataType: 'application/json',
data: params,
success: function(data){
console.log(data);
},
error: function(data){
console.log("Error");
console.log(data);}
});
}
You cannot retrieve information from Shopify Admin API by AJAX. There is a limitation about this because you have to expose your username/key and password which is not a good idea.
You have to use some service/app or just to create a custom app.
Shopify returns an Object when you make a call. Hence 200 OK status. Inspect the object returned. A failed create POST object will not have an ID. So there is clue number one. Secondly, you'll see that Shopify tells you what the problem was in the Error key of the returned object. If you cannot figure out what you did with the message from Shopify, make the same call to the GraphQL endpoint if you can, as the error messages Shopify returns from those endpoints are currently much better. They are backporting them to the older REST API, but for now, GraphQL is more expressive.

Ajax empty data returned

I am using Angular, but same thing happens with a normal jQuery Ajax request, to get data.
Data structure is:
{
"providers":
{
"complete":[1,2,3],
"inProgress":[4,5,6]
},
"results":
[
{"thing":{"id":"1234"},"somethingelse":null},
{"thing":{"id":"5678"},"somethingelse":null}
]
}
The Ajax request looks like this:
$.ajax({
dataType: 'jsonp',
headers: {'cache-control': 'no-cache'},
url: $resultsURL
}).done(function(data) {
and the Angular request:
$http.jsonp($resultsURL)
.success(function(data, status){
Now, kind of hard to explain without a demo and sadly I can't expose any of the api endpoints, but the above works fine, as expected and tells me I have two results.
Now the real issue, I can append a partials request to the url and get back a smaller data set, with an offset etc, if I try console.log(data.results) I get an empty []. If I try data.results.length, it returns 0.
Appreciate that might not make much sense, so I guess the first thing to solve is why the ajax might return the length of data.results as zero?
Have I missed something massively obvious?
Cheers
Turns out I was hitting the service too quickly so it thought it was empty initially.

Passing ampersand to ajax with jquery?

I have this ajax call
function addNewRemarksToDataBase(argRemark) {
if (argRemark != '') {
// if not blank
$.ajax({
url: '../AutoComplete.asmx/AddNewRemarks',
type: 'POST',
timeout: 2000,
datatype: 'xml',
cache: false,
data: 'argRemarks=' + argRemark,
success: function (response) {
// update the field that is source of remarks
updateRemarksSource();
},
error: function (response) {
}
});
}
};
The method is defined as
[WebMethod]
public void AddNewRemarks(string argRemarks)
{
BAL.BalFactory.Instance.BAL_Comments.SaveRemarks(argRemarks, Globals.BranchID);
}
The problem is if a user enters something like long & elegant or something like smart & beautiful, something that contains &, I only get the first part before &, long (in the first case), smart (in the second one) (also notice the whitespace!)
I read in jquery ajax documentation that one should set processData to false, because it is something used for querystring or something. I added the
processData: false
but I am still getting the term before the &. I don't want to use encodeURIComponent because it will turn the & to amp; (or something like that). What I need is the full value long & elegant, smart & beautiful that will be saved to the database. How can I do this?
EDIT Doing { argRemarks: argRemark } doesn't helps! The function doesn't event gets called. Running it with firebug, and setting breakpoint in error function, I got this
[Exception... "Component does not have requested interface" nsresult: "0x80004002 (NS_NOINTERFACE)" location: "JS frame :: http://localhost:49903/js/jquery-1.8.1.min.js :: .send :: line 2" data: no]"
UPDATE 2 :
Doing
data: 'argRemarks=' + encodeURIComponent(argRemark)
did the trick. But can anyone help me understand how does this works? I thought it would convert & to & but it didn't? The parameter I am receiving to the method now is just what I wanted, long & elegant, smart & beautiful, doesn't encodeURIComponent() converts special characters?
You do need to encode the argRemark. The easiest way to do this is to let jQuery do the job for you:
data: { argRemarks: argRemark }
This is different than data: 'argRemarks=' + argRemark in that by passing in an object, jQuery assumes that it needs to URL-encode the values of the properties on that object -- while if passing in a string, you are expected to have properly encoded it beforehand.
You have to URL-encode the string first:
data: 'argRemarks=' + encodeURIComponent(argRemark)

In ExtJS, How can I list multiple returns from JSON data in a field set?

Ok, I am semi-new to ExtJS, and I am building a program that has "inputs" that are listed in a grid, and in my DB these inputs can be linked to "symptoms".
I am trying to create a function that will take in the id of the input and grab all of the symptoms from the database that are linked to that symptom, and list them in a field set.
It works fine when I click on an input that is only linked to one symptom, but if the input is linked to more than one symptom, then the error says.. "invalid property id"
This is what I have for my function.
function listSymptoms(inputID){
Ext.Ajax.request({
url: "../../inc/project4.php?list=symptoms",
reader: new (Ext.data.JsonReader)({
root: "symptoms",
inputid: "id"
}),
params: {
inputid: inputID
},
method: "POST",
success: function (f, a){
var jsonData = Ext.util.JSON.decode(f.responseText);
symptomsFieldSet.body.update(jsonData.data.name);
},
failure: function (f,a){
Ext.Msg.alert('There was a problem opening your message.');
}
});
}
I have the inputID for the function being passed in when the user clicks on one of the inputs that are held inside the grid.
I believe that my problem has something to do with this line..
symptomsFieldSet.body.update(jsonData.data.name);
I am just stumped on how to handle this. Do I need to create a data store like I have for grids? Or is there an easier way to do this?
ANY help is appreciated! thanks in advance.
I think you need to rethink the structure of your JSON response object. You can send this in your JSON response to your request. If you are using Ext.util.Ajax calls instad of a form, you'll need to decode this JSON response string using the util method Ext.util.JSON.decode(). Check out the API Documentation
{
success: true,
msg: {text: 'this can be used for error message handling' },
data : [
{id:1,
chiefComplaint: 'head hurts',
symptoms: [
{symptomID: '740.1', text: 'Headache'},
{symptomID: '12352135'. text: 'and so on'}
}
]
]
}

Resources