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

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");
}

Related

What's a correct way of retrieving data?

I've posted a few questions seeking clarity in small details about the do's and don't's of javascript, ajax and html. And here's one more. I'm creating a list with javascript by the usage of an api. When making the list I get the correct values for the text. When pressing the button in the row I'm getting the alert message. But the new entry is blank.
Can I add data this way (a for loop getting info and building a string with it baked in)?
OR is it the way I retrieve and store data that is wrong?
EDIT: My data is undefined. Don't I get a string from: data.items[i].Info.drivers?
Part of javascript that talks to an api and gives drivers and cars. This segment is part of a for loop.
...+'<h5><data-title="'
+data.items[i].Info.drivers+'">'
+data.items[i].Info.drivers
+'</data></h5>'
+'<p class="subtitle"><data-title="'
+data.items[i].Info.cars+'">'
+data.items[i].Info.cars
+'</data></p>'
+ '<input class="adding"type="button" name="vehicle" value="Add book">'...
My add code (javascript in html):
$(document).on('click', '.adding',function() {
window.alert("active");
var $this = $(this);
var drivers = $(this).data('drivers');
var cars = $(this).data('cars');
alert($(this).data('drivers')); //<----gives alert, says Undefined
$.ajax({
url: 'insert.php',
type: 'POST',
data: {
'driver': drivers,
'car': cars
},
success: function(msg) {
window.alert("success triggered");
}
});
});
This is referring to the button. By putting the data attributes in the button in the same way the problem is solved.

Wikipedia API search -- Retrieve same index of each array with forEach?

I'm working on a project for freeCodeCamp and I've been stuck on this part all day. I'm pulling data from the Wikipedia API and I'm able to work with it, yet I'm not sure how the syntax should look for what I'm trying to achieve. Here is a link to an example of the data I'm working with. Wikipedia API Search.
Now, in my HTML I have a bootstrap modal that appears after the user inputs something into a form, with a listed group inside with the returned data from the search.
This is the code I have so far.
$(document).ready(function () {
$('#searchForm').on('submit', function(e) {
e.preventDefault();
$('#wikiSearch').modal('show');
var usersearch = document.getElementById('userinput').value;
var apiURL = "https://en.wikipedia.org/w/api.php?
action=opensearch&search="
+ usersearch + "&format=json&callback=?";
$.ajax({
url: apiURL,
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'GET',
success: function (data) {
data[1].forEach(function(item) {
$('#results').append("<tr><td><a href='#'>"+item+"</a></td></tr>")
});
data[2].forEach(function(item) {
$('#brief').append("<tr><td>"+item+"</td></tr>")
})
}
});
});
});
For each group in my modal of my HTML I want to display 1 result from the search. I figured I would be able to use a nested forEach but it's not returning the results I wanted. I've tried using map, and also tried creating a long nested for loop and feel like I might be doing more harm than good when it comes to learning since I'm only getting confused now lol. Thanks for any input.
To show the first row from the search results use the first key of the nested array:
$('#results').append("<tr><td><a href='#'>" + data[1][0] + "</a></td></tr>")
$('#brief').append("<tr><td>" + data[2][0] + "</td></tr>")
Don't forget to add a check for the possible undefined value inside the data array.

create links in dynamic table fields

im new to Javascript and im struggling with this question for a while.
I have a dynamic jquery table and my goal is to hyperlink one row of that table (the row data) to a .php page to make some queries.
My objective is something like this:
for example, in the table
data info money name ID
20161001 ... 34 test 1010
20161002 .... 20 dddd 111
20161003 ... 12 .... .....
users could press 20161001 or 20161002 and this would link to a detailed table with all the info of this day
My first problem is to reach the object inside the array of data.
Every time i try to reach data i got something like : [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
The only way i could reach them was from:
JSON.stringify(data[i])
i made a for statement but this return all the info from table and i just need the data from the row: Data.
for my dynamic table i get the headers from :
var keys=[];
for (var key in data[0]) {
keys.push(key);
}
I also try to combine this 2 ways to reach the info but no success.
My ajax code:
$.ajax({
type: 'post',
url: "data.php",
dataType: "json",
data: $(this).serialize(),
success: function(data) {
console.log(data);
$('#btn-load').click(function(e) {
var keys=[];
for (var key in data[0]) {
keys.push(key);
}
dt = dynamicTable.config('data-table', //id of the table
keys, //field names
null, //set to null for field names to be used as header names instead of custom headers
'no data...');
dt.load(data);
});
(Dynamic table with code of this page:
Dynamically update a table using javascript)
I need to reach this info, link him and pass the value into a php page.
I don't know if this method is the more appropriate so if someone can give me some lights i would appreciate.
Thanks
Assuming you want to pass the first column value of the row into your php function you can just try this.
Bind a click event to your table tr using event delegation (as you said it's a. Dynamic table) and extract the first td value on click.
$("#yourTableId").on("click","tr",function(){
var data = $(this).find("td:eq(0)").text();
alert(data); //test
});
$("#data-table").on("click","tr",function(){
var data2 = $(this).find("td:eq(0)").text();
window.open("teste.php?data2="+data2,'_blank','toolbar=0,location=no,menubar=0,height=400,width=400,left=200, top=300');
console.log (data2);
Thans for the help Reddy . This solve the problem, i pass the data trough the Window.open ;)

I have passed an array in session variable. I need to pass key strokes to it to return values

I have stored the returned data from a mysql query into a session variable. I can extract what I want from using $_SESSION['info'][][].
I would like to be able to retrieve values from the array dynamically. The user will select numbers from drop downs (2 of them). One of the numbers needs to passed to the first element of the array and obviously, the second goes to the second element. And then, the result is echoed to the screen.
I need to do this all client side. So like this:
Get result of keypress a
Store it as $a
Get the result of keypress b
Store it as $b
Pass the results of to echo $_SESSION['info'][$a][$b]
I can get one key stroke and pass it to a variable and even possible the second with my limited knowledge but pass them to the session variable and printing the result escapes me at the moment.
enter code here$(document).ready(function() {
$("#pcc").keyup(function() {
var dInput = $(this).val();
$n1=dInput;
//$(".dDimension:contains('" + dInput + "')").css("display","block");
});
});
$(document).ready(function() {
$("#pcp").keyup(function() {
var dInput = $(this).val();
$n2=dInput
//$(".dDimension:contains('" + dInput + "')").css("display","block");
});
});
I know I could probably nest that but one hurdle at a time. I know that saves the keystrokes. I have tested it by passing the values to alerts.
Progess at last. I am using this code to pass the variables from the input fields:
$(document).ready(function(){
$("#pcp").keyup(function(){
var value = $("#pcp").val();
n1= value;
});
$("#pcp").keyup(function(){
var value = $("#pcc").val();
n2= value;
matrix('n1','n2');
});
});
And I know its getting passed to matrix() because Im dumping the variables to console from within matrix like so:
function matrix(){
// getting values from key presses
//console.log(n1, n2);
$.ajax({
url: "matrix.php",
method: 'GET',
dataType: 'json',
data: { a: n1, b: n2 },
success: function(data) {
var response = data.response;
}
$_SESSION['arrayOfMatrix'][$a][$b]= response;
});
I also know that the variables have been passed because I was getting variable undefined errors in console and now I dont. So 2 positive things.
However, thats as far as seem to be able to go. I dont seem to be getting anything back. I have tried putting console.log inside of matrix.php but I dont get anything in that either so Im guessing its just not firing and sending data to matrix.php. Is there any other testing I can do to see where its failing? I feel that Im close to nailing it.
};
What you need is AJAX. You need to create a PHP script that will take two values for $a and $b through a GET or POST request. You can then use jQuery's $.ajax to asynchronously invoke that script and get the result.
So for a start you need a PHP script (let's call it for the sake of this example: example.php).
In example.php you can do something like this:
<?php
session_start();
$a = $_GET['var_a'];
$b = $_GET['var_b'];
//do some checking of the two above variables here
$response = array(
'response' => $_SESSION['info'][$a][$b];
);
echo json_encode($response);
You can substitude $_POST with $_GET if you prefer using a POST request instead.
The next step involves quite a bit of JavaScript so, when you have both $n1 and $n2 populated you can send a POST request using $.ajax:
$.ajax({
url: <path-to-example.php>,
method: 'get',
dataType: 'json'
data: { var_a: $n1, var_b: $n2 }
}).done(function(data){
var response = data.response;
//$_SESSION['info'][$a][$b] is now in response
});
Again you can substitute 'get' with 'post' in case of a POST request

Using jquery ajax load() to transfer multiple data fields

I have an HTML form that I am trying to convert to submitting using the Jquery load() function. I have it working for a single field, but I have spent hours trying to get it to work for multiple fields, including some checkboxes.
I have looked at many examples and there seems to be about three of four ways of approaching this:
Jquery .load()
jquery .ajax()
jquery .submit()
and some others. I am not sure what the merits of each approach is but the first example I was following used the .load(), so that is what I have persisted with. The overall object is to submit some search criterion and return the database search results.
What I have at present:
<code>
// react to click on Search Button
$("#SearchButt").click(function(e){
var Options = '\"'+$("#SearchText").val()+'\"' ;
var TitleChk = $("#TitleChk").prop('checked');
if (TitleChk) Options += ', \"TitleChk\": \"1\"';
// load returned data into results element
$("#results").load("search.php", {'SearchText': Options});
return false; //prevent going to href link
});
</code>
What I get is the second parameter appended to the first.
Is there a way to get each parameter sent as a separate POST item or do I have to pull it apart at the PHP end?
It would seem as if you're stumbling over the wrapper, let's go ahead and just use the raw $.ajax() and this will become more clear.
$("#SearchButt").click(function(e){
var Options = {};
Options.text = $('#SearchText').val();
Options.title = $('#Titlechk').prop('checked')) ? 1: 0; //ternary with a default of 0
$.ajax({
url: 'search.php',
type: 'POST',
data: Options
}).done(function(data){
$('#results').html(data); //inject the result container with the server response HTML.
});
return false;
});
Now in the server side, we know that the $_POST has been populated with 2 key value pairs, which are text and title respectively.

Categories