fetch mysql data into javascript variable - javascript

var events = [
{"id":"1","title":"pending","start":"","end":"2020-04-27 10:25:34","url":"","allDay":"1"},
{"id":"2","title":"22","start":"2013-12-15 10:25:47","end":"2013-12-16 10:25:39","url":"","allDay":"1"},
{"id":"3","title":"33","start":"2013-12-26 10:25:50","end":"2013-12-27 10:25:42","url":"","allDay":"false"},
{"id":"4","title":"2-12 ","start":"2020-04-20 10:26:28","end":"2020-04-20 10:26:28","url":"","allDay":"false"},
{"id":"6","title":"test nay","start":"2013-12-09 00:00:00","end":"2013-12-11 00:00:00","url":"event","allDay":"false"}
]
i want to Retrieve data in my database into this JavaScript variable please anyone simply explain how do to do that ?

You have to use any of the backend technologies (Java/Python/php/Node JS etc) to save the json array to DB. This is because javascript can not directly handle or connect to Database.
From javascript side, you can use jQuery ajax to send the data to your backend api as follow.
$.ajax({
type: "post",
url: "", //your backend API endpoint
data: {data: events},
success: function(responseData){
//If backend api runs successfully, control comes to this method with responseData as return from api
},
error: function(responseData){
// If api call does not run properly, control comes in this method.
}
});
And your backend API got the data, connects to the DB and run the SQL to store the data. So based on backend technology, you have to develop the code.

On the server side, create a get or post route which sends data in JSON format.
On the client side, use jQuery/fetch/axios to grab that data. It's easy. Try this, https://github.com/axios/axios

Related

How to use access token stored in session storage for doing web api call using HttpClient?

I have done login using ajax call and stored the access token in session storage using following code.
$('#btnLogin').click(function () {
$.ajax({
url: 'http://localhost:59983/token',
method: 'POST',
contentType: 'application/json',
data: {
username: $('#txtUsername').val(),
password: $('#txtPassword').val(),
grant_type: 'password'
},
success: function (response) {
sessionStorage.setItem("accessToken", response.access_token);
console.log("Success!!!!");
alert("Login Successful");
},
error: function (jqXHR) {
console.log("Failed!!!!");
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
});
});
Now after login, I want to use the stored access token for performing api calls using HttpClient from a controller method. I don't know how to pass that stored access token to make api call.
The following code I have written to make api call using HttpClient.
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:59983/api/flight");
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
var responseTask = client.GetAsync("flight");
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<IList<tblFlight>>();
readTask.Wait();
flights = readTask.Result;
}
else
{
flights = Enumerable.Empty<tblFlight>();
ModelState.AddModelError(string.Empty, "Server error. Please contact administrator.");
}
}
Please suggest me how to use that stored access token ?
When we are dealing with webstorage such as session storage or local storage we are doing it client side using javascript , jquery etc. These storage item cannot be accessed in server side code. They are confined to your local browser and can be accessed from client side code running on browser.
Now for your condition i think you can go for session on server side. The point where you are setting value in local storage , instead of putting there do a ajax call to any actionresult function on server and set the value in session. Later on fetch it on server side. Again if you want that value client side you need to do ajax call again and get it from server side function in controller.
ok, so if I understand correctly, you login and create a token then from your MVC controller you want to call API endpoints and use the stored token for that.
The code you posted seems to be what exists in your MVC controller.
using (var client = new HttpClient())
{
//here retrieve the token from where you stored it
string accessToken = "whatever";
client.BaseAddress = new Uri("http://localhost:59983/api/flight");
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
var responseTask = client.GetAsync("flight");
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<IList<tblFlight>>();
readTask.Wait();
flights = readTask.Result;
}
else
{
flights = Enumerable.Empty<tblFlight>();
ModelState.AddModelError(string.Empty, "Server error. Please contact administrator.");
}
}
Now, if you call the API endpoint directly from javascript then at that point you will need to have it available to your client so in theory. What you could do is store the token in client side storage as well so you can retrieve it when you need to and I can see you're already doing it on the client side.
If you need it in your MVC controller, then get it from session and pass it through to your API endpoint. In this case, you can use an initial extra call, you get your token on client side anyway so after that just call an extra MVC endpoint, pass the token to it and save it in session. This way to have it both on client side and backend side should you need that.
The MVC, Web API combo is a bit of a bastardization of everything. The reason is that MVC obviously has access to Session, while Web API is supposed to be stateless, thus no Session access. In theory a Web API endpoint which is part of an MVC application can get access to the Session object, although that is something that I would avoid doing. I prefer to keep Web API as a completely separate project but I know that's not always possible.

Angularjs $http Service POST, PUT and GET

I am developing application in AngularJS. But I still not so clear the difference of POST, PUT and GET. Usually I use $http GET when I get data from server when server side does not require any front end data to return data to client side as below.
$http.get(configSettings.baseUrl +"retrive_user.php").success(function (data) {
}).error(function() {
console.log("error");
});
When I am using POST is when I server side require front end data in order to return data to client side as following.
$http({
url: configSettings.baseUrl + "insert_message.php",
method: "POST",
data: {
'username': username,
'messageContent' : messsageContent,
'sender_id': usernameID,
'subscribeChannel' : subscribeChannel,
'attachmentType' : attachmentType,
'event' : 'chat_message'
}
}).success(function(response) {
console.log(response);
}).error(function(response) {
console.log(response);
})
});
Even, I want to delete data or edit data in my MySQL database I am using POST method in angularjs as above and then in my PHP server side, I do like following to get data.
$chat_info = file_get_contents("php://input");
$chat_request = json_decode($chat_info,true);
#$username = $chat_request['username'];
#$messageContent = $chat_request['messageContent'];
#$sender_id = $chat_request['sender_id'];
#$subscribeChannel = $chat_request['subscribeChannel'];
#$attachmentType = $chat_request['attachmentType'];
#$event = $chat_request['event'];
I don't know whether this is a correct practice in RESTful API. I understand the difference between POST and GET. I my server side scripting, I just need to get data from client side in order to Create, Update, Read and Delete data from database. What so special about PUT, DELETE and PATCH in RESTful API?
HTTP verbs are probably one of the most cryptic things about the HTTP protocol.
PUT replace the ENTIRE RESOURCE with the new representation provided or you can say that if user want to add new record, he should use PUT.
On the other hand PATCH => As the name said its a kind of patch to update a piece of record. If user can only wants to update a partial record, say just an email address, he should use PATCH.
As PUT method can update all the record so it need more bandwidth or handle full resources instead on
partial. So PATCH was introduced to reduce the bandwidth.
For example :- lets say I am sending new record to server i.e,
{ "first": "Anand Deep", "last": "Singh" }
So I will use Put because I am adding new record. But here has one problem with Put request that when I will use PUT, I have to send all two parameters that is first and last again. so it is mandatory to send all value again
But Patch only send the data which user want to update and it won't effecting or changing other data.So no need to send all value again.
So PUT for creating new record and PATCH is for updating existing record.
Same for DELETE, its tell to server that this request should delete the record which pass it to server.
For more details click on below image or this URL :-

Pebble.js ajax request with post data. No data in request

I just started fiddeling with pebble.js for a prototype. I have to make a connection to a server and send user data from the pebble (login information) to the server for a handshake and send back data from the server to the pebble. I am using pebble.js because its easy for prototyping.
Now I am using the ajax library (http://developer.getpebble.com/docs/pebblejs/#ajax) to setup the connection. I have the following code:
ajax(
{
url: URL,
method: 'post',
type: 'json',
data: {
auth : 'test'
}
},
function(data) {
// Success!
console.log(JSON.stringify(data));
},
function(error) {
// Failure!
console.log('no response');
}
);
In PHP on the server I get the complete header information by apache_request_headers(); and send it to the pebble with echo json_encode(apache_request_headers());
This results in an output of console.log(JSON.stringify(data))
{"Host":"192.168.0.113","Content-Type":"application/json","Accept":"*/*","Connection":"keep-alive","Cookie":"v2ci_session=55MmpPmzb2cvBWiq3VNgneHexYzBtIFr46Ycb94s2KNKwmnz%2FStJq3euLpUSuBmbsKmKou2915ZR5Cp%2FA7xXnK7FO5EHcnem3Xi6gLpAJPXCF51sQxVQn%2BP1fAmlDqEzSnZEVkbhAO3LkZzALdnjzUc2SPyRCdVx70xAnkohQVH%2BuaU7qZtlCtYwJ7MYQqwa1%2BXuPfw9Vb7vgduYqoWMB%2FVIab5uDPe1KnIxZ08reU1PHVTWXcXXyGCEwmYfCYDkXZSIH%2FcnM%2B4oKAu3kEalGX9jxEVvC6VKz4mAdg7O5Q4Ns%2BEKyTR5VqrpisfZcY2VWOX8ipjCuYMTTosY9Lm%2F0qSpU4P%2B2ObuXCbsJIYviK2EsQqj6%2BWNo0L3DEK6L2N7","User-Agent":"PebbleApp/20141016231206 CFNetwork/711.1.12 Darwin/14.0.0","Accept-Language":"nl-nl","Accept-Encoding":"gzip, deflate","Content-Length":"6"}
As you can see no data is send within the request.
Anyone have an idea why no data is send with the request?
Solved
I was able to solve it through the github of pebblejs. For people with the same problem:
When the 'type' is set to 'json' the ajax library does not only expect the response to be json, but also the data that is posted is posted as json. If you want to gather this data in an array in PHP use the following code:
json_decode(file_get_contents('php://input'), true);

PUT and POST Request of .save() of Backbonejs model

How to be confirmed whether a backbonejs .save() is sending PUT request ?? I checked my server side, which is working good, there is no problem in server side. But my .save() is not working.
Here is my model of backbone
define(['underscore','backbone'],function(_,Backbone)
{
var my_model = Backbone.Model.extend(
{
urlRoot: "http://localhost/back/server_file.php/number"
});
return my_model;
});
Here is how I am using .save()
var my_data = {
id: data.id,
code: data.code
};
var My_model = new my_model();
My_model.save(my_data,
{
success: function(response)
{
alert('Yes');
},
error: function(response)
{
alert('No');
}
});
I think my .save() is sending POST request to server.
UPDATE
I think I could find out my problem. I am describing that here.
What I would like to do
I would like to send 2 parameters from backbonejs model to server side script (I am using PHP SLIM Framework). Based on those 2 parameters server side script update a record's(2 field of this record match with those 2 parameters ) another field with a static parameter at database.
What backbonejs provide (As I think )
Backbonejs has a model with id as JSON format. Backbonejs sends PUT request to server side script. Server side script just dump (update) the data(which was as JSON format,like a bundle) to the database with matching id. Serer side script would not like to look inside the data.
I am getting (from network tab of firebug) my PUT request URL is like http://localhost/back/server_file.php/number/1 (This is the id) . On the other hand I would like to get URL is like http://localhost/back/server_file.php/number/1 (id the first parameter)/456 (Second parameter).
If I am right, anyone could say how can I implement my plan??
This should work,
My_model.set(my_data);
My_model.save(null, {
wait : true,
url : "http://localhost/back/server_file.php/number/1/456",
success : function(response){
},
error : function(e){
}
});
You can debug the request being sent in network tab of Chrome Developer Tools or you can use a network tool like Fiddler to see all requests.
Refer the attached on where to see the request method being used.

How to send data in request body with a GET when using jQuery $.ajax()

The service API I am consuming has a given GET method that requires the data be sent in the body of the request.
The data required in the body is a list of id's separated by hypen and could potentially be very large and thus it must be sent in the body otherwise it will likely foobar somewhere in the browsers/proxies/webservers etc chain. Note I don't have control over the service or API so please don't make suggestions to change it.
I am using the following jQuery code however observing the request/response in fiddler I can see that the "data" I am sending is ALWAYS converted and appended to the query string despite me setting the "processData" option to false...
$.ajax({
url: "htttp://api.com/entity/list($body)",
type: "GET",
data: "id1-id2-id3",
contentType: "text/plain",
dataType: "json",
processData: false, // avoid the data being parsed to query string params
success: onSuccess,
error: onError
});
Anyone know how I can force the "data" value to be sent in the body of the request?
In general, that's not how systems use GET requests. So, it will be hard to get your libraries to play along. In fact, the spec says that "If the request method is a case-sensitive match for GET or HEAD act as if data is null." So, I think you are out of luck unless the browser you are using doesn't respect that part of the spec.
You can probably setup an endpoint on your own server for a POST ajax request, then redirect that in your server code to a GET request with a body.
If you aren't absolutely tied to GET requests with the body being the data, you have two options.
POST with data: This is probably what you want. If you are passing data along, that probably means you are modifying some model or performing some action on the server. These types of actions are typically done with POST requests.
GET with query string data: You can convert your data to query string parameters and pass them along to the server that way.
url: 'somesite.com/models/thing?ids=1,2,3'
we all know generally that for sending the data according to the http standards we generally use POST request.
But if you really want to use Get for sending the data in your scenario
I would suggest you to use the query-string or query-parameters.
1.GET use of Query string as.
{{url}}admin/recordings/some_id
here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.
2.GET use of query string as{{url}}admin/recordings?durationExact=34&isFavourite=true
here the durationExact ,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.
3.GET Sending arrays
{{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]
and you can access those array values at server side like this
let osValues = JSON.parse(req.query.os);
if(osValues.length > 0)
{
for (let i=0; i<osValues.length; i++)
{
console.log(osValues[i])
//do whatever you want to do here
}
}
Just in case somebody ist still coming along this question:
There is a body query object in any request. You do not need to parse it yourself.
E.g. if you want to send an accessToken from a client with GET, you could do it like this:
const request = require('superagent');
request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => {
if (err) throw new Error(err);
console.log(res);
});
The server request object then looks like {request: { ... query: { accessToken: abcfed } ... } }
You know, I have a not so standard way around this. I typically use nextjs. I like to make things restful if at all possible. If I need to make a get request I instead use post and in the body I add a submethod parameter which is GET. At which point my server side handles it. I know it's still a post method technically but this makes the intention clear and I don't need to add any query parameters. Then the get method handles a get request using the data provided in the post method. Hopefully this helps. It's a bit of a side step around proper protocol but it does mean there's no crazy work around and the code on the server side can handle it without any problems. The first thing present in the server side is if(subMethod === "GET"){|DO WHATEVER YOU NEED|}

Categories

Resources