jQuery Parse JSON Response - javascript

I am successfully Posting to a PHP file, and getting a good response. The part I cannot seem to get is parsing it out then displaying it on my page. Here is my javascript in a validate handler:
submitHandler: function(form) {
var formData = $(form).serialize();
$.post('http://test.php', formData, function(data) {
if(data.success) {
$('#load').show();
var response = i;
$('#load').hide();
//var msg = '';
for(var i = 0; i < x.flights.length; i++) {
msg += '<span>';
msg += '<p>Flight Number: ' + x.flights[i].flight_number + '</p>';
msg += '<p>Cost: ' + x.flights[i].cost + '</p>';
msg += '</span>';
}
//this is were I think it should display. but It's not working
$('#load').html(msg);
Here is my json response:
success
true
message
"Success"
flights
[Object { flight_number="334", cost="983.40", departure_city="Kearney Regional Airpor...arney, Nebraska - (EAR)", more...}]
0
Object { flight_number="334", cost="983.40", departure_city="Kearney Regional Airpor...arney, Nebraska - (EAR)", more...}
flight_number
"334"
cost
"983.40"
departure_city
"Kearney Regional Airport, Kearney, Nebraska - (EAR)"
arrival_city
"Chadron Muni Airport, Chadron, Nebraska - (CDR)"
departs
"2014-03-19 04:33:00"
arrives
"2014-03-19 08:12:00"
duration
"219"
adult_seats_available
"2"
senior_seats_available
"1"
I know you you are not seeing the JSON response, but I can see it in FF firebug. I'm new to jQuery/JSON, and I just want to print the response to my page. Thanks in advance.

Look into JSON.stringify(data) doc I don't know where you want to display your JSON but if you just want to see what it is open up the debugger and console.log(JSON.stringify(data)); should do it.

You are using post method and it may default return xml, json, script, text, html. So you are getting the data from post method.
Try looking at https://api.jquery.com/jQuery.post/
And if you want to access it, then you can use JSON.stringify(data) to show json as a string. And to access data from json you can use dot(.) notation.

There's a couple of things to look at here.
First you're adding your html (ie msg) to the #load element ($('#load').html(msg);) but earlier in the code you're hiding it ($('#load').hide();). So I think this will answer your main question; i.e. remove the the line $('#load').hide(); or add $('#load').show(); after the line $('#load').html(msg);.
Still not seeing anything? Then perhaps the response isn't as corrent as you're claiming so perhaps an easier way to check what's been assigned to msg is to alert the html alert(msg); <- make this call after you've built your html.
So aside from this is the use of the #load element you seem to be using it to hold a loading gif but also assigning it the response via the content of msg. Perhaps you need to separate the use of the elements so that the #load element is for the loading gif and you add another element for the response. so you're code is more like this.
html
<div id="load" class="hide"><img src="loading-animation.gif">...</div>
<div id="post-response" class="hide alert"><div>
where the hide class is display none and alert class represents an style for a response alert.
js
submitHandler: function(form) {
// show the loading gif before we make the
// post data and wait for an async response
$('#load').show();
...
$.post('http://test.php', formData, function(data) {
if(data.success) {
// post-back has completed so lets hide the animation
$('#load').hide();
// your code to build html msg
// assign and show the response element
$('post-response').html(msg);
$('post-response').show();
...

Related

document.getElementById(..) gives null even though element is present

I have the following program in which a user can enter any name in a search box after which I redirect the user to a page called usernameSearchResults.php where I print a list of the usernames obtained in the form of an array from usernamesearch.php. Here is the javascript:
$(window).on('load', function() {
$(".searchBarForm").submit(function(e){
e.preventDefault();
var search=document.getElementsByClassName("search")[0].value;
$.ajax
({
type: 'POST',
url: 'usernamesearch.php',
data:
{
search:search
},
success: function (response)
{
window.location.href="usernameSearchResults.php";
response = JSON.parse(response);
var array_length = Object.keys(response).length;//getting array length
for(var i=0;i<array_length;i++){
if(i==0){
document.getElementById("searchResults").innerHTML=""+response[0].username+"<br>";//i=0
}else{
document.getElementById("searchResults").innerHTML+=""+response[i].username+"<br>";
}
}
window.stop();//stops page from refreshing any further(put here to fix a bug that was occuring)
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
return false;
})
});
This is usernameSearchResults.php(inside tags):
<h1>Username Search Results</h1>
<p id="searchResults"></p>
But the problem is that whenever I go to any other page say index.php and enter the username to be searched, the page redirected to is indeed usernameSearchResults.php but the page is blank and error in the console shown says document.getElementById("searchResults") is null.But if I stay at the page usernameSearchResults.php and refresh it and then search any name again, then the results are correctly obtained. What is the problem here?
I would say that the user is being redirected to usernameSearchResults.php but the JavaScript code is still being executed from the current page, which have no element with id "searchResults" defined.
As #Kashkain said, one way to achieve what you want is to pass your response variable in your redirection url and process it then into your other page.
I think the problem here is that the new document could very well still not have been loaded when you call getElementById.
You could add a listener on your target element which would trigger on the load event. In this event's handler you could execute the operations that are now giving you an error.
I have never done or tried this, but maybe something like this would work:
$('#searchResults').on('load', function() {
//execute code here
});
Or you could add a form to the page with action="target_url" method="post" and send your response data through post by doing form.submit, and place the problematic code into usernameSearchResults.php, which will need to read data from POST - this way you can send your ajax data to the new page

Javascript code running fine until put into a function

I have taken some source code from here to submit a form using AJAX. The form is basically taking some information from a user and putting it into a database via PHP. The code I have works, but given that what I am working on has many forms all doing the same thing, I - obviously - want to make sure my code is lean and mean. So, making sure that each of my form field names have the same as my database with some matching IDs for various parts of the form for user feedback, have changed it to the following:
<script type="text/javascript">
$(document).ready(function() {
// process the form
$('#formId').submit(function(event) { // for the specified form:
// completeForm('#formId'); // WHERE I CALL THE FUNCTION
// FUNCTION STARTS HERE WHEN IT IS ONE
var formData = {}; formId = '#formId';
$(formId + ' input, ' + formId + ' select, ' + formId + ' textarea').each(
function(index){ // for each item (input, select, textarea in the specified form
var input = $(this);
// First, clear any existing formatting that has been added by previous form inputs
$('#' + input.attr('id') + '-group').removeClass('has-info has-error has-success bg-error bg-info bg-success');
// Next, add data to the array of data to pass to the PHP script
Array.prototype.push.call(formData, input.val());
}
); // End of loop through each item.
// Now the data is collected, call the requested PHP script via AJAX.
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : $(this).attr('action'), // '/processing/general_settings_processing.php', // the url where we want to POST
data : formData, // our data object
dataType : 'html' // 'json' // what type of data do we expect back from the server
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// Return success and error messages to the user
// Code to come once the basics have been sorted out!
});
// FUNCTION WOULD END HERE WHEN IT IS ONE.
event.preventDefault();
});
});
</script>
The code as above works absolutely fine; the relevant PHP file is called and - although I have no processing done in this particular file yet - does its stuff (I have it echoing the $_POST array to a file and returning to view in the console log atm).
However, when I try and make it a function, it doesn't - the console log simply echoes out the source code for this document instead of the PHP array that it supposed to be doing. The function is placed above the $(document).ready line; specified as function completeForm(formID) { . . . } , contains the section of code as noted in the comments and called in the commented out line as shown. So, logically (to me) it should work.
The ultimate idea is to have the function to do this in a file that can be called by all the forms that call it, while the code to call the function is in the relevant part of the page. Some pages will have more than one form using it. (I mention that should even if what I am doing here works, it wouldn't when I come to reuse the code!)
(I'm relatively new to JS and JQuery, although have a fairly good grasp of some programming techniques, mainly these days just in PHP.)
The issue you are having with making that a function is you forget to include the "thisBinding". As a result, when you tried to use the form's action target in your ajax call with this code:
url : $(this).attr('action')
it does not find an "action" attribute - basically the issue is that this is actually window and as a result there is no action attribute. Simply bind this to your function call and your code will work as written.
completeForm.call(this,'#formId');
.call MDN

JSON Parse Error: unexpected end of data at line 1 column 1 of the JSON data

I have a database, analysis.php and index.php webpages. The analysis.php gets the data from the database, sorts it in a required pattern, and then echoes the json_encode($array); into a div with the id 'data'. I am trying to get that JSON Data and parse it in the index.php page.
However I am getting an error. SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
I am trying to get this data everytime the user selects an option from a select box.
My jQuery code is:
$(document.body).on('change', '.select' , function () {
var identification = $(this).val();
var JSONText = $(this).closest('div[id|="module"]').find('p[id="JSON"]');
JSONText.load('analysis.php?data=' + identification + ' #data');
console.log("JSON Imported: '" + identification + "'");
var obj = jQuery.parseJSON(JSONText.text());
console.log(JSONText.text());
});
EDIT: As you can see I have the snippet console.log(JSON.text());. The output of the JSON that I get is correct. The only issue I think might be is that the quotes are all " instead of the JSON quotes being different from the outer quotes.
jQuery.load is asynchronous, you're trying to parse the JSON before its actually loaded. Using jQuery.getJSON loads the content, does the parsing and provides a callback you can bind to.
jQuery.load loads the content as HTML and sets the innerHTML of the selected element, you could bind the complete handler here aswell, but you may encounter issues by loading the content as HTML and then using text to retrieve it from the DOM as some parts of your JSON may be interpreted as HTML elements.
Better use this:
$(document.body).on('change', '.select' , function () {
var identification = $(this).val();
$.getJSON(
'analysis.php?data=' + identification + ' #data',
function (data) {
console.log(data);
}
);
});
In addition to LJ_1102's solution, here is a way to fix your current snippet:
JSONText.load('analysis.php?data=' + identification + ' #data', function() {
console.log("JSON Imported: '" + identification + "'");
var obj = jQuery.parseJSON(JSONText.text());
console.log(JSONText.text());
});

Trying to read the Google Calender JSON Data using JQuery

I am trying to read the google calendar events from the JSON response but nothing happens.
I have tried the code from here but that too is not working. I am adding the code to my CMS and when I check on the front end, nothing appears. I even tried running this fiddle http://jsfiddle.net/bGdhD/ but this also doesn't provide any response.
My google calendar URL is
https://www.google.com/calendar/feeds/varun.luthra.72%40gmail.com/public/full?alt=json-in-script&max-results=25&singleevents=false&futureevents=true&sortorder=descending&orderby=starttime
<script>
var event = '';
var gclaData = 'https://www.google.com/calendar/feeds/varun.luthra.72%40gmail.com/public/full?alt=json-in-script&max-results=25&singleevents=false&futureevents=true&sortorder=descending&orderby=starttime';
$.getJSON(gclaData,function(data){
$.each(data.feed.entry, function(i, entry){
event += '<div class="eventHolder">';
event += '<div class="eventTime">'+ entry.gd$where[0].startTime+"</div>";
event += '<div class="eventName">'+ entry.title.$t + "</div>";
event += '<div class="eLink">'+ entry.link[0].href + "</div>";
event += '</div>';
});
$('#output').html(event);
});
</script>
<div id="output"></div>
Also, could this be a cross domain issue?
It's not a cross domain problem, because the response includes the Cross Origin Resource Sharing header:
access-control-allow-origin:*
The problem is the response is a JSONP response and so includes a callback function. This makes it invalid JSON (unless you strip the callback).
Option 1: If you set &callback=? in the URL, jQuery will treat the response as JSONP:
var gclaData = 'https://www.google.com/calendar/feeds/varun.luthra.72%40gmail.com/public/full?alt=json-in-script&max-results=25&singleevents=false&futureevents=true&sortorder=descending&orderby=starttime&callback=?';
Option 2: Use $.ajax() and strip the callback:
gdata.io.handleScriptLoaded(
Also strip the closing parenthesis and semicolin );. This leaves you with a valid JSON response, which needs to be decoded from a string to a Javascript object using JSON.parse() or similar.
Also, there doesn't appear to be an entry array or object in the response, so you need to modify your success event accordingly.
Last point, this will not work:
entry.gd$where[0]
If the variable name has special characters, use the [] notation:
entry['gd$where'][0]

how to access and output json results from $.ajax() success callback

I'm using coldfusion and jquery. This is my first real go at jquery and I've searched and read for a long time without cracking this so any help would be greatly appreciated...
Ok, I have an autocomplete returning an id. I'm then passing the id to a second function that returns an array of datatype json. The autocomplete works great and I can get the json to display in an alert box but am a bit stuck on how to use the json results.
I'm trying to loop through the json array and write the values into radio buttons, which then dynamically display on page... So the whole idea is this.
user is selected from drop box and id is returned
user id from selection is passed to user options function and user options are returned in json arrary.
json array is looped through and on each iteration a radio button is created with appropriate values.
all radio buttons are then output to screen for access and selection.
The code I have so far is this :
<script type="text/javascript">
// <!--
$(document).ready(function() {
$("#userName").autocomplete({
cache:false,
source: "/jqueryui/com/autocomplete.cfc?method=getUser&returnformat=json",
//setup hidden fields
select:function(event,ui) {
var uid = ui.item.id;
$("#userid").val(ui.item.id);
// start call to get user options
$.ajax({
type: "POST",
url: "/jqueryui/com/autocomplete.cfc?method=getUserOptions&returnformat=json",
data: ({ userid: uid }),
success: function(data) {
alert(data)
}
});
/// end call to get user options
}
});
});
// --->
</script>
The json displayed in the "alert(data)" popup, which looks fine, is this :
[{"productname":"licence free","quantity":1,"term":12,"id":1},
{"productname":"licence basic","quantity":1,"term":24,"id":1},
{"productname":"licence full","quantity":1,"term":12,"id":2}]
I need to know how to loop through this data and create a radio button for each option, probably something like this, and display them all on screen, which I'm guessing I'll just write to a via the dom once I have something to write :
<input type="radio" name="userOption" value="#id#|#qty#|#term#">#productname#
I have tried a few things, without success, such as :
for(var i =0;i<Data.length-1;i++)
{
var item = Data[i];
alert(item.productname + item.id);
}
And
$.each(data.items, function(i,item){
alert(item);
if ( i == 3 ) return false;
});
I couldn't get either of these to work.
Anyway this is getting a bit long winded. Hope it's clear, and again any help or suggestions appreciated.
Thanks!
First check the datatype of the data parameter returned. You might first need to use .parseJSON() to construct a JSON object.
Then your for loop syntax is not correct. this code works for me:
var data = [{"productname":"licence free","quantity":1,"term":12,"id":1},
{"productname":"licence basic","quantity":1,"term":24,"id":1},
{"productname":"licence full","quantity":1,"term":12,"id":2}];
for (var i=0; i<data.length; i++) {
alert(data[i].productname);
}
Here's a jsfiddle
Try checking parseJSON jquery function.
I quess that the type is a string? If so try it with the javascript function eval. It converts a string to a javascript type.. in your case something like this should work:
Var new_data = eval(data);
Now it should be a workable array/object
Edit: to stay with the data variable:
data = eval(data);
Edit 2:
Your ajax call misses the dataType property:
dataType: "json"
With this you dont need the stuff above i said
Use a each loop to get data and appendTo function to print data in an HTML element with result1 id:
dataType:"json", //nature of returned data
success: function(data) {
var content = '';
$.each(data, function(i, dbdata) {
content += '<p>' + dbdata.columnName + '<p>';
});
$(content).appendTo("#result1");
}

Categories