I have been trying all the help available on different forums but now give up and posting my question here. Trying to populate dropdown using ajax call. Getting the data in json format successfully. But don't know to fill dropdown. code below:
Controller:
function getRegion()
{
$this->load->model('Settings_model');
$title = $this->input->get('title');
$result = array("region" => $this->Settings_model->getSelectedRegion($title));
echo json_encode($result);
}
View:
$(document).on('change', '#campaignSel', function() {
changecampaign();
});
function changecampaign(){
var title= "New Normal";//$('#campaignSel option:selected').text();//$('#campaignSel').text();
$regionSel = $("#regionSel");
$.ajax({
type:"GET",
url: "<?php echo base_url('Pricecomparison/getRegion'); ?>",
data:{ "title":"New Normal"},
datatype: "json",
success: function(result){
var appenddata;
$.each(result, function (key, value) {
appenddata += "<option value = '" + value.id + " '>" + value.region + " </option>";
});
$('#regionSel').html(appenddata);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
Response: {"region":[{"id":"1","region":"109 FEATHERSTON ST (ELEC)\r\n"},{"id":"2","region":"ASHBURTON/MID CANTERBURY
ELEC"}]}
I want to fill dropdown with Regions.
you need to loop the region like this $.each(result.region, function (key, value) { instead of result
Update1:
added if condition if ($.isArray(result.region)){ ... }
result = {"region":[{"id":"1","region":"109 FEATHERSTON ST (ELEC)\r\n"},{"id":"2","region":"ASHBURTON/MID CANTERBURY ELEC"}]}
var appenddata='';
if ($.isArray(result.region)){
$.each(result.region, function (key, value) {
appenddata += "<option value = '" + value.id + " '>" + value.region + " </option>";
console.log(appenddata);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Finally I resolved the issues in my code. I like to share the changes I made to my code below:
added:
contentType: "application/json",
and
parsedobj = JSON.parse(result)
so the final ajax code is:
$.ajax({
type:"GET",
url: "<?php echo base_url('Pricecomparison/getRegion'); ?>",
data:{ "title":title},
contentType: "application/json",
datatype: "json",
success: function(result){
parsedobj = JSON.parse(result)
var appenddata='';
$.each(parsedobj.region, function(index, value)
{
appenddata += "<option value = '" + index + "'>" + value.region + " </option>";
});
$('#regionSel').html(appenddata);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
Related
I got the following ajax response.
{"ord_item_Json_string":"[{\"code\":\"1002\",\"item\":\"Diamond Softy\",\"size\":\"15 inch\",\"color\":\"Light Blue\",\"qty\":\"2\",\"price\":\"849.45\",\"amount\":\"1698.90\"},{\"code\":\"1001\",\"item\":\"sAMPLE\",\"size\":\"Cob\",\"color\":\"Naturtal\",\"qty\":\"5\",\"price\":\"434.05\",\"amount\":\"2170.25\"}]"}
now the problem is that i want to display only code and item fields & value but i am unable. please help me how to access that fields.
my code is following.
$.ajax({
url: base_url + 'order_jobcard/getOrderDetails/' + ord_id,
type: "POST",
data: JSON.stringify($('ord_id').serializeArray()),
success: function (data) {
$("#OrdItem").html(data);
console.log(data);
return true;
},
error: function () {
alert('Not Working');
$('#ord_buyer_pack_inst').empty();
}
});
Try this:
var abc = {"ord_item_Json_string":"[{\"code\":\"1002\",\"item\":\"Diamond Softy\",\"size\":\"15 inch\",\"color\":\"Light Blue\",\"qty\":\"2\",\"price\":\"849.45\",\"amount\":\"1698.90\"},{\"code\":\"1001\",\"item\":\"sAMPLE\",\"size\":\"Cob\",\"color\":\"Naturtal\",\"qty\":\"5\",\"price\":\"434.05\",\"amount\":\"2170.25\"}]"}
var a = JSON.parse(abc.ord_item_Json_string)
$.each(a, function(index,value){
console.log(value.code+'--'+value.item)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
try the code below...in success callback you will be getting data in json object format. so just get value using its key.
$.ajax({
url: base_url + 'order_jobcard/getOrderDetails/' + ord_id,
type: "POST",
data: JSON.stringify($('ord_id').serializeArray()),
success: function (jsonResponse) {
var itemsList = jsonResponse.ord_item_Json_string;
$.each(itemsList, function (index, value) {
console.log(value.code + '--' + value.item);
});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error");
}
});
try this: you can try below code where you can iterate over json array and read each attribute
$.ajax({
url: base_url + 'order_jobcard/getOrderDetails/' + ord_id,
type: "POST",
data: JSON.stringify($('ord_id').serializeArray()),
success: function (data) {
var dataStr = "";
var jsonData = data.ord_item_Json_string; // this is already json
jsonData = JSON.parse(jsonData);//value need to parse
for (var i = 0; i < jsonData.length; i++) {
var ord= jsonData[i];
console.log(ord.code);
dataStr += ord.code;
}
$("#OrdItem").html(dataStr);
console.log(data);
return true;
},
error: function () {
alert('Not Working');
$('#ord_buyer_pack_inst').empty();
}
});
JSFiddle
I am trying to pass parameter from $.ajax post to mysqli_query
this is my ajax
$.ajax({
type: 'post',
url: 'edit-doctor.php',
data: "imei="+imei,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
$.each(data, function() {
$.each(this, function(k , v) {
trHTML += '<tr><td><b>'+ k.toString() + '</b></td> : <td>' + v.toString() + '</td></tr>';
})
})
$("#target_table_id").append(trHTML);
}
});
this is my php
<?php
include("connect.php");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$src1= $_POST["imei"]; //.. getting variable in src1
$sql = "select * from tbl_beacons where imei = '".$src1."' ";
//$sql = "select * from tbl_beacons where imei = '".$_POST['imei']."' ";
// also tried this
$result = $conn->query($sql);
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
$conn->close();
problem is that I am able to get parameter but not able to pass in query and get result . if i send hardcore value then query is working fine
what I can modify to get parameter value and send it
EDIT:
i also figured out and modfied ajax , this also working
$.ajax({
type: "POST",
url: "edit-doctor.php",
data: {imei:imei},
success: function (data) {
$.each(JSON.parse(data), function() {
$.each(this, function(k , v) {
trHTML += '<tr><td><b>'+ k.toString() + '</b></td> : <td>' + v.toString() + '</td></tr>';
})
})
$("#target_table_id").append(trHTML);
}
});
data: "imei="+imei, is not JSON. Try data: {imei:imei},
if you send JSON you need to receive JSON too
You can also just remove the contentType: "application/json; charset=utf-8", dataType: "json",
Even better:
$.post('edit-doctor.php', {"imei":imei},function (data) {
var trHTML=[];
$.each(data, function() {
$.each(this, function(k , v) {
trHTML.push('<tr><td><b>'+ k + '</b></td> : <td>' + v + '</td></tr>');
})
})
$("#target_table_id").append(trHTML.join(''));
});
All that I am trying is to iterate the data I have in the database using the Jquery each method, but couldn't figure when I am losing it all. Can someone look through this piece of code and tell me what I am doing wrong ?
$(function(){
var output = $("#folderOne");
$.ajax({
url: 'http://......',
dataType: 'json',
// data: {action: 'output'},
success: function(data, status){
console.log(data);
$.each(data, function(index, value) {
if (value.f_id == 1) {
var cards = "<div class='thumb'>" + value.f_id +
"</div><br>" + "<p>" + value.title + "</p> ";
}
output.append(cards);
});
},
I have seen some other posts in Stackoverflow which were related. Tried that code but it did not work out for me.
actually i have a database with 2 images of an actress in my MYSQL database. I am generating JSON data using PHP and it works fine.
Link for JSON data
I am trying to parse it with Javascript as shown in this fiddle
Direct Parsing Fiddle Link
var json = [{
"id": "1",
"url": "http:\/\/i.imgur.com\/J8yqh3y.jpg"
}, {
"id": "2",
"url": "http:\/\/i.imgur.com\/WNx9i2c.jpg"
}];
var nazriya = json;
$.each(nazriya, function (index, nazriya_nazim) {
$('#url-list').append('<li>' +
'<h4>' + nazriya_nazim.url + '</h4>' +
'</li>');
});
and it works fine.
But if i try to parse it from my PHP file located in my domain. It does not display anything. It shows blank page.
FIDDLE Link : Parsing JSON data on PHP File
type: "POST",
dataType: 'json',
url: "http://chipap.com/apps/nazriya_nazim/test1.php",
success: function (data) {
alert("1");
//var obj = jQuery.parseJSON(idata);
var json = JSON.parse(data);
$.each(json, function (index, nazriya) {
$('#url-list').append('<li>' +
'<h4>' + nazriya.url + '</h4>' +
'</li>');
});
}
I did not write all these code on my own. Browsed Stack and found solutions. But stuck up at the last step (parsing from a PHP file located in my server).
As said by #DaGLiMiOuX tried it in a separate HTML document.
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "http://chipap.com/apps/nazriya_nazim/test1.php",
success: function (data) {
alert("1");
var json = data;
$.each(data, function (index, nazriya) {
$('#url-list').append('<li>' +
'<h4>' + nazriya.url + '</h4>' +
'</li>');
});
},
error: function(jqXHR, status, errorText) {
alert('Status code: ' + jqXHR.status +
'\nStatus text: ' + status + '\nError thrown: ' + errorText);
}
});
</script>
</head>
<body>
<ul id="url-list"></ul>
</body>
Now also it shows the same error.
In your client side specified the jsonpcallback as below
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "http://chipap.com/apps/nazriya_nazim/test1.php",
jsonpCallback: function(data){
alert('generate a specified jsonp callback');
return "jsonpCall";
},
success: function (data) {
alert("1");
var json = data;
$.each(data, function (index, nazriya) {
$('#url-list').append('<li>' +
'<h4>' + nazriya.url + '</h4>' +
'</li>');
});
},
error: function(jqXHR, status, errorText) {
alert('Status code: ' + jqXHR.status +
'\nStatus text: ' + status + '\nError thrown: ' + errorText);
}
});
In http://chipap.com/apps/nazriya_nazim/test1.php
<?php
$callback = $_GET["callback"]; // return "jsonpCall" that was specified in jsonpCallback ajax with jsonp
$json = '[{"id":"1","url":"http:\/\/i.imgur.com\/J8yqh3y.jpg"},{"id":"2","url":"http:\/\/i.imgur.com\/WNx9i2c.jpg"}]' ;
echo $callback.'('. $json.')' ;
?>
You can understand much better about jsonp at at http://en.wikipedia.org/wiki/JSONP
http://jsfiddle.net/channainfo/wn5bz/
1) that's just an extract of a code, not a compiling function. The complete code would be
$.ajax({
type: "POST",
dataType: 'json',
url: "http://chipap.com/apps/nazriya_nazim/test1.php",
success: function (obj) {
alert("1");
$.each(obj, function (index, nazriya) {
$('#url-list').append('<li>' +
'<h4>' + nazriya.url + '</h4>' +
'</li>');
});
}
});
2) you need to import jQuery (you don't do it in the fiddle)
XMLHttpRequest cannot load
http://chipap.com/apps/nazriya_nazim/test1.php. Origin
http://fiddle.jshell.net is not allowed by
Access-Control-Allow-Origin.
You have to handle ALWAYS posible errors.
Check this demo.
This should work, but you got Access-Control-Allow-Origin error. This is caused because your dataType was incorrect. Try this configuration for your ajax call:
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "http://chipap.com/apps/nazriya_nazim/test1.php",
success: function (data) {
alert("1");
var json = data;
$.each(data, function (index, nazriya) {
$('#url-list').append('<li>' +
'<h4>' + nazriya.url + '</h4>' +
'</li>');
});
},
error: function(jqXHR, status, errorText) {
alert('Status code: ' + jqXHR.status +
'\nStatus text: ' + status + '\nError thrown: ' + errorText);
}
});
NOTE: You get in the demo an alert as if it were an error, but your status code is 200 (check status codes). Try it in your project. Maybe JsFiddle it's not allowing to return data from external servers.
I have a php file with encoded json. What I would like to do is to get each data(maxVote and Id) from encoded json
Here is my php file named results.php
<?php
$result = array();
array_push($result,array("maxVote"=>300,"id"=>"li_2"),array("maxVote"=>200,"id"=>"li_1"));
echo json_encode($result);
?>
Since I am new to ajax and json,
what are the codes to put on success so that i will get each maxVote's and each id's
$.ajax({
url: "results.php",
success: function(){
...
}
});
Thanks in advance!
You can use:
$.ajax({
dataType: "json",
url: 'results.php',
success: function(data){
var items = [];
$.each(data, function(key, val) {
items.push(key + ' : ' + val + '</br>');
});
$('body').append(items.join(''));
}
});
or
$.getJSON('results.php', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(key + ' : ' + val + '</br>');
});
$('body').append(items.join(''));
});
Add the data parameter to your success function:
$.ajax({
url: "results.php",
success: function(data){
$.each(data, function(id, elt) {
// use data[id].maxVote or elt.maxVote
}
}
});