How to show array result in ajax success using codeigniter? - ajax

I am fetching values from data using where in() mysql query and I got the correct result, but I don't know how to display the result in ajax success.
How do I display company name and email id from result data set?
my ajax code
<script type="text/javascript">
$('#ok').on('click', function() {
var vals = $('#show').val();
$.ajax({
type: "POST",
url: "<?php echo base_url();?>email/get_company",
data: { vals:vals },
datatype: 'json',
success: function (data) {
alert(data);
$("#result").html(data);
var result = JSON.parse(data);
}
});
});
</script>
my controller code:
function get_company()
{
$vals = $this->input->post('vals');
$query = $this->db->query("SELECT * FROM customer` where company_id IN ($vals) ")->result();
echo json_encode($query);
}
my result:
[{"company_name":"xyz Ltd","company_email":"123#gmail.com"},{"company_name":"wer Jit","company_email":"2222#gmail.com"}]

assuming you get this json in your ajax success:
const json = '[ {
"company_name": "xyz Ltd",
"company_email": "123#gmail.com"
},
{
"company_name": "wer Jit",
"company_email": "2222#gmail.com"
}]
';
const obj = JSON.parse(json);
// you don't need this line, if you have set ajax datatype:'json'
you can get results for a single data set:
console.log(obj[0].company_name);
// this is how to get the first company name of the data set
// expected output: "xyz Ltd"
or you can loop through the whole data set
obj.forEach(element => $("#result").append(element.company_name + '<br>'));
see a working example
conclusion: your ajax function could look just simply like this:
$.ajax({
type: "POST",
url: "<?php echo base_url();?>email/get_company",
data: {
vals: vals
},
datatype: 'json',
success: function(data) {
obj.forEach(data => $("#result").append(data.company_name + '<br>'));
}
})

Related

Ajax request jquery

Need
Pull PlanId from the Get variable send it to Web Service and I have GetPlanInfo function
Get the details of the package and display them
var MainServiceURL = 'http://someWebService';
var plan=[];
function planInit()
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: MainServiceURL + "/GetPlanInfo",
data: {"ID" : ID ,"countryID" : CountryID},
success: function(response) {
plan = response.d;
main();
}
});
}
function main(plan)
{
document.getElementById("costPerMonth").innerHTML = plan.CostPerMonth;
document.getElementById("firstMonthPrice").innerHTML = plan.FirstMonthPrice;
document.getElementById("planName").innerHTML = plan.Name;
document.getElementById("landline").innerHTML = plan.Landline;
document.getElementById("mobile").innerHTML = plan.Mobile;
}
Where error?
Within the function main you treat a plan variable like a known object and you try to access its properties. However, plan is only an argument for the function main, which you don't pass once you get the response from your request. Look at:
success: function(response) {
plan = response.d;
main();
}
When you write like this, you call main function without passing plan argument. It should look like:
success: function(response) {
plan = JSON.parse(response).d;
main(plan);
}
Because as a response you only get a string - you have to translate it to JSON object using JSON.parse function.

function is callign but Ajax is not calling

Here I am using codeigniter with highchart. Highchart will change after dropdown select by calling ajax.
Here, function is called but ajax is not calling. So, where I go wrong with this.
This is my ajax:
$('.edit').click(function(e)
{
e.preventDefault();
$.ajax({
url: '<?php echo site_url("Chart/branchwiseactivity");?>',
type: 'POST',
data: {
series: []
},
dataType: 'json',
success: function(json)
{
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.series[1] = json[2];
options.series[2] = json[3];
options.series[3] = json[4];
chart = new Highcharts.Chart(options);
}
});
e.preventDefault();
});

Checking all JSON values for a specific attribute/parameter

I am trying to check a JSON for the "start" object, and what it value is.
For example, if my AJAX is
$(document).ready(function () {
$.ajax({
url: "Content/events/document.json",
type: "GET",
success: function (resp) {
alert(JSON.stringify(resp)); //Stringify'ed just to see JSON data in alert
},
error: function () {
alert("failed");
}
});
});
and it returns
[
{"title":"Bi-weekly Meeting1","start":"2014-07-09","color":"red"},
{"title":"Bi-weekly Meeting2","start":"2014-08-06","color":"red"},
{"title":"Bi-weekly Meeting3","start":"2014-07-23","color":"red"},
{"title":"Test Event","url":"http://google.com/","start":"2014-07-28"}
]
How can I check every "start" value? and if it is today, store that event in a different array?
I just want to keep track of today's events and I am not sure how to iterate through a JSON Object.
Note you should set dataType: "json" so that JQuery will parse the ajax response coming back as JSON automatically. Then just iterate through the array you receive, like so:
function sameDay( d1, d2 ){
return d1.getUTCFullYear() == d2.getUTCFullYear() &&
d1.getUTCMonth() == d2.getUTCMonth() &&
d1.getUTCDate() == d2.getUTCDate();
}
$(document).ready(function () {
$.ajax({
url: "Content/events/document.json",
type: "GET",
dataType: "json",
success: function (resp) {
resp.forEach(function(item) {
console.log(item.start);
if (sameDay( new Date(item.start), new Date)){
// This one has today's date!
}
});
},
error: function () {
alert("failed");
}
});
});

How to dynamically pass data parameter in a jquery ajax call (multiple arrays of data)

I have this ajax code:
return $.ajax({
type: "POST",
url: "somefile.php",
cache:false,
data: { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() },
dataType:"json",
success: function(data){
alert("success");
}
This works fine, but I need to pass the data parameter dynamically. For now I need the above data parameter content and a single string.
How do I pass this dynamically? / How do I store it in a variable and pass it to the "data:" field?
{ "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() }
I tried JSON.stringify I I couldn't get it to work probably due to the data being an array.
The year and genre arrays are coming directly from the jquery drop down menu. It is selected like by it's #id like so "$("#yearFilter")". This is the select form element.
<select multiple="multiple" name="yearFilter[]" class="filterChange" id="yearFilter">
What I need at the base level is:
var someData = "";
if(...){
someData = { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() };
}
else if(...){
someData = "sampleString";
}
And in ajax call:
...
data: someData,
...
I think I have an idea what you want but post has been overly complicated by extraneous issues like json stringify . Here's a function that could be used in several places eleswhere in your code to make one type of AJAX call or another.
You would then perhaps have several buttons and call the function within handlers for each type of button and change the argument passed to function
doAjax('someval');/* use in button 1*/
doAjax('someOtherval');/* use in button 2*/
function doAjax(arg) {
var someData = "";
if (arg == 'someval') {
someData = {
"yfilter": $("#yearFilter").val(),
"gfilter": $("#genreFilter").val()
};
} else {
someData = "sampleString";
}
$.ajax({
type: "POST",
url: "somefile.php",
cache: false,
data: someData,
dataType: "json",
success: function(data) {
if (arg == 'someval') {
alert("success 1");
} else {
alert("success 2");
}
}
})
}
Hope I've understood what you're asking for.
You could do something like this:
var parameters = {};
if (...) {
parameters = $("#yearFilter").serializeArray();
}
if () {
parameters = $("#genreFilter").serializeArray();
}
and then replace the line:
parameters: { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() },
with:
data: parameters,
JSON type should be best option for dynamically data. push whatever data you wish to inside json like shown below, Hence create your json dynamically and send as ajax data.
var employees = {
accounting: [],
dept: "HR"
};
employees.accounting.push({
"firstName" : item.firstName,
"lastName" : item.lastName,
"age" : item.age
});
$.ajax({
url: POSTURL,
type: 'POST',
dataType: 'json',
data : employees,
contentType: 'application/json; charset=utf-8',
success: function (results)
{
},
error: function (results)
{
jQuery.error(String.format("Status Code: {0}, ", results.status, results.statusText));
}
});
Try it:
someData = JSON.stringify({ yfilter: $("#yearFilter").val(), gfilter: $("#genreFilter").val() });
It will work.

how do you make ajax data key dynamic in jquery?

I'm trying to make my inline edit to be dynamic so it will just depend on some data- attributes from my markup so here's the code for now:
$(".inline-edit").editable(
function(value, settings) {
var editableField = $(this);
$.ajax({
type: 'PUT',
url: editableField.attr('data-href'),
dataType: 'html',
success: function(html) {
editableField.parents('.replaceable').replaceWith(html);
},
data: { 'regression_test_environment[name]' : value }
});
return(value);
},
{
event: 'click',
width: '80%',
height: '20',
submit : 'OK'
}
)
i want the name in regression_test_environment[name] to be editableField.attr('data-column-name') but it always fails in compiling because it keeps taking the key as a string. I tried making a variable after the editable field variable assignment and building the string as a different variable but it doesn't want to evaluate the key as a function.
Is there a way to do this? or am i stuck in creating a separate .editable call for each of my editable fields?
You may try like this:
var name = editableField.data('column-name');
var values = { };
values['regression_test_environment[' + name + ']'] = value;
$.ajax({
type: 'PUT',
url: editableField.data('href'),
dataType: 'html',
data: values,
success: function(html) {
editableField.parents('.replaceable').replaceWith(html);
}
});
Better, less confusing answer:
var data = {};
data[thisField] = $(this).text();
$.ajax({
data: data
});
Best is to pass dynamic values by serializing it :
var data = $('#formid').serialize(); // serialize all the data in the form
$.ajax({
url: 'test.php', // php script to retern json encoded string
data: data, // serialized data to send on server
...
});

Resources