how to fetch data from url using javascript - javascript

I have link generated from rest Api console
this is the link:
https://SomeThing/rest1/order2/getOrders
and i have token generated from the same rest Api console
now i can make post by ajax ang get the data but i want to fetch this data
this is my code
$(document).ready(function() {
$("button").click(function() {
$.post(
"https://SomeThing/rest1/order2/getOrders",
{ token: "Token" },
function(a, b) {
<----what i should use --->
}
);
});
});

Good news is that you are very close, bad news is that you leaked your token and will have to regenerate it now.
I would replace function(a,b,) just with function(data) and accessed data retrieved from called REST endpoint through the variable data
$(document).ready(function() {
$("button").click(function() {
$.post(
"https://www.tesetturpazari.com/rest1/order2/getOrders",
{ token: "<token>" },
function(data) {
console.log(data);
}
);
});
});
When you then press F12 (or other hotkey used to open developer console in your browser), you can go through data retrieved from remote server and figure out how to further process your data based on its structure. It comes back in JSON format, which is very easy to process in Javascript.
OP further explained the need to render data to div that already exists on site (in the comment on the answer that was deleted), solution is to update callback function:
$(document).ready(function() {
$("button").click(function() {
$.post(
"https://www.tesetturpazari.com/rest1/order2/getOrders",
{ token: "<token>" },
function(data) {
// Possibly before displaying it all, do some preprocessing here over the data variable
// Replace 'mydiv' with ID of an element where you want to show data
$("#mydiv").html(data)
}
);
});
});
Note: Please regenerate and replace your token.
Note 2: I repost this answer so I can remove the original one where I managed to duplicate access token, sadly.

Related

Should I validate response data in jQuery's ajax success handler?

Let's assume I have a post AJAX call and I want to put returned data into some HTML elements.
$.post(settings.url, function(data) {
$('#someElement').text(data.someData1);
$('#someElement2').text(data.someData2);
});
I'm a back-end developer and it's natural for me that I have to do server-side validation of any piece of data coming from user. Although it's the opposite situation, the code above feels a little bit wrong for me (not validated outside data). But on the other hand, I know what I'm returning from the server.
The question is if is it fine to trust that data returned from (also mine) back-end application will have expected structure, or should I validate somehow every data coming server?
Additional question is if there is some nice method to do such validation? Manual validating of existence of every piece of data seems to be a pain in the neck. Especially for more complex data structure.
Just during writing this question an idea came to my mind. I could use $.extend() just like it's commonly used for setting default options while writing modules/plugins. Something like:
$.post(settings.url, function(data) {
var trustedStructure = $.extend({
someData1: $('#someElement').text(),
someData2: $('#someElement2').text(),
}, data);
$('#someElement').text(trustedStructure .someData1);
$('#someElement2').text(trustedStructure .someData2);
});
That way I could have trusted data with additionally current data as default or any other if I want.
Edit:
Forgot to note. I'm talking about pure JSON data responses. No HTML etc included.
Generally you don't validate the response data, as you said before, the data is returned from your own back-end. What you really need to do is to ensure that you have a proper way to handle exceptions or errors with the information coming from the server.
If you're returning an exception from the server you should have a way in the client-side to figure out that if an error or not.
i.e. returning a specific code like a Rest API or having a JSON structure like this:
// Success
{
"error": false,
"data": {
...
}
}
// Exception
{
"error": true,
"message": "Username already taken",
"type": "warning"
}
If you always return a 200 OK status code:
$.ajax({
...
success: function(response) {
if (response.error) {
alert(response.error.message);
} else {
document.querySelector('#field').value = response.data.text;
}
}
});
The HTML Response Codes are useful when you use promises, you can return a 200 OK for the primary flow (success, done), and 4XX or 5XX if something unusual happen (fail):
$.ajax({
url: 'example.php',
...
})
.done(function(response) { alert(response.data); })
.fail(function(error) { alert(error.message); })
.always(function() { clearFields(); });
Does the data returned from your server contain DOM Elements?
If it doesn't and is a pure text return, you can use a textarea to parse incoming data like this:
var textArea = document.createElement('textarea');
textArea.innerHTML = data;
data = textArea.textContent;
Just try it out and let the server send some <p>, <img> or <script> Elements

How do I reload a page without the user noticing?

I've been trying to figure out how to reload a page and pull dynamic info from a server without users noticing the page has been reloaded. For instance, if I want to create a 'live' message board system when the board updates every time other people make a comment or post a message.
I noticed that Javascript has a boolean function .reload() that when set to false reloads the page from the cache and when set to true reloads the page from the server, but from what it looks like, the function does something similar to reloading the browser. Is there another way do what I'm trying to do?
Something like this...
function getContent()
{
return new Promise(function(resolve, reject){
var url = "http://yourendpoint.ext"
$.ajax({
url: url,
success: function(data)
{
resolve(data);
},
error: function(err)
{
reject(err);
}
});
}));
}
// Usage
getContent()
.then(function(data)
{
$('#some-element').html(data);
});
Are you sure you really want to do an reload?
What you could do is make an AJAX Request to the server and display the result, without even reloading the Page. I would recommend using jQuery for this, just out of comfort.
AJAX stands for Asynchronous JavaScript and XML. In a simple way the process could be:
User displays page, a timer is started
Every 10s (or 20s or whatever) you do an AJAX Request using JavaScript, asking the server for new data. You can set a callback function that handles the result data.
Server answers with result data, your callback function inserts the new data.
Code Example (taken from jQuery Docs):
$.ajax({
method: "POST",
url: "target.php",
// Data to be sent to the server
data: { name: "John", location: "Boston" },
// success will be called if the request was successfull
success: function( result ) {
// Loop through each Element
$.each(result.newElements, function(index, value) {
// Insert the Element to your page
$('.classOfYourList').append(value);
}
});
});
Just set the proper endpoint of your server as the target and insert whatever you want to do in the success function. The function will get an answer containing whatever you sent to it from the server. More Information in the jQuery Documentation:
You can Achive what you want using AJAX. you can use ajax with either javascript or jquery. You can load the content you want dynamically without reloading the entire page. here is a quick example.
Here is a <div> with id load where your content will be loaded.
<div id="load">Loaded Content:</div>
<button id="load_more">load more</button>
JQuery to request for the data, where getdata.php is the php file which will send data you want to display.
<script type="text/javascript">
$(document).ready(function(){
$("#load_more").click(function (){
$.post("getdata.php", {variable1:yourvariable, variable2:ifneeded},function(data){
//data is the string or obj or array echoed from getdata.php file
$('#load').append(data); //putting the data into the loaded div.
}
});
});
});
</script>`
finally getdata.php file
<?php
//fetch data from Databas eif needed. or echo ut what you want to display in the div.
echo "This is a small example of using JQuery AJAX post request with PHP.";
?>
Hope that helps!

Receive data in ajax call back from server without reloading and update current page. Express 4 and Node

I have a form
form#form-reflow(action='/', method='post',
onsubmit="docreflow()")
input#textinp(type="text", name="textinp")
input#submit(type="submit", name="submit")
that runs the following ajax client script to send the form data to Express.
function docreflow() {
$('#form-reflow').on('submit', function (evt) {
evt.preventDefault();
$.post($('#form-reflow').attr( 'action' ),
{
data: $("#textinp").val(),
headers: {'X-Requested-With': 'XMLHttpRequest'},
dataType: 'text',
accepts: {
text: 'text/plain'
},
})
.done(function onDone (data) {
console.log("returned data is: ");
var data = JSON.parse(data).data;
console.log(data);
$('#form-reflow').html(data);
}
)
.fail(function onFail(err) {
$('#form-reflow').html("<p> There Wazza Khold Dey</p>");
});
})
}
I want the server POST method to not reload the page.
Instead I want to know how can I receive the data on the client back as an html:
this is jade btw.
div#ajaxMsg
p It actually works!
p Data is "#{data}"
from the controller method while it does something like
res.render('afterReload.jade', {some data...})
The page should not reload instead on ajax done it should
just include that rendered html snippet here:
$('#form-reflow').html(data);
For eg, consider you would write an AJAX api to New york times
the NYT api uses a jsonp to sendback with your defined Callback
and I can just include that data in my current page.
Lets say I do a json rendering only. from the server I send the json data
and on success, the function will append that data on client side as I wish.
How can I do a 'No Reload' AJAX server to client response?
Feel free to ask me for further clarity.
According to this
changing the evt type to change doesn't affect the behaviour. it still reloads the page.
Both the current and POST page controller routes are defined to be '/'
UPDATE
I have removed the html5 onsubmit event. no need:
form#form-reflow(action='/', method='post')
input#textinp(type="text", name="textinp")
input#submit(type="submit", name="submit")
UPDATE #2
This does not solve my problem
even if I add a return false; at the end of the function call in that script,
the controller function:
function ajaxReq(req, res) {
console.log(req.body);
if (req.accepts('text')) {
//#TODO: do something with this to doc reflow instead page reload
res.json({data: req.body.textinp});
}
};
still reloads the page.
I disagree with #mccannf for pointing out that its a duplicate.
No it doesn't solve my problem. Try implementing an express app. where you render something at '/' with a form that posts with ajax to server and it should render back an html snippet from, say a .jade/template file, as an html chunk back to the successful ajax call and replace the current html in place of form.
That is the core of my problem.
UPDATE #3
I have been able to check this out and do a rendering but its not doing a partial rendering.
Anyone knows how to use it in express 4 without loading the whole page and
returning value to ajax call?
This solves my problem and now it is a single working page:
script(src="js/scr.js")
the view is this and something more:
form#form-reflow(action='/scr')
input#textinp(type="text", name="textinp")
input#submit(type="submit", name="submit")
scr is this without a function wrapper. for eg:
$('#form-reflow').submit(function (e) {
e.preventDefault();
var posting = $.post( $('#form-reflow').attr( 'action' ),
{data:$("#textinp").val()
})
posting.done(
function onDone (val) {
$("#form-reflow").removeAttr('action');
$("#form-reflow")
.html("<p> hello baby " + val.data + "</p>");
});
return false;
});
the controller is :
some_controller = function some_controller(req, res) {
if (req.accepts(['json', 'jsonp'])) {
res.setHeader("Content-Type", "application/json");
var json_data = {data: req.body.data,
};
res.jsonp(json_data);
}
};
app.use('/', some_router);
some_router.post('/scr',some_controller);
So this works without rendering to a new page.

How to store/remember the data fetched from ajax call?

I'm retrieving some data into a JSON array, then display it into an HTML table which contains some data enclosed within hyper links. i.e. a couple of the columns' data are clickable, once clicked it displays another JSP page (say page #2) with some more data which was kept on the JSON array itself.
Now this page 2 has a 'Back' button functionality - the expected behavior is when user clicks the 'Back' button it should go back to page 1 where the HTML table data was displayed and user should be able to see the data which they first fetched too. i.e. there should be some way to remember the data fetched from my initial AJAX request and retrieve the same data which user fetched in page 1 when they go back to that page from the child page#2.
Th AJAX call is triggered when user enters an account# and the type of account - I fetch data accordingly and get the result in the 'response' object and neatly display it on html table, but after user moves from that page and again hits the back button I see the page#1 without the table. Now again I cannot ask the user to re-enter the details to see the data that they retrieved earlier. It's pretty annoying.
Please give me a solution to this problem. Thanks All.
Appreciate for taking time to read this.
Here's a part of the code:
$(document).ready(function () {
var flag = "1";
$('#accountType').bind('change', function (event) {
var accountType = $('#accountTypeSelect').val();
var account = $('#accountText').val();
jQuery.ajax({
type: 'POST',
url: '${pageContext.request.contextPath}' + "/Page1.spr", //request page
cache: false,
dataType: "json",
data: {
"accountType": accountType,
"account": account,
"flag": flag
}, //data sent to request page
success: function (response) {
// code to display the data into the html table
},
error: (function (message) {
console.log("error message : " + message);
}),
statusCode: {
404: function () {
alert("page not found");
}
}
});
});
You can save the data in HTML5 sessionStorage or localStorage using the setItem method as follows:
success: function(response) {
sessionStorage.setItem("result", response)
// code to display the data into the html table
}
And access it later using the getItem() When you come back to the page like
var prevResponse = JSON.parse(sessionStorage.getItem("result"));
if(prevResponse)
{
// code to be executed when old dats is found
}
else{
}
Ideally you code in first pages load will be something like
var prevResponse = JSON.parse(sessionStorage.getItem("result"));
if(prevResponse)
{
// data exists : code to be executed when old dats is found
}
else{
jQuery.ajax({}) // send the AJAX request to fetch data
}
You can read more about session and local Storage here
Browser support for web storage API.
Update
If you don't have HTML5 support, you could use jQuery cookie plugin (There are plenty of others as well) for storing data at client side.
You can store data into a cookie as follows:
$.cookie("result", response);
Then to get it from the cookie like:
$.cookie("result");
You maybe can use cookie via jquery. But user have to enable the browser's cookie. It usually enabled by default setting.
To add:
$.cookie("key1", data1);
$.cookie("key2", data2);
To read:
$.cookie("key1");
To delete:
$.removeCookie("key1");
So, you can try to read cookie to load table data, if no data, call ajax:)
Another way is to save it in a hidden input:
success: function(response){
$("#hiddenInput").val(JSON.stringify(response));
}

Iterate over the data to show Autocomplete suggestions

This is an API which returns results in an array, for auto suggestions
For Eg. if I query "google" I get the results as follows
["google","google maps","google translate","google earth","google images","google docs","google voice","google scholar","google chrome","google calendar",]
You can try it yourself here
Here's my code that I m using to query this API but it doesnt seem to return results.
Here's the code that I m using for it
$(function() {
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "q.php",
dataType: "json",
data: {
"q" : request.term
},
success: function( data ) {
response(data[1]);
}
});
},
minLength: 2
});
});
I dont understand where am I going wrong in the code
Please correct me ! Because it doesnt seem to be working as I wanted
Edit: Accessing the Data from the same server
You forgot to add jquery-ui library in your fiddle. But if you do code will not work anyway, because you can't access data from another domain via ajax request. Only from same domain on what js code executes.
This might be helpful
$(document).ready(function() {
$.getJSON('http://twitter.com/users/usejquery.json?callback=?', function(json) { //get information about the user usejquery from twitter api
$('#twitter_followers').text(json.followers_count); //get the follower_count from the json object and put it in a span
});
});
Look for something called as cross-domain ajax.
http://usejquery.com/posts/the-jquery-cross-domain-ajax-guide
You can read here about using jQuery autocomlete for cross-domain environment: http://1300grams.com/2009/08/17/jquery-autocomplete-with-json-jsonp-support-and-overriding-the-default-search-parameter-q/
Also you need to add jquery.autocomplete.js to your jsFiddle environment.

Categories

Resources