Please help me with my problem in displaying JSON data into my view..
my script is:
$('#supplierId').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
var firstnameID = $('#firstnameID');
$.each(data, function(index, element) {
firstnameID.val(element.first_name);
});
});
});
and my JSON reply is:
{"id":7,"first_name":"John","last_name":"Doe"}
the thing is when i tried to:
alert(element.first_name);
it says UNDEFINED, but when I:
alert(element);
it gives me the value of the last name which is Doe.. my question is how can I then access the other values like the ID and the first name..
EDITED:
this is my route:
Route::get('api/dropdown', function(){
$input = Input::get('option');
$supllier = Supplier::find($input);
returnResponse::json($supllier->select(array('id','first_name','last_name'))
->find($input));
});
Please help me with this one, This is my first time using JSON so im a bit confuse on how this works.
Best Regards
-Melvn
Why are you using each? This should work:
$('#supplierId').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
var firstnameID = $('#firstnameID');
firstnameID.val(data.first_name);
});
});
Ok, give this a try..
Explicitly state that what you're expecting back from the server is JSON using the dataType option in get().
$('#supplierId').change(function()
{
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data)
{
var firstnameID = $('#firstnameID');
$.each(data, function(index, element)
{
firstnameID.val(element.first_name);
});
},
'json' // <<< this is the dataType
);
});
Now you should be able to access the data using the dot syntax:
console.log("last_name: " + element.last_name);
console.log("first_name: " + element.first_name);
console.log("id: " + element.id);
I would add another few lines, just to check that you're getting back what you expect to see:
console.log("NEW ELEMENT"); // << indicator in the console for your reference
console.log(element); // << the whole "element"
Related
I have this json:
{"objects":[{"text":{"x":643,"y":71,"width":82,"height":33,"font":"Arial","style":"bold","size":24,"label":"Part A"}},
{"text":{"x":643,"y":116,"width":389,"height":42,"font":"Arial","style":"bold","size":16,"label":"What does \"novel\" mean as it is used in paragraph 8 of \"Turning Down a New Road\"? "}},
{"radiobutton":{"x":643,"y":170,"width":100,"height":20,"label":"A. old"}},{"radiobutton":{"x":643,"y":209,"width":100,"height":20,"label":"B. afraid"}},
{"radiobutton":{"x":643,"y":250,"width":100,"height":20,"label":"C. new"}},
{"radiobutton":{"x":643,"y":289,"width":100,"height":20,"label":"D. friendly"}}]}
I need to get the properties of each element, but I can't get the property of second level, I mean I can´t know if the element is a "text","radiobutton","label", I have no problem with the propeties of third level.
This is my source:
$.ajax({
url: 'generateobject.php',
dataType: 'json',
type: 'GET'
}).done(function(data) {
$.each(data, function(index, firstLevel) {
$.each(firstLevel, function(anotherindex, secondLevel) {
alert(secondLevel[0]);//shows [object Object]
$.each(secondLevel, function(yetAnotherIndex, thirdLevel) {
//alert(thirdLevel.y+''+thirdLevel.y);
});
});
});
});
How do I get the property of second level?
Use Object.keys(data) and access the first item. If you run the snippet you should see the types alert as expected:
var data = {"objects":[{"text":{"x":643,"y":71,"width":82,"height":33,"font":"Arial","style":"bold","size":24,"label":"Part A"}},
{"text":{"x":643,"y":116,"width":389,"height":42,"font":"Arial","style":"bold","size":16,"label":"What does \"novel\" mean as it is used in paragraph 8 of \"Turning Down a New Road\"? "}},
{"radiobutton":{"x":643,"y":170,"width":100,"height":20,"label":"A. old"}},{"radiobutton":{"x":643,"y":209,"width":100,"height":20,"label":"B. afraid"}},
{"radiobutton":{"x":643,"y":250,"width":100,"height":20,"label":"C. new"}},
{"radiobutton":{"x":643,"y":289,"width":100,"height":20,"label":"D. friendly"}}]};
$.each(data, function(index, firstLevel) {
$.each(firstLevel, function(anotherindex, secondLevel) {
alert(Object.keys(secondLevel)[0]);
$.each(secondLevel, function(yetAnotherIndex, thirdLevel) {
//alert(thirdLevel.y+''+thirdLevel.y);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am using PHP at server side to get json formatted output as below. At client side I use jQuery to display the results but it displays null. Please let me know where I went wrong. Any help is appreciated.
PHP
while ($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
echo json_encode($rows);
Output
[
{
"a_name": "affles",
"bname": "bua",
"c_number": "10101010",
"dateandtime": "2013-11-30 17:50:04"
},
{
"a_name": "affles",
"bname": "bua",
"c_number": "10101010",
"dateandtime": "2013-11-30 17:50:04"
},
{
"a_name": "anan",
"bname": "nesh",
"c_number": "2017439441",
"dateandtime": "2013-12-04 17:50:04"
}
]
Client side
$.getJSON("http://apip.com/results.php", function (data) {
$.each(data, function (index, value) {
$('<li>' + value.a_name + '</li>').appendTo('#groups');
});
});
Client side code using JSONP: I modified client side to use JSONP but still it returns null. An help is appreciatd
<script>
(function() {
var flickerAPI = "http://apip.com/results.php?jsoncallback=?";
$.getJSON( flickerAPI,
(function( data ) {
$.each( data.items, function( index, value ) {
$('<li>' + value.a_name + '</li>').appendTo('#groups');
});
});
})();
</script>
As you can see from this fiddle, it is working fine. What I do suspect is going wrong is that you're using http://apip.com/results.php and you might be fooling jQuery into thinking you're doing a cross-domain request (which you might be doing), which is generally prohibited by browsers unless you use JSONP. If you own http://apip.com/, use
$.getJSON("/results.php", function (data) {
$.each(data, function (index, value) {
$('<li>' + value.a_name + '</li>').appendTo('#groups');
});
});
I am fairly new to JavaScript and PHP, and it's the first time to encounter and use JSON. I think my AJAX request is fine, but even so, the $_POST array is empty.
Here is the AJAX call:
$( "#submit" ).click( function() {
var submit_basic = $.post( 'index.php/submit_data/pass_basic_data',
get_experience_data()
);
submit_basic.done( function(data) {
alert(data); // for debugging purposes
});
});
And this is the function that takes the data from a table:
function get_experience_data() {
var temp, data_exp = [];
$( "#exptable tbody tr" ).each( function() {
temp = {
company: $(this).find('td').eq(0).html(),
position: $(this).find('td').eq(1).html(),
datestart: $(this).find('td').eq(2).html(),
dateend: $(this).find('td').eq(3).html(),
description: $(this).find('td').eq(4).html()
};
data_exp = data_exp.concat(temp);
});
return data_exp;
}
And for reference, the destination controller function that only prints the $_POST array (by the way I am using CodeIgniter):
public function pass_basic_data() {
var_dump($_POST);
}
Can you please pinpoint the error I've made, since I can't find it. Thanks a lot!
UPDATE: I am getting this message in particular:
array(1) {
["undefined"] =>
string(0) ""
}
UPDATE:
Thanks for all the help guys! I already solved it. It made me dance all around the room.
I wrapped the return value in a {name : value} pair.
$( "#submit" ).click( function() {
var post_vars = get_experience_data();
var submit_basic = $.post( 'index.php/submit_data/pass_basic_data',
{object: post_vars}
);
submit_basic.done( function(data) {
alert(data); // for debugging purposes
});
});
I would suggest doing the following for a start :
var submit_basic = $.post('index.php/submit_data/pass_basic_data', get_experience_data());
Try this:
var submit_basic = $.post('index.php/submit_data/pass_basic_data', get_experience_data());
// you need to add parentheses here --------------------------------------------------^
When you pass a function to $.post() it assumes it is a callback that is to be called after the response is received. What you want to do is call the function and pass it's return value in to $.post().
By the way, this line:
data_exp = data_exp.concat(temp);
could be replaced with:
data_exp.push(temp);
No need to be creating a new array every time if you're just adding a value to the end.
You need to execute the method get_experience_data, otherwise you are passing the function not executing it
try troubleshooting the actual jquery, not the php part.
but heres a suggestion:
var post_vars = get_experience_data();
var submit_basic = $.post( 'index.php/submit_data/pass_basic_data', post_vars );
here is a conclusion to my previous answer plus the comments, but im still not sure if you could stingify arrays in arrays..
var submit_basic = $.ajax({
type: "POST",
url: 'index.php/submit_data/pass_basic_data',
dataType: 'json',
async: false,
data: JSON.stringify(get_experience_data()),
success: function (response) {
alert(response);
}
});
UPDATE:
modify your get_experience_data function according to this jsfiddle script
like this:
temp = '{ ';
temp+= '"company":"' +$(this).find('td').eq(0).html()+ '", ';
temp+= '"position":"' +$(this).find('td').eq(1).html()+ '", ';
temp+= '"datestart":"' +$(this).find('td').eq(2).html()+ '", ';
temp+= '"dateend":"' +$(this).find('td').eq(3).html()+ '", ';
temp+= '"description":"' +$(this).find('td').eq(4).html()+ '"';
temp+= ' }';
Turning off asynchronous requests in jQuery fixed the issue.
I have the following Javascript & AJAX request (using jQuery) in my page:
"use strict";
var hsArea, counter, hotspots, count;
counter = 4;
count = 0;
hotspots = {};
function fetchHotspotList() {
$.getJSON ('/alpha/engine/hotspots/gethotspot.php', {'type' : 'list'}, function(json) {
hotspots = json;
});
}
function displayHotspot(type, id, number) {
$.ajax({
url: '/alpha/engine/hotspots/gethotspot.php',
dataType: 'json',
data: {'type' : type, 'id' : id},
success: function(json) {
console.log(json);
var hotspot, extract;
extract = json.content;
extract = extract.replace(/<(?:.|\n)*?>/gm, '');
extract = extract.substring(0, 97);
extract = extract + "...";
json.content = extract;
hotspot = document.createElement("div");
hsArea.append(hotspot);
hotspot.setAttribute('class','hotspot');
hotspot.setAttribute('id','hotspot' + number);
$(hotspot).css('position', 'absolute');
$(hotspot).css('top', number * 100 + 100);
$(hotspot).css('left', number * 100 + 110);
hotspot.innerHTML = "<h1>"+ json.title + "</h1><p>" + json.content + "</p>";
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus, errorThrown);
}
});
}
function listHotspots() {
for(count = 0; count < counter; count++) {
(function(count) {
displayHotspot('scribble',hotspots[count], count);
count = count + 1;
})(count);
}
}
function loadHotspots() {
fetchHotspotList();
listHotspots();
}
$(document).ready(function() {
hsArea = $("#hotspotArea");
fetchHotspotList();
listHotspots();
});
(Sorry the formatting is a bit off!) - Now, the $(document).ready() function assigns the hsArea variable as it should, however, a combination of fetchHotspotList() and listHotspots() returns:
Uncaught TypeError: Cannot call method 'replace' of null
However, if in the Google Chrome Javascript console, I run:
loadHotspots();
it fetches the data from the AJAX request and displays it properly on the page. At first I thought the problem was that I Wasn't using the $(document).ready() handler, but adding it hasn't fixed it. Neither has using an onload handler inside of the body tag.
Any help would be greatly appreciated.
Regards,
Ben.
It's probably due to the fact that your listHotSpots function is called before fetchHotSpots returns (since it's an async call).
You're better off chaining the execution of listHotSpots to the completion of fetchHotSpots, like so:
function fetchHotspotList() {
$.getJSON ('/alpha/engine/hotspots/gethotspot.php', {'type' : 'list'}, function(json) {
hotspots = json;
listHotSpots();
});
}
You may be better off modifying listHotSpots to take the json data returned from your AJAX call. Hope this helps!
I have an unknown number of inputs and i want to write them in a database. I tried some different ways but nothing worked. I dont know the number of the inputs, so i need something like a multidimensional array
javascript:
var temp=new Array();
var obj;
$("#mitarbFuktionen fieldset").each(function(){
i=$(this).parent().children().index($(this));
if ($(this).hasClass("New")){
temp[0]='New';
temp[1]=$("legend",this).text();
//.....
obj+=JSON.stringify(temp)
}else if ($(this).hasClass("Remove")){
temp[0]='Remove';
temp[1]=$("legend",this).text();
//.....
obj=$.toJSON(temp);
}
})
$.post("ajax/MitarbSave.php",{
anrede:$('input[name="neuMitarbAnrede"]:checked').val(),
titel:$('#neuMitarbTitel').val(),
nation:$('#neuMitarbNat').val(),
//.....
'kom[]': obj
}, function(data){
alert(data);
})
PHP:
$output= json_decode($_POST["kom"], true);
echo var_dump($output);
Just to provide an answer to my comment:
$(document).ready(function()
{
var test = [];
test.push('a');
test.push('b');
$.post('ajax/script.php',
{
Param : test
},
function(resp)
{
}, 'json');
});
jQuery will automatically convert an array when passed as an param to an Ajax request, to a multi-dimensional array.
You could also just build an object, an pass that:
var obj={};
$("#mitarbFuktionen fieldset").each(function(){
var i=$(this).index();
obj[i]={};
obj[i][$(this).is(".New") ? 'New :' : 'Remove :'] = $("legend", this).text();
});
$.post("ajax/MitarbSave.php",{
anrede:$('input[name="neuMitarbAnrede"]:checked').val(),
titel:$('#neuMitarbTitel').val(),
nation:$('#neuMitarbNat').val(),
kom: obj
}, function(data){
alert(data);
});
just add the array to your input fields in HTML like:
<input type="text" name="neuMitarb[NUMBER][anrede]">
<input type="text" name="neuMitarb[NUMBER][titel]">
//...
So you let html create your array. Submitting your form like regular form submit with ajax