Pushing JSON Data into an array? - javascript

I have a PHP script which returns a JSON response like the below
[{"agencyID":"99999", "name":"john", "surname":"doe", "bookings":[{
"ID":"54321", "transactions":[{"desc":"example text"}],
}]
}]
MUST ADD - I HAVE MADE UP THIS JSON - JUST AN EXAMPLE.
How do i push all this information into a JavaScript array from AJAX success block?
I would like to be able to use the information later for example like this -$('#div').append(array.desc);
Content-Type
application/x-www-form-urlencoded; charset=UTF-8

If you are using the jQuery ajax method, you can push the response from your PHP script into an array and use it later. Here's an example:
JavaScript
$.ajax({
url: 'url/to/php/script.php',
dataType: 'JSON',
success: function (data, textStatus, jqXHR) {
var array = [];
array.push(data);
$('#foo').append(array);
}
});

Related

Javascript Convert JSONP data from string to Json object

So i am not sure if i am doing this right.
I want to send markup over HTML (i am trying to create a widget)
Here is the mocky response that i am expecting
so I create a simple jquery get like this
var jsonp_url = "http://www.mocky.io/v2/5c9e901a3000004a00ee98a1?callback=myfunction";
$.ajax({
url: jsonp_url,
type: 'GET',
jsonp: "callback",
contentType: "application/json",
success: function (data) {
$('#example-widget-container').html(data.html)
},
error: function (data) {
alert('woops!'); //or whatever
}
});
then created myFunction
function myfunction(data) {
console.log(data);
}
The problem being that while, i get the response it comes as a string instead of a json or function. i am not sure how to extract the json from this (unless i do string manupulation).
Any pointers would be helpful.
JSFiddle here
P.S. Per https://www.mocky.io/ ,
Jsonp Support - Add
?callback=myfunction to your mocky URL to enable jsonp.
Delete function myfunction.
In the URL, replace callback=myfunction with callback=?.
jQuery will generate a function (your success function) and a function name for you.

Ajax Call in PHP and jQuery

This is my functions.php script containing the following code. The array is encoded into JSON.
functions.php
$final['custom']['main'] = queryCustom($conn, $id);
echo json_encode($final);
My global.js has the following code which makes an AJAX request in jQuery:
$.ajax({
type: "POST",
url: "functions.php", // file to reach Ajax call
dataType: "json",
data: {
action: 'custom',
id: id,
},
success:
function(data) {
setCustom(data.custom);
I want to know what the data contains in function(data)? The setCustom(data.custom), what does this mean here? Can someone provide me an explanation of this please?
data contains an object literal provided by the server side json_encode(). It's been automatically parsed because the data type is set to json.
example:
PHP:
$final['custom']['main'] = queryCustom($conn, $id);
echo json_encode($final);
Will give the following json string (formatted for better understanding):
{
"custom": {
"main":[
{
"symbol":"MAP4",
"official_ID":"112315"
}
]
}
}
The ajax call above is set to datatype json. jQuery knows if this datatype is set, it will automatically parse the string to an object literal.
Javascript:
$.ajax({
type: "POST",
url: "url.php", // file to reach Ajax call
dataType: "json",
success: function(data) {
var main = data.custom;
console.log(main); // returns the child object with "main"
}
});
data contains the initial object, custom is a child object of data and main is a child object of custom.
Success: A function to be called if the request succeeds. The function gets passed three arguments:
Data Returned From The Server
Status
jqXHR (XMLHttpRequest Object)
In your PHP code you've added echo json_encode($final); which will be returned if the request is completed successfully. The response will be passed to data which you can later use in your front-end code.
You can read more about $.ajax() at http://api.jquery.com/jQuery.ajax/

Using JSONP and I have 'ReferenceError: data not defined'

I've got a problem with displaying JSON data called via JSONP. I've got a complex JSON file delivered cross domain via a URL and I'm quite the novice at JSON and ajax. I followed a JSONP article here at https://learn.jquery.com/ajax/working-with-jsonp/ and that worked a treat. Now I am trying to iterate through the JSON object and display data in the HTML page after following this question How do I iterate through this JSON object in jQuery? and I'm not going anywhere. The data is not defined and I'm not sure what I am doing wrong:
// Using LibCal and JSONP
$.ajax({
url: "https://api2.libcal.com/1.0/room_bookings_nickname/?iid=3356&group_id=12306&key=92a47e5c854dee620cca071648c3fc41",
// The name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
// Tell LibCal what we want and that we want JSON
data: {
q: "select Room name,booked timeslots,booking name from LibCal room bookings",
format: "json"
},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});
$.each(data.bookings, function(index, element) {
alert(element.timeslots.room_name);
});
I hope it's an obvious fix to a more advanced user our there :)
Thats because your data object doesn't exist. The data key you're referring to is a on the object you're passing to the $.ajax method.
You need to execute your function inside the success callback in order for it make any sense.
$.ajax({
...
// keep all your original stuff
...
success: function( response ) {
var data = response;
$.each(data.bookings, function(index, element) {
alert(element.timeslots.room_name);
});
}
});
I did the request like this. You need to go one level more to access the array to loop.
var json_url = "https://api2.libcal.com/1.0/room_bookings_nickname/?iid=3356&group_id=12306&key=92a47e5c854dee620cca071648c3fc41"
$.ajax({
url: json_url,
crossDomain:true,
dataType:"jsonp"
}).done(function(response) {
// at the end of request
//Yours --->response.bookings
//Mine --->response.bookings.timeslots
//access the array to loop
var rooms = response.bookings.timeslots;
$.each(rooms, function(index, element) {
create_elem(element.room_name, index);
});
});
Here is a working version in jsFiddle - https://jsfiddle.net/9e746pkh/
Hope this helps.

create jquery array for ajax post

How can I convert the output of drp.getDateRange to an array so that I can post it via AJAX?
I have updated this code to represent the advice given below
<script>
var drp;
var myArray = [];
function makedatepicker() {
drp = $("#myDate").datepicker({});
}
function getRange() {
var data = $("#myOutput").serialize();
console.log("This is the serialized element");
console.dir(data);
$.ajax({
url: "myurl.com",
type: 'post',
data: data,
success: function(response) {
console.log("This is the response from your ajax script");
console.dir(response);
}
});
}
$(document).ready(function () {
makedatepicker();
});
</script>
Update
Note on JSON. The default encoding will be url form encoded. If you want the request to send the data as JSON, you will need to add..
content-type: "application/json; charset=utf-8",
also if you are returning JSON, you should add ...
datatype : "json",
Not sure which scripting language your using on the back end, but if PHP, you can send back array data like this
echo json_encode($myArray);
I will add the JSON stuff to the sample code below.
End Update
If you use .serialize() you an send it as ajax data and it will show up in your post or get array.
If you are working with an array, you might want to use .serializeArray()
You can view an object or array in your developer tools (F12 in Chrome or FF), by using console.dir(someObject);
var data = $("#myOutput").serialize();
console.log("This is the serialized element");
console.dir(data);
$.ajax({
url: "myurl.com",
type: 'post',
datatype : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
beforeSend : function (){
console.log("Before Send: Data looks like..");
console.dir(data);
},
success: function(response) {
console.log("This is the response from your ajax script");
console.dir(response);
console.log("parsing JSON ...");
console.dir($.parseJSON(response));
}
});
Chrome Developer Tools Console, this is where you will see anything that you console.log or console.dir
You can check the JSON that is being sent by clicking the Network tab. Then click the name of the ajax script and it will show you the data being sent. (Also, clicking on the "response" tab will show you what is being sent back by your script.)
In the example below I am sending an ajax request using the above code and it is showing that the data is indeed a JSON object.

Jquery Ajax jsonp request display in console

Please excuse this question but I cant quite get my head around what I am doing wrong, I am trying to make a jsonp request via ajax and jquery - if i look at the response my data shows fine, however I cant get my head around how to display it in the console.
here is my code
$(document).ready(function(){
var jsondata = [];
$.ajax({
type: 'GET',
url: '<myurl with json response in a form of an array >?callback=?',
cache: false,
dataType: 'jsonp',
success: function (data) {
console.log(data);
}
});
});
just to clarify my response shows like this:
[{"content":asdf,"created_at":"date","asdf":"asdf"}]
Your response is an ARRAY of objects, so reference the array index, followed by property:
console.log(data[0].content);
var content = data.content;
var created_at= data.created_at;
var asdf= data.asdf;
console.log(content);
console.log(created_at);
console.log(asdf);
Try this

Categories