I want to get JSON string to my Jquery Mobile App and add that values in to Java-Script array for future use.
here is the structure of the json
{"daily":[{"a":1,"b":3,"c":2,"d":5,"e":3}]}
here is the link for above daily_report
here is my code
$(document).on('pagebeforeshow', '#pageone', function(e, data){
$.ajax({url: "http://iilsfa.br0s.info/Dashboard/get_daily_report.php",
dataType: "json",
async: true,
success: function (result) {
ajax.parseJSONP(result);
},
error: function (request,error) {
alert('No Network!');
}
});
});
var ajax = {
parseJSONP:function(result){
$.each( result, function(i, row) {
$('#output').append('<li><h3>' + row.a+ '</h3></li>');
// I Need to add json elements to an array here
});
$('#output').listview('refresh');
}
}
#output is a tag located in #pageone
Above code is not working.please show me how to fix it..thank you..
$.ajax({url: "http://iilsfa.br0s.info/Dashboard/get_daily_report.php",
dataType: "json",
async: true,
success: function (result) {
result.daily.forEach(function(el){
$('#output').append('<li><h3>' + el.a+ '</h3></li>');
});
},
error: function (request,error) {
alert('No Network!');
}
});
});
Related
I am using ASP.net MVC, and following is the Html code
$.ajax({
type: "POST",
url: urlAjax,
dataType: 'json',
data: dataValue,
async: false,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
$("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
alert("fail")
}
});
<div id=waitscreen>
//some code
</div>
Code in external js
function _post(someparameter)
{
$.ajax({
type: "POST",
url: urlAjax,
dataType: 'json',
data: dataValue,
async: false,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
$("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
alert("fail")
}
});
}
Also tried adding document ready in above code it is still not working
Above code worked fine and it show and hide as expected, but now I need to repeat ajax call in every page so I decided to move in external JS file now same code is not showing waitscreen.
Things I tried:
Loaded external script in head - Not working
Loaded external script at end of page - Not working
Question: I want to make hide and show work from external JS file
The following code snippet should help you. Tested by including the external JS file in the <head> of the main document and just below the inclusion of jQuery.
// main window
var json = {"key": "value"}
console.log('before calling _post()');
_post(json); // call external JS
// code in external JS say test.js
function _post(someparameter)
{
console.log('external JS called!');
$.ajax({
type: "POST",
url: 'http://www.niketpathak.com',
dataType: 'json',
data: someparameter,
async: true,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
// $("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
//delaying the error callback
setTimeout(function() {
$("#waitscreen").hide();
console.log('after completing the http-request');
}, 500);
}
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=waitscreen>
Waitscreen....
</div>
Also, note that I have used async: true (which is also the default) since setting it to false is deprecated and not a good idea as it blocks the UI.
My ajax code in External.js file,
function _post()
{
var data = {
Email: "a#a.com",
Password:"1111"
}
$.ajax({
type: "POST",
url: "/Home/hello/",
dataType: 'json',
data: data,
async: false,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
$("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
alert("fail")
}
});
}
In my HomeController, I have hello method like this,
[HttpPost]
public ActionResult hello(LoginViewModel data)
{
ViewBag.Message = "Your contact page.";
return Json(data, JsonRequestBehavior.AllowGet);
}
And in my all the views I have the "waitscreen" div.
Now I just reference the External.js file to my _Layout page, I just drag and drop after jquery reference.
<script src="~/Scripts/External.js"></script>
Then in end of the same _Layout page, i just call the method like this,
<script>
_post();
</script>
Everything working properly.
Note: If you have only one parameter in your hello action method and suppose you have written like (int x) then in that case it will through 500 error. Because in your RouteConfig.js its mentioned that, by default the parameter name should be id. So you need to write int id.
Hope its help.
I have a web service which adds an item to the database after being called using JQuery Ajax. The web service returns a string, and I can't manage to pick up only the string part returned. Instead I receive {"d":"The message I want to display"} using alert(data);.
I also tried alert(Object.keys(JSON.parse(data))[0]); which returns d and alert(Object.keys(JSON.parse(data))[1]); or alert(data.d); returns Undefined.Here's what my code looks like
function AddAjaxJQuery() {
var isbn = $('#<%= txtIsbn.ClientID %>').val();
var pdata = { "book": { "Isbn": isbn} };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/BookWebService.asmx/InsertBook",
data: JSON.stringify(pdata),
dataType: 'text',
async: true,
success: function (data, textStatus) {
alert(data);
},
error: function (error) {
alert(data);
}
});
}
If your data is a string, then you should parse it to JSON first:
var dataInJson = JSON.parse(data);
alert(dataInJson.d)
You have to access property d of data (response) so Replace success callback with
success: function (data, textStatus) {
alert(data.d);
},
I have this script that adds elements with data by a get json function.
$(document).ready(function() {
ADD.Listitem.get();
});
It basicly adds a bunch of html tags with data etc. The problem I have is following:
$(document).ready(function() {
ADD.Listitem.get();
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
-
get: function(web) {
AST.Utils.JSON.get("/_vti_bin/AST/ListItem/ListitemService.svc/GetListItem", null, AST.Listitem.renderListitem);
},
renderListitem: function(data) {
$("#Listitem-template").tmpl(data["ListItemResults"]).prependTo(".ListItem-section-template");
}
and here is the json get:
ADD.Utils.JSON.get = function (url, data, onSuccess) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
async: true,
url: url,
data: data,
cache: false,
dataType: "json",
success: onSuccess,
error: ADD.Utils.JSON.error,
converters: { "text json": ADD.Utils.JSON.deserialize }
});
}
The array each loop is not running beacuse the get method is not finished with rendering the Listitem-section-item-title selector so it cant find the selector.
Is there any good solutions for this?
You could change your functions to return the promise given by $.ajax :
ADD.Utils.JSON.get = function (url, data) {
return $.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
async: true,
url: url,
data: data,
cache: false,
dataType: "json",
converters: { "text json": ADD.Utils.JSON.deserialize }
}).fail(ADD.Utils.JSON.error);
}
get: function(web) {
return AST.Utils.JSON.get("/_vti_bin/AST/ListItem/ListitemService.svc/GetListItem", null).done(AST.Listitem.renderListitem);
},
So that you can do
$(document).ready(function() {
ADD.Listitems.get().done(function(){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
});
Callback:
$(document).ready(function() {
ADD.Listitem.get(url,data,function(){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
});
Without callback:
If you cant get the get method to take a callback or return a promise then I think the best way will be to check when its done.
$(document).ready(function() {
ADD.Listitem.get();
var timer = setInterval(function(){
if ($("#thingWhichShouldExist").length>0){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
clearInterval(timer);
}
},50);
});
Retrieve the values and on success, call a function which will push the values into the array.
Also, arr.push($(this.text())); should be arr.push($(this).text());.
I have an ajax call and it retunrs some value. Now i need to check the value in javascript. How can i do it
$('#cm').blur(function () {
var cmnumber = document.forms['myform']['cm'].value;
$.ajax({
type: 'get',
url: "/validatecm/" + cmnumber,
cache: false,
asyn: false,
data: cmnumber,
success: function (data) {
alert(data)
},
error: function (data) {
alert(data)
}
})
});
Now i need to access the "data" in my javascript submitformfunction. Any help wil be appreciated
success: function(data) {
console.log(data);
useInAnotherFunction(data);
}
function useInAnotherFunction(data)
{
...use here
}
If you use console.log(data); you can view clearly data what you have
You are already accessing the data here
alert(data)
If you still want to access it outside your success callback then make it like this
success: function(data) {
YourFunctionCall(data)
}
I need to call an asp.net page from javascript with queryString having Arabic text. It shows me an error when goes online but works smoothly on the local server. When arabic value is small then it works smoothly problem arises when arabic text is in multiple lines.
$.ajax({
url: "Empty/emptyGovt2.aspx",
data: "arKeyword="+encodeURIComponent($("#txt_arKeywords").val(),
success: function(data) {
diaL("Details Updated Successfully");
},
error: function(){
diaL('Error Occurred');
}
});
Dont use get with long and complex datas use post
$.ajax({
url: "Empty/emptyGovt2.aspx",
type:"POST",
data: {
"arKeyword" :$("#txt_arKeywords").val(),
"OrgId" : newParentOfficeID
// etc
},
success: function(data) {
diaL("Details Updated Successfully");
},
error: function(){
diaL('Error Occurred');
}
});
And on the php you can access the values as $_POST['OrgId'] etc
I would suggest you to use POST and dataType:'json' or 'text':
$.ajax({
url: "Empty/emptyGovt2.aspx",
type: 'POST',
data: {"arKeyword" : $("#txt_arKeywords").val()}, //<----json objects
dataType: 'json', //<----dataType
success: function(data) {
// retriev json response
var respData = $.parseJSON(data);
$.each(respData, function(i, item){
console.log(item);
});
diaL("Details Updated Successfully");
},
error: function(){
diaL('Error Occurred');
}
});
and make sure to return json from 'Empty/emptyGovt2.aspx'