I have method to update notification and when update it return number of notification and content of notification with json type
{
"friend_request": 4,
"request": [{
"user_id": "1",
"picture": "/home/sepdau/",
"name": "Le Chanh"},
{
"user_id": "2",
"picture": "",
"name": "Yii PHP"},
{
"user_id": "4",
"picture": "13366396884.jpg",
"name": "Minh Le"},
{
"user_id": "11",
"picture": "",
"name": "Thang Phan"}]
}
When I receive I update number of notification success
function updateNotification(){
$.ajax({
url: '/nevergiveup/index.php/site/updatenotification',
type: "post",
dataType: "json",
success: function(data){
if(data.friend_request>0){
$(".zingcounter").text(data.friend_request); //update number of nofitcation
// load the template file, then render it with data
var html = new EJS({url: '/nevergiveup/jstemplates/friend_request.ejs'}).render(data);
//$("#frlist").append(html);
//$(html).replaceAll('#replacehere');
$('#replacehere').replaceWith(html); // update content of notification
}
setTimeout(updateNotification,10000);
},
error: function(){
setTimeout(updateNotification,10000);
}
});
}
I use EJS to build a template of content
I have a <div id="replacehere"> to replace my content here
I use $('#replacehere').replaceWith(html); to replace but it success when first request in 10s after
I see json data receive has a new content and number of notification has change but content not change.
How to change it when receive new content.
Guess you need just use
$('#replacehere').html(html);
otherwise it will remove #replacehere div... and second request wont find it to put content in...
Related
I am new to JQuery. I am trying to develop a small travel website for checking PNR. I am currently using an API provided by one of the travel company. As soon as we hit the API Url, browser displays the result in JSON format.
I am using JQuery, JS and HTML. I want to know how to store the JSON value (in string format) retrieved from hitting an API, in a variable and use it later in the script.
PS: Though I have found many answer in Stackoverflow but none of the result works. Kindly help with the appropriate value.
Sample Code: (I am using one textbox and button)
<script>
function search_pnr(){
var pnr = $('#input_pnr').val();
var result;
var url = "http://api website/pnr"+pnr;
//Suggest the code here, to fetch the result from url and store in the variable result.
</script>
<input type="text" placeholder="Enter PNR" id ="input_pnr"/>
<input type="button" value="Search PNR" onclick="search_pnr()"/>
Below is the JSON value getting from server
{"to_station": {"lng": 77.2888291, "name": "ANAND VIHAR TERMINAL", "lat": 28.6118176, "code": "ANVT"}, "total_passengers": 1, "pnr": "6717552286", "journey_class": {"name": null, "code": "3A"}, "train": {"classes": [{"available": "N", "name": "SECOND AC", "code": "2A"}, {"available": "Y", "name": "THIRD AC", "code": "3A"}, {"available": "N", "name": "SECOND SEATING", "code": "2S"}, {"available": "N", "name": "FIRST AC", "code": "1A"}, {"available": "Y", "name": "AC CHAIR CAR", "code": "CC"}, {"available": "N", "name": "FIRST CLASS", "code": "FC"}, {"available": "N", "name": "3rd AC ECONOMY", "code": "3E"}, {"available": "N", "name": "SLEEPER CLASS", "code": "SL"}], "days": [{"code": "MON", "runs": "N"}, {"code": "TUE", "runs": "Y"}, {"code": "WED", "runs": "N"}, {"code": "THU", "runs": "Y"}, {"code": "FRI", "runs": "N"}, {"code": "SAT", "runs": "Y"}, {"code": "SUN", "runs": "N"}], "number": "22405", "name": "BGP-ANVT GARIB RATH"}, "from_station": {"lng": 86.9828131, "name": "BHAGALPUR", "lat": 25.2494829, "code": "BGP"}, "passengers": [{"booking_status": "CNF/G12/36/GN", "no": 1, "current_status": "CNF/-/0/GN"}], "reservation_upto": {"lng": 77.2888291, "name": "ANAND VIHAR TERMINAL", "lat": 28.6118176, "code": "ANVT"}, "response_code": 200, "boarding_point": {"lng": 86.9828131, "name": "BHAGALPUR", "lat": 25.2494829, "code": "BGP"}, "debit": 3, "doj": "25-08-2018", "chart_prepared": false}
Kindly also help how to read both the objects and array in the given JSON.
You can use ajax to fetch the result from the url
var result;
var url = "http://api website/pnr"+pnr;
$.ajax
({
url: url,
type: 'GET',
dataType: 'json',
success: function(data)
{
result = data;
alert(JSON.stringify(data));
}
});
You just need to parse JSON and how to read each object. This should give you good start
$.ajax({
type: "GET",
url: "http://api_website/pnr"+pnr,
data: data,
success: function(resultData) {
console.log(resultData);
var to_station = resultData.to_station;
var trains = resultData.train;
var passengers = resultData.passengers;
alert("Station Name: "to_station.name);
alert("Passengers: "passengers.booking_status);
},
error(function() {
alert("Something went wrong");
}
});
You can read more bout how to read JSON here.
$.ajax({
method: "GET",
url: url
})
.done(function( data ) {
console.log(data)
// see what properties you need from data object and save it to variable
var data = data
});
First thing,
Use a javascript file....API calls are better off done in a js file rather than in a script tag.
Second thing, if you want to store it in a json format,
you can store it in a value like the way you have declared your url variable.
Since, you are fetching the data, I'm assuming this is a get request, you can find more information about them in the following links -
https://www.sitepoint.com/ajaxjquery-getjson-simple-example/
https://api.jquery.com/jquery.get
Also, if the data isn't very sensitive, you can store it in the local storage of your browser, so that you can access it later on in other web pages as well.
In your current json data, I would say that if you declare it to a variable say
apiResult
Your to_station would be apiResult.to_station, the lng value would be apiResult.to_station.lng and so on.
Hope any of this helps, and good luck.
Everyone already added the AJAX examples, so I will leave that out.
So for reading the objects, you just have to parse what you need through various means, if you know what the object looks like and exactly what you need you can use dot notation. If you are looking to grab things more dynamically you can using higher order functions or for loops as well as Object prototypes example getting the entries (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries)
You might consider using localStorage for storing the information depending on what you are using it for which is a built-in Web API
here is MDN's definition
The read-only localStorage property allows you to access a Storage
object for the Document's origin; the stored data is saved across
browser sessions. localStorage is similar to sessionStorage, except
that while data stored in localStorage has no expiration time, data
stored in sessionStorage gets cleared when the page session ends —
that is, when the page is closed.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
You may want to use AJAX. You have to be sure how the server will retrieve the data. If it is in a JSON format do:
<script>
function search_pnr(){
var pnr = $('#input_pnr').val();
var result;
var url = "http://api website/pnr"+pnr;
$.getJSON( url, function( data ) {
result = data;
$.each( data, function( key, value ) {
// whatever with keys and values if needed
}
);
}
</script>
Ref w3 Schools
JQuery official website
All current browsers have native JSON support built in. So as long as you're not dealing with prehistoric browsers like IE6/7 you can do it just as easily as that:
var j={"name":"binchen"};
JSON.stringify(j); // '{"name":"binchen"}'
For more info kindly visit link
I have a json like
var rules=[
{
"ruleId": "1234",
"version": "R1234",
"name": "Usage crossing 50MB",
"description": "Find usage more than 50mb",
"active": true,
"created_by": "Rahul",
"create_date": "2015-08-18",
"modified_date": "2015-08-22",
"modified_by": "Subho",
"category": {
"name": "High Usages Rule",
"id": "26"
}
]
Now I want to call a java page or function where i want to get these data so i put it on DB.
this is my controller
(function(){
"use strict";
angular
.module("RulesEngine")
.controller("RulesEditCtrl",
["rules","$state",RulesEditCtrl]);
function RulesEditCtrl(rules, $state){
var vm=this;
vm.rules=rules;
vm.submit=function(){
vm.rules.$save(function (data) {
toastr.success("Save Successful");
vm.ruleJson=data;
});
console.log(vm.ruleJson);
//in yhis vm.ruleJSON holds the the updated json. it prints fine in console.log
}
}
}());
I want to call a function using $ajax or $http.get() to call a function insertEntry() which is in a java page named ShowJson.java. please help me to call the function and send the data.
I tried
$.ajax({
url : "insertEntry?rule="+vm.ruleJson,
type: 'POST',
dataType : "json",
success : function(data) {
console.log("inserted");
},error : function(data) {
}
});
But its not working...
How to write the underlying code given in the Moxtra API in jQuery or JavaScript
POST /v1/UiaduESWsbzFoK9TOldC6zF/binders
{
"name": "My First Binder"
}
{
"code": "RESPONSE_SUCCESS",
"data": {
"id": "B7U3ze39oO08PYO70973lX6",
"name": "My First Binder",
"revision": 3,
"created_time": 1342813061602,
"updated_time": 1342813061602
}
}
Assuming you want to POST the first object and receive the second object as a successful response, here's how you'd do it with jQuery's shorthand AJAX POST function:
var data = {"name": "My First Binder"};
$.post("/v1/UiaduESWsbzFoK9TOldC6zF/binders", data, function(response) {
// Response object contains your response from the server
console.log(response);
});
I am trying to make a cross domain request to send/recieve some data. I can't get past the object error. Before I was getting the No Transport Error but adding Query.support.cors = true; solved this issue.
var url = "http://CROSSDOMAINSERVER:PORT/Service1.svc/GetDataUsingDataContract";
$.ajax({
type: 'GET',
url: url,
data: 'tool=1&product=Some%20Product&details=9&bogus=should%20not%20pass%20validation',
datatype: "jsonp",
contentType: "application/json",
success: function (response) {
alert(response.data);
},
error: function (error) {
alert(error.statusText);
}
});
If I type the url out in a browser:
http://CROSSDOMAINSERVER:PORT/Service1.svc/GetDataUsingDataContract?&tool=1&product=Some%20Product&details=9&bogus=should%20not%20pass%20validation
I get the correct response.
{"d":{"__type":"ClientSideData:#ProdResourceToolService","details":"9","product":"Some Product","result":"1","site":"Somewhere, SD","systime":"2\/6\/2013 2:50:20 PM","team":"0000000000","tool":"1","user":"username"}}
When I use ajax it does not submit it to the database or return data, just object error. Does anyone have any suggestions on how to get around this?
I should also specify if I remove http://CROSSDOMAINSERVER:PORT/ from var url when debugging locally I get the correct json response. Why does cross domain not work?
This is your current response:
{
"d": {
"__type": "ClientSideData:#ProdResourceToolService",
"details": "9",
"product": "Some Product",
"result": "1",
"site": "Somewhere, SD",
"systime": "2/6/2013 2:50:20 PM",
"team": "0000000000",
"tool": "1",
"user": "username"
}
}
This is a valid JSON string. However, its not valid JSONP. If possible, make your service wrap the json in a function:
responseFunc({
"d": {
"__type": "ClientSideData:#ProdResourceToolService",
"details": "9",
"product": "Some Product",
"result": "1",
"site": "Somewhere, SD",
"systime": "2/6/2013 2:50:20 PM",
"team": "0000000000",
"tool": "1",
"user": "username"
}
});
And in your $.ajax() call, add a property: jsonpCallback: 'responseFunc'.
Also, I would suggest passing the data as an object:
data: { tool: 1, product: 'Some Product' } //etc...
If you can access the service from the serverside without any issues you could create a httphandler (.ashx for example) and let it generate the JSON for you. Then you wouldn't have to deal with the cross domain issues on the client side.
I have a json object that I'm loading from wordpress using the JSON API plugin. When I load the json object and try to log out the parts of it, it seems like it treats every single character as its own object so the loop returns me a couple thousand objects all with item in it which is a single character. This is my first time using json so idk if i'm missing a step here. this is the code I'm using so far.
function getProjInfo(theId){
$.ajax({// calling the ajax object of jquery
type: "GET",// we are going to be getting info from this data source
url: 'http://testing.charter21.com/api/get_post/?post_id='+ theId,//the datasource
dataType: "application/json",
success: function(data){
parseJson(data);
}, // what happens when it is successful at loading the XML
error: function(){
alert("error");
}
});
}//end of the function
function parseJson(inData){
postInfo = inData;
$.each(postInfo, function(index, value){
console.log(this);
});
}
the json looks like this:
{
"status": "ok",
"count": 10,
"count_total": 19,
"pages": 2,
"posts": [
{
"id": 175,
"type": "post",
"slug": "home-page-slider",
"url": "http:\/\/testing.charter21.com\/uncategorized\/home-page-slider\/",
"status": "publish",
"title": "Home Page slider",
"title_plain": "Home Page slider",
"content": "<p>The cImages in here are the images that are in the slider on the home page this content in this box will not show up. Its only here as a guide.<\/p>\n",
"excerpt": "The cImages in here are the images that are in the slider on the home page this content in this box will not show up. Its only here as a guide.",
"date": "2011-01-25 10:40:25",
"modified": "2011-01-25 10:40:25",
"categories": [],
"tags": [],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [],
"attachments": [],
"comment_count": 0,
"comment_status": "open"
}
so basically instead of giving me "status" as an key and "ok" as a value, i get "s" as an object with an index 0 that has a value of "s" for every single character in the json object. Any help on this matter would be appreciated.
You need to set dataType:json in your $.ajax() request so that jQuery converts the JSON-formatted string into a JavaScript object for you to process as such. You're currently using application/json which is a mime type, and not a valid value for this field in a jQuery request.
In your case you can even try data = eval(data) , this javascript statement should convert your string to json object.
Use the Jquery function:
data = $.parseJSON(data);
before using $.each.
The way I solved it in my AngularJS app is by sending the response from the server (I'm using Node Express) as a JavaScript object, rather than as a string. Nothing else worked for me.
var response = {};
response.error = "Error message";
res.send(response);