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.
Related
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.
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.
I found allot of examples of AJAX and I think I can get some code with it to work on my own. If only I knew what the use of all the terms of the AJAX code where.
I think in general it lacks the availability of these guides or special pages where constructed code is explained in detail for new programmers.
This would help enormously because of the misunderstanding of the syntax in many cases. Me for example spend 8 hours a day on my internship to learn PHP, Jquery, HTML from scratch and there is allot of information out there but its not structured and in most cases to technical. Any tips on that maby ? :)
$.ajax({
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
Ajax is asynchronous, which mean you can use it to get new informations from the server without reloading the whole page.
Here's an explanation of your code :
$.ajax({
$ is the JQuery object, on which you're calling the ajax function
type: 'POST',
You're gonna send your data by post, which mean that you'll have to get them in php with $_POST['variable_name']. You could also put GET instead
url: 'http://kyleschaeffer.com/feed/',
the url you want to reach
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
as you're sending your request with POST, you cannot pass data directly from the URL.
So you have to pass them like that. { nameVar: 'value', .... }
If you were sending with GET, you could directly write them into url like : "http://my_url.php?var1=val1&var2=val2 etc ...
beforeSend:function()
You can define an action before sending your ajax request
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
Here, inside your div "ajax-panel" you want to write some content. (a div "loading" and a picture inside "loading").
success:function(data)
If your request is successful, you can do something. By successful it means if server answer 200 i guess, anyway ... If you have a response from server... ;)
$('#ajax-panel').empty();
You delete content into ajax-panel
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
You're adding some html AFTER (append) the ajax-panel div
error:function()
Not sure you were looking for that, hope that help you ;)
AJAX is an acronym standing for Asynchronous JavaScript and XML and this technology help us to load data from the server without a browser page refresh.
If you are new with AJAX, I would recommend you go through our Ajax Tutorial before proceeding further.
JQuery is a great tool which provides a rich set of AJAX methods to develope next generation web application
Take a took at this
$.ajax({
type : varType, //GET or POST or PUT or DELETE verb
url : varUrl, // Location of the service
data : varData, //Data sent to server
contentType : varContentType, // content type sent to server
dataType : varDataType, //Expected data format from server
processdata : varProcessData, //True or False
success : function(msg) {//On Successfull service call
},
error : function() {// When Service call fails
}
});
I create a method to post json data to web service :
function WishList() { }
WishList.prototype.addToWishList = function(redirectURL, postURL, userObj) {
$.ajax({
type: "POST",
url: postURL,
data: JSON.stringify(userObj),
dataType: 'json',
contentType: "application/json",
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
}
This is my object:
var user1 = {
ID:1,
Sex:1,
Name:"titi",
Company:"ABC",
Address:"Phnom Penh",
Email:"test.abc#gmail.com",
Phone:"011123456",
WebAccount:"test.abc#gmail.com",
Password:"123456",
GroupCustomerID:125,
Stars:1,
IsVIP:0,
PriceLevel:1,
LastDateSale:"\/Date(-62135596800000)\/",
TotalCredit:150.12,
AgingData:null,
TotalRedeemPoint:1000.00,
RedeemData:null,
ExchangeRate:155.00,
HistoryData:null
};
Calling function :
$(document).ready(function () {
var myWishList = new WishList();
$('#addToWishList').click(function(){
myWishList.addToWishList('http://www.blahblahblah.com' , 'http://blahblah/Website/Products/Product.svc/Wishlist/' , user1);
});
});
Then I got errors in my console :
"NetworkError: 405 Method Not Allowed in firefox and Invalid HTTP status code 405 , XMLHttpRequest cannot load url in chrome.
Note: When I use Rest Client of Chrome to POST to web service, it worked.
Any help would be much appreciated, thank you.
Not sure what you are using as the service on the other end but this may be due to cross domain posting. I hate to post a link and run but this may be of some use to you.
http://praneeth4victory.wordpress.com/2011/09/29/405-method-not-allowed/
Looks like they could get it working in IE but had some issues as you with the other browsers. Perhaps these couple changes will help access the service better.
This post was good at explaining the error and parts to it as well so if the above link is not helpful this one may help you diagnose the issue further.
http://www.checkupdown.com/status/E405.html
ok ok last edit, just wanted to make sure you have enough info to hopefully resolve your issue, here is a good article on the underlying problem I believe you are having..
http://www.d-mueller.de/blog/cross-domain-ajax-guide/
I am getting data through $.ajax multiple times. However the data is not getting refreshed in every call. Rather I am getting the same data in every call to $.ajax. The code was working properly at my home.
However in below code if I substitute console.log("success "); with console.log("success "+data); and observe in chrome console, then the code works fine. I suspect its a caching issue, but can figure it out.
function getDataJSON()
{
originalData="";
new Date().toString();
$.ajax({
url: 'data.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
success: function(data)
{
console.log("success ");
...
...
Thanks
you can set cache Cache. by default it will set to cache=true.
from DOCS
If set to false, it will force requested pages not to be cached by the
browser. Note: Setting cache to false will only work correctly with
HEAD and GET requests. It works by appending "_={timestamp}" to the
GET parameters. The parameter is not needed for other types of
requests, except in IE8 when a POST is made to a URL that has already
been requested by a GET.
$.ajax({
url:'url',
cache:false,
.....
})
Like #Ravi said cache priperty is you're frined.
You should realy spend more time on studying you're weapon of choice!
Link => first hit on google if you search jquery ajax
There is another method of preventing caching. Just append some random number to url you are accessing.
For example:
"www.url.com?" + new Date().getTime()
or
"www.url.com?" + Math.random()
from Stack answer