I get 'undefined' when accessing a json array position - javascript

I am getting the results of a db query in php and return it thru ajax in a json array, but when I try to access the data it gives me data as 'undefined'
why is that happening?
Here is my php code:
<?php
$tipo_prod= $_POST['tipo_prod'];
$conn = oci_connect("admin", "admin", "localhost/XE");
$query = "SELECT COD_PRODUCTO, NOMBRE FROM PRODUCTO WHERE COD_TIPO_PROD=" . $tipo_prod;
$exec= oci_parse($conn, $query);
oci_execute($exec);
//Check connection!!!
$exec= oci_fetch_array($exec);
echo json_encode($exec);
?>
And my ajax code:
$.ajax({
url : "trae_producto.php",
type : "POST",
data: {"tipo_prod" : tipo_prod},
success : function(data){
data = JSON.stringify(data);
$.each(data, function(index, value){
$('#producto').append("<option value='" + value.COD_PRODUCTO + "'>" + value.NOMBRE + "</option>");
});
}});

try doing::
$.ajax({
url : "trae_producto.php",
type : "POST",
data: {"tipo_prod" : tipo_prod},
dataType: "json",
success : function(data){
$.each(data, function(index, value){
$('#producto').append("<option value='" + value.COD_PRODUCTO + "'>" + value.NOMBRE + "</option>");
});
}});
try adding Content-Type header in your PHP code, like:
header('Content-Type: application/json');
echo json_encode($exec);
Added:
do something like
while($data = oci_fetch_array($exec)) {
$out[] = $data;
}
echo json_encode($out);

$.ajax({
url : "trae_producto.php",
type : "POST",
dataType: "json",
data: {"tipo_prod" : tipo_prod},
success : function(data){
/* data = JSON.stringify(data); */
$.each(data, function(index, value){
$('#producto').append("<option value='" + value.COD_PRODUCTO + "'>" + value.NOMBRE + "</option>");
});
}});
I don't know what's your real return from PHP script but if it assumed as correct, the AJAX seems have some flaws.
JSON.stringify will make your object to string type so the jQuery iterator won't work.
use "dataType" attribute to inform AJAX it will getting JSON object

You're trying to turn the result that it gives you into JSON. jQuery parses it already for you, just remove the line for JSON.stringify.
$.ajax({
url : "trae_producto.php",
type : "POST",
data: {"tipo_prod" : tipo_prod},
success : function(data){
$.each(data, function(index, value){
$('#producto').append("<option value='" + value.COD_PRODUCTO + "'>" + value.NOMBRE + "</option>");
});
}
});

At first, debug through firebug whether you are getting a JSON object, as well as your server is sending data. Then, instead of data = JSON.stringify(data);, you can use data = JSON.parse(data);

Related

How to get JSON data into option list

I am getting JSON in the following format (as array of objects)
[{"0":"Ahmednagar","city_name":"Ahmednagar","1":"1","city_id":"1"},{"0":"Akola","city_name":"Akola","1":"2","city_id":"2"},{"0":"Amravati","city_name":"Amravati","1":"3","city_id":"3"},{"0":"Aurangabad","city_name":"Aurangabad","1":"4","city_id":"4"},{"0":"Beed","city_name":"Beed","1":"5","city_id":"5"},{"0":"Bhandara","city_name":"Bhandara","1":"6","city_id":"6"},{"0":"Buldhana","city_name":"Buldhana","1":"7","city_id":"7"},{"0":"Chandrapur","city_name":"Chandrapur","1":"8","city_id":"8"},{"0":"Dhule","city_name":"Dhule","1":"9","city_id":"9"},{"0":"Gadchiroli","city_name":"Gadchiroli","1":"10","city_id":"10"},{"0":"Gondia","city_name":"Gondia","1":"11","city_id":"11"},{"0":"Hingoli","city_name":"Hingoli","1":"12","city_id":"12"},{"0":"Jalgaon","city_name":"Jalgaon","1":"13","city_id":"13"},{"0":"Jalna","city_name":"Jalna","1":"14","city_id":"14"},{"0":"Kolhapur","city_name":"Kolhapur","1":"15","city_id":"15"},{"0":"Latur","city_name":"Latur","1":"16","city_id":"16"},{"0":"Mumbai City","city_name":"Mumbai City","1":"17","city_id":"17"},{"0":"Mumbai Suburban","city_name":"Mumbai Suburban","1":"18","city_id":"18"},{"0":"Nagpur","city_name":"Nagpur","1":"19","city_id":"19"},{"0":"Nanded","city_name":"Nanded","1":"20","city_id":"20"},{"0":"Nandurbar","city_name":"Nandurbar","1":"21","city_id":"21"},{"0":"Nashik","city_name":"Nashik","1":"22","city_id":"22"},{"0":"Osmanabad","city_name":"Osmanabad","1":"23","city_id":"23"},{"0":"Palghar","city_name":"Palghar","1":"36","city_id":"36"},{"0":"Parbhani","city_name":"Parbhani","1":"24","city_id":"24"},{"0":"Pune & Pimpri-Chinchwad ","city_name":"Pune & Pimpri-Chinchwad ","1":"25","city_id":"25"},{"0":"Raigad","city_name":"Raigad","1":"26","city_id":"26"},{"0":"Ratnagiri","city_name":"Ratnagiri","1":"27","city_id":"27"},{"0":"Sangli","city_name":"Sangli","1":"28","city_id":"28"},{"0":"Satara","city_name":"Satara","1":"29","city_id":"29"},{"0":"Sindhudurg","city_name":"Sindhudurg","1":"30","city_id":"30"},{"0":"Solapur","city_name":"Solapur","1":"31","city_id":"31"},{"0":"Thane","city_name":"Thane","1":"32","city_id":"32"},{"0":"Wardha","city_name":"Wardha","1":"33","city_id":"33"},{"0":"Washim","city_name":"Washim","1":"34","city_id":"34"},{"0":"Yavatmal\t","city_name":"Yavatmal\t","1":"35","city_id":"35"}]
ajax call to get json
$(document).ready(function(){
$("#select_state").change(function() {
var $state_var=$('#select_state').val();
alert("Selected State Value "+$state_var);
//make the ajax call
$.ajax({
url: 'ajax/location.php',
type:'GET',
data: {
state_name : $state_var
},
success: function(city_list) {
console.log(city_list);
var options = '';
for (var i = 0; i < city_list.length; i++) {
var city = city_list[i];
options += '<option value="' + city.city_id + '">' + city.city_name + '</option>';
}
$('#select_city').html(options);
$('#select_city').show();
}
});
});
});
Now it gives me only undefined is option list
You need to add:-
dataType;'json',
In your $.ajax code so that your response is automatically parsed and success function will execute properly.
Like below:-
$.ajax({
url: 'ajax/location.php',
type:'GET',
dataType:'json', // add this
data: {
state_name : $state_var
},.....rest code

How to save the data into database in jquery and display upon the screen using web api

I want to add the values inot the database but I am not to able to do that.
var Array;
$(document).ready(function ()
{
$.ajax({
url: '../api/Emp/GetAll',
type: 'Get',
cache: false,
datatype: 'json',
success: function (text) {
Array = text.Table;
var List = JSON.stringify(text);
for (var i = 0; i < data.length; i++) {
var Id = Array[i].id;
var Name =Array[i].name;
var city = Array[i].city;
$('#table body').append('<tr><td>' + Id + '</td><td><input type="text" value="' + Name + '" id="txt' + Id + '" /></td><td>' + city + '</td> </tr>');
}
}
})
If you need to put it back into the database you just need to reverse the process.
Use post for your type and send the data back with ajax to a php script page that inserts the data into your database.
You can edit the data on the php page before you insert it into the database or you can edit the data with javascript then send it back to php page.
Create an ajax post
$.ajax({
type: "post",
datatype: "json",
url: "insertPage.php",
data: {dataNameHere: editedDataGoesHere},
success: function(data){
alert("SUCCESS");
},
error: function(e){
alert("ERROR");
}
});
And then in your PHP:
$obj = $_POST['dataNameHere'];
and insert it into your database like you normally would.

Jquery each data object attribute

I am trying to create table rows containing data from each attribute from my object response using $.each, however the Id, Purpose, and Amount are coming back undefined. I have tested the response in Fiddler and the data is all being received correctly, the problem just seems to be in the "item" part. Here is my Jquery:
$.ajax({
type: "GET",
url: "https://chad-test4.clas.uconn.edu/api/Commitments/GetCommitmentPurposes/2",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (response) {
var purposes = $("#purposes tbody");
if (response.Success == true) {
purposes.empty();
var buttons = '<tr><td><button type="button" class="btn-primary">Save</button>'
+ '<button type="button" class=".btn-danger">Delete</button></td>'
var list = response.Data;
$.each(list, function (i, item) {
purposes.append(buttons + '<td><select id=' + item.Id + '>' + item.Purpose + '</select>'
+ '<td><input type="text" val =' + item.Amount + '/>')
});
}
}
});
});
Could you post a snippet of JSON aswell ?
Basically I believe what you need to do is to access the entries by an identifier:
$.each( list.items, function(i, item ) {
But posting JSON would clarify if that is true.

displaying json_encode results individually

Hi I was able to display a json data(List of conversation result) but I want to display them just like how I display records from database like this:
foreach(res->fetchAll(PDO::FETCH_ASSOC) as result):
$username = $result['username'];
$message = $result['message'];
endforeach;
are there any similar procedure like this but with json_encode() ?
here is my php script
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd;
$sql7 = "SELECT * FROM ".$tbpre."chat_conversation WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( 'chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$rows = $stmt7->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
This php script are getting its data from my ajax script below
function AjaxRetrieve()
{
var rid = document.getElementById('trg').value,
data = {chat: uid, rid: rid, name: user};
$.ajax({
url: "includes/getChat.php",
type: "GET",
data: data,
dataType: 'json',
success: function(result){
var container = $("#clog");
$.each(result, function(i, message) {
$.each(message, function(key, value) {
container.append($('<p />').html(key + ':' + value));
});
});
}
});
The php and javascript are working fine the JSON are being displayed.. But I'm trying to figure out if there is a way that I can display only the username and the message just how I use the foreach statement that I mentioned above...
I may be misunderstanding, but you should be able to filter what is displayed by adding a condition with an if
$.each(result, function(i, message) {
$.each(message, function(key, value) {
if (key == "username" || key == "message")
container.append($('<p />').html(key + ':' + value));
});
});

Ajax returning an undefine value

I have a search function that is suppose to search a name from the database, and then when the user clicks add, the item choosen has to appear below the search field, in short it has to be posted back so that the user can re-select his/her second option from the search element so that all the selected options can be saved in the database. The problem im facing is that after I click add im getting undefined value back instead of the one I choose and my response is a name instead of an Id number, here is my code and a picture below.
MODEL
public function getName($id)
{
$select = $this->select()
->where('service_provider_id LIKE "' . $id . '%"')
->order('service_provider_name');
return $this->fetchAll($select);
}
CONTROLLER
{
$id = $this->getRequest()->getParam('id');
$mdlserviceprovider = new Model_ServiceProviders();
$serviceprovider = $mdlserviceprovider ->getName($id);
$arr_rtn = array();
if (count($results) > 0){
foreach($results as $result)
{
$myarr = array( 'label' => $result->service_provider_name,
'value' => $result->service_provider_name,
'id' => $result->service_provider_id
);
array_push($arr_rtn, $myarr);
}
}
echo Zend_Json::encode($arr_rtn);
}
PHTML/AJAX
$('#add1').click(function(){
var data = {};
data['sp'] = $("#search").val();
$.ajax({
url:'<?php echo $this->baseUrl()?>/ajax/postserviceprovider/id',
type:'post',
dataType: "json",
data: data,
success:function(data){
var row = '<tr><td>' + data["serviceprovider"] + '</td></tr>';
$('#t1').append(row);
//alert();
}
});
});
Thanks in advance
You can use data["value"] instead of data["serviceprovider"]:
var row = '<tr><td>' + data["value"] + '</td></tr>';
Since you've encoded the array which contains three keys: label, value and id. So there's no serviceprovider key at this moment for Zend to encode.
You are looking for a key that doesn't exist in the array you are returning try this
var row = '<tr><td>' + data['label'] + '</td></tr>';
Or this
var row = '<tr><td>' + data['value'] + '</td></tr>';
As those are the two keys you defined in your PHP page
Try
var row = '<tr><td>' + data[0].value + '</td></tr>';
Also try to put an alert() in the success function like,
alert(JSON.stringify(data));
and see what is included in it..
From what I see I think you are ruturning a multidimensional array from php so I would try something like this in javascript:
$('#add1').click(function(){
var data = {};
data['sp'] = $("#search").val();
$.ajax({
url:'<?php echo $this->baseUrl()?>/ajax/postserviceprovider/id',
type:'post',
dataType: "json",
data: data,
success:function(data){
data.each(function(index, el){
var row = '<tr><td>' + el.label + '</td></tr>';
$('#t1').append(row);
//alert();
}
}
});
});
In your controller try:
$this->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
return $this->_helper->json(array('key1' => $val1, 'key2' => $val2, ...));

Categories