Im trying to load the content of a JSON File into an variable.
Before, the variable looked something like this:
var Data = {
teams : [
["Team 1", "Team 2"],
["Team 3", "Team 4"]
],
results : [
[[1,2], [3,4]],
[[4,6], [2,1]]
]}
Now I have a JSON File looking something like this:
{"teams":[["Team 1","Team 2"],["Team 3","Team 4"],"results":[[[[1,2],[3,4]],[[4,6],[2,1]]]}
Now I want that the the content of the JSON File is stored in the Data Variable before. I tried it with Ajax which looks like this:
$.ajax({
type: "GET",
dataType : 'json',
async: true,
url: 'data.json',
success: function(data) {
console.log(data)
var Data = data
},
});
Console.log works perfect, but the Data is not saved in the variable and I'm getting the error: Uncaught ReferenceError: Data is not defined.
I also tried it with var Data = JSON.parse(data), but this doesn't seem to work either.
And now I'm stuck without any clue.
Thanks for help in advance.
I'm not sure what your code looks like after the ajax call, but I'm guessing the the code where you are using Data is after the ajax call. ajax is asynchrounous. That means that your code doesn't wait for it to finish before moving on. Any code that needs to wait until after it's done fetching the data, you can put in the .success function. Also, it's worth noting that success only gets called when the ajax request is successful. If you want to handle errors, you can use .error Something like this should work:
$.ajax({
type: "GET",
dataType : 'json',
async: true,
url: 'data.json',
success: function(data) {
console.log(data)
var Data = data;
// Anything that needs to use Data would go inside here
},
error: function(err) {
// handle errors
console.error(err);
}
});
// Any code here will not wait until `Data` is defined
// console.log(Data) // error
Related
So I am trying to post some some data from one PHP file to another PHP file using jquery/ajax. The following code shows a function which takes takes data from a specific div that is clicked on, and I attempt to make an ajax post request to the PHP file I want to send to.
$(function (){
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
const sha_obj = JSON.stringify({"sha": sha_id});
$.ajax({
url:'commitInfo.php',
type:'POST',
data: sha_obj,
dataType: 'application/json',
success:function(response){
console.log(response);
window.location.replace("commitInfo");
},
error: function (resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
Then on inside the other php file 'commitInfo.php' I attempt to grab/print the data using the following code:
$sha_data = $_POST['sha'];
echo $sha_data;
print_r($_POST);
However, nothing works. I do not get a printout, and the $_POST array is empty. Could it be because I am changing the page view to the commitInfo.php page on click and it is going to the page before the data is being posted? (some weird aync issue?). Or something else? I have tried multiple variations of everything yet nothing truly works. I have tried using 'method' instead of 'type', I have tried sending dataType 'text' instead of 'json'. I really don't know what the issue is.
Also I am running my apache server on my local mac with 'sudo apachectl start' and running it in the browser as 'http://localhost/kanopy/kanopy.php' && 'http://localhost/kanopy/commitInfo.php'.
Also, when I send it as dataType 'text' the success function runs, but I recieve NO data. When I send it as dataType 'json' it errors. Have no idea why.
If anyone can help, it would be greaat!
You don't need to JSON.stringify, you need to pass data as a JSON object:
$(function() {
$(".commit").on('click', function() {
const sha_id = $(this).data("sha");
const sha_obj = {
"sha": sha_id
};
$.ajax({
url: 'commitInfo.php',
type: 'POST',
data: sha_obj,
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
And on commitInfo.php, you have to echo string on json format
=====================================
If you want to redirect to commitInfo.php you can just:
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
window.location.replace("commitInfo.php?sha=" + sha_id );
});
Sorry for the confusing title, basically I have a json file that looks like this that points to other locations:
{
"link": [
{
"href": "some-external-resource",
"title": "services-path"
}
]
}
My real problem is getting the href of the object to not load asynchronously into the Angular service. The following is my request to the above json file:
var servicesPath = $http({
url: 'resource-directory.json',
method: "GET"
}).success(function(data){
return $filter('filter')(data.link, {title: "services-path"})[0].href;
});
console.log(servicesPath);
I know what is being returned is what I want, but the console log returns the standard "then, catch, finally, success, error" object functions, meaning the data isn't there when I need it. How can I manipulate my request so the variable contains the information?
Since you have an async call, the value would be returned when the call is finished (successfully)
$http({
url: 'resource-directory.json',
method: "GET"
}).success(function(data){
console.log('response data', data);
var theHref = $filter('filter')(data.link, {title: "services-path"})[0].href;
console.log('theHref', theHref); // value shows here
}).error(function(errorResp){
console.log('error');
});
I have a list containing news articles in the backend of a site which is then displayed on a homepage. I'd like the homepage to always display the most recent news.
I've never used AJAX before but in pseudo it would need to do the following:
call the homepage using an AJAX-get
Compare the article div with the same div from the AJAX-get.
If the AJAX-get has different content inside the div, display that
Can I do this with Jquery load, or do I need to go into AJAX for this functionality. and if so, could anyone give me a hand with the AJAX itself
trying to use AJAX, i have started using the following code, to no avail
$.ajax({
url: ctx.HttpRoot,
data: { "id": $("newsSliderWrapper").attr("id") },
success: function (data) {
data = $(data).find('div#newsSliderWrapper')
alert(data)
},
error: function () {
// your error logic
alert("AJAX failed");
}
})
AJAX in your case will do the following:
Ajax call will send the recent article ID to the server.
The server will compare the article ID. If the article ID is different, then the server will return the new article content. If the id is same, return different status message.
Ajax call will simply render the content
So
$.ajax({
url : "backendurl",
data : {"id" : $("recentarticleDivId").attr("id")},
// id must be the article ID which you need to match
success : function(data) {
$("#articleDivId").html(data);
},
error : function() {
// your error logic
}
})
$.ajax({
url: "homepage.php",
type: "GET",
data: { id : article_id },
success:function(data){
console.log(data);
// your logic
},
error:function(){
}
});
myscript.js below is outputing:
[{"orcamento":"10","atual":"20","desvio":"","data":"2015-01-01","nome_conta":"BBB","nome_categoria":"abc","nome_entidade":"def"}]
myscript.js:
if (addList.length) {
$.ajax($.extend({}, ajaxObj, {
data: { "addList": JSON.stringify(addList) },
success: function (rows) {
$grid.pqGrid("commit", { type: 'add', rows: rows });
},
complete: function () {
$grid.pqGrid("hideLoading");
$grid.pqGrid("rollback", { type: 'add' });
$('#consola').text(JSON.stringify(addList));
}
}));
}
The JSON data above has to be sent to my script.php below:
if( isset($_POST["addList"]))
{
$addList = json_decode($_POST["addList"], true);
var_dump ($addList);
echo "test";
exit();
}
Although the data is correct and myscript.php is being called it isn't returning anything. I get:
NULLtest
I tried using GET, instead of POST but the result is the same, what is wrong with the code above?
EDIT:
Here's the ajaxObj used in the ajax request:
var ajaxObj = {
dataType: "json",
url:"../myscript.php",
type: "POST",
async: true,
beforeSend: function (jqXHR, settings) {
$grid.pqGrid("showLoading");
}
};
From the PHP Docs on json_decode:
NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
So it is most likely that there is some error in your JSON data that is preventing json_decode from parsing it correctly, I've ran that snippet through jsonlint and it does say that it's valid JSON, but it's worth checking a larger sample of the data you send to the server for inconsistencies.
Other than that, is there any reason that you are calling JSON.stringify on the data object prior to sending to the server? I would try just sending the object itself as the data parameter of your AJAX call like so:
$.ajax($.extend({}, ajaxObj, {
data: { "addList": addList },
success: function (rows) {
$grid.pqGrid("commit", { type: 'add', rows: rows });
},
complete: function () {
$grid.pqGrid("hideLoading");
$grid.pqGrid("rollback", { type: 'add' });
$('#consola').text(JSON.stringify(addList));
}
}));
And see if that helps:
EDIT
I should have noticed in my original answer, you will not need to call json_decode on your posted data, jQuery encodes the data as post parameters correctly for you; It should be accessible within your PHP script as an associative array, try replacing your current var_dump statement in your PHP var_dump($_POST['addList'][0]['orcamento']); and you should be good to go.
First of all, be sure you are posting to a php file, use firebug or similar tools to track your script..
I don't see the part you defined the target PHP file on your javascript file..
A regular javascript code can look like this :
jQuery.ajax({
type : "post",
dataType : "json",
url : 'target.php',
data : {foo:bar },
success: function(response) {
// do something with response...
}
});
If you see that you are posting to the right php file the right parameters on firebug, try to use $_REQUEST if $_POST not working..
Firebug will show you the response of PHP file.. so do a print_r($_REQUEST['addList']) to see what is going on...
I have a PHP function that echoes out JSON data and pagination links. The data looks exactly like this.
[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
Previous
Next
To get these data, I would use jQuery.ajax() function. My code are as follow:-
function loadData(page){
$.ajax
({
type: "POST",
url: "http://sandbox.dev/favourite/test",
data: "page="+page,
success: function(msg)
{
$("#area").ajaxComplete(function(event, request, settings)
{
$("#area").html(msg);
});
}
});
}
Using jQuery, is there anyway I can scrape the data returned from the AJAX request and use the JSON data? Or is there a better way of doing this? I'm just experimenting and would like to paginate JSON data.
It's better to not invent your own formats (like adding HTML links after JSON) for such things. JSON is already capable of holding any structure you need. For example you may use the following form:
{
"data": [
{"name": "John Doe", "favourite": "cupcakes"},
{"name": "Jane Citizen", "favourite": "Baked beans"}
],
"pagination": {
"prev": "previous page URL",
"next": "next page URL"
}
}
On client-side it can be parsed very easily:
$.ajax({
url: "URL",
dataType:'json',
success: function(resp) {
// use resp.data and resp.pagination here
}
});
Instead of scraping the JSON data i'd suggest you to return pure JSON data. As per your use case I don't think its necessary to write the Previous and Next. I am guessing that the first object in your return url is for Previous and the next one is for Next. Simply return the below string...
[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
and read it as under.
function loadData(page){
$.ajax
({
type: "POST",
url: "http://sandbox.dev/favourite/test",
dataType:'json',
success: function(msg)
{
var previous = msg[0]; //This will give u your previous object and
var next = msg[1]; //this will give you your next object
//You can use prev and next here.
//$("#area").ajaxComplete(function(event, request, settings)
//{
// $("#area").html(msg);
//});
}
});
}
This way return only that data that's going to change not the entire html.
put a dataType to your ajax request to receive a json object or you will receive a string.
if you put "previous" and "next" in your json..that will be invalid.
function loadData(page){
$.ajax({
type: "POST",
url: "http://sandbox.dev/favourite/test",
data: {'page':page},
dataType:'json',
success: function(msg){
if(typeof (msg) == 'object'){
// do something...
}else{
alert('invalid json');
}
},
complete:function(){
//do something
}
});
}
and .. in your php file, put a header
header("Content-type:application/json");
// print your json..
To see your json object... use console.log , like this:
// your ajax....
success:(msg){
if( window.console ) console.dir( typeof(msg), msg);
}
Change your json to something like this: (Use jsonlint to validate it - http://jsonlint.com/)
{
"paginate": {
"previous": "http...previsouslink",
"next": "http...nextlink"
},
"data": [
{
"name": "JohnDoe",
"favourite": "cupcakes"
},
{
"name": "JaneCitizen",
"favourite": "Bakedbeans"
}
]
}
You can try this :-
var jsObject = JSON.parse(your_data);
data = JSON.parse(gvalues);
var result = data.key;
var result1 = data.values[0];