Controller
public function getback(Request $request)
{
$chart = DB::table('BirthChart_1')
->where('FileId', 123)
->get();
foreach ($chart as $key ) {
$f[] = [$key->k1,$key->k2,$key->k3,$key->k4,$key->k5,$key->k6,$key->k7,$key->k8,$key->k9,$key->k10];
}
return response()->json($f);
}
javascript
$(document).ready(function() {
$.getJSON("/getback", function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(val);
});
alert(items);
alert(items[0]);
alert(items[1]);
});
});
http://127.0.0.1:8000/getback
Result...
[[3,4,null,null,null,5,null,null,null,null]]
http://127.0.0.1:8000
Result
alert(items); // 3,4,,,,5,,,,
alert(items[0]); // 3,4,,,,5,,,, (here I want 3)
alert(items[1]); // undefined (here ,I want 4)
What is my mistake in here ? or how to correct it properly ?
Just Changed
alert(items[0][1]);
alert(items[0][2]);
I got answer form #charlietfl Thank you sir ..
Related
Controller Function to get values from DB
public function index(Request $request)
{
$getEvents2 = DB::table("appointments_tbl")
->join("patients_tbl", function($join){
$join->on("appointments_tbl.patient_id", "=", "patients_tbl.id");
})
->select("appointments_tbl.start_time","appointments_tbl.end_time", "patients_tbl.status", "patients_tbl.first_name")
->get();
$events = [];
foreach ($getEvents2 as $values) {
$event = [];
$event['title'] = $values->first_name;
$event['status'] = $values->status;
$event['start'] = $values->start_time;
$event['end'] = $values->end_time;
$events[] = $event;
}
return $events;
}
In the FullCalendar Initialization function, added the function to append the status field value.
events: 'getEvents',
eventDidMount: function(event) {
$('.fc-event-time').append("<br/>" + event.status);
},
Output is undefined
Here is the answer
events: 'getEvents',
eventDidMount: function(info) {
var statusText = info.event.extendedProps.status;
$(info.el).find('.fc-event-time').append("<br/>" + statusText);
},
Thank you so much for the help!
I am getting list of images from a folder for particular ID. Right now I am getting file names but I also want to get upload path.
How to get both data in one function.
Jquery Code:
listFilesOnServer(project_id);
function listFilesOnServer (project_id) {
var items = [];
uploadURI = uploadURI+'/'+project_id;
console.log(project_id+'--KAL--'+uploadURI);
$.getJSON(uploadURI ,function(data,path) {
console.log(data);
$('div #list-group').html("").html(items.join(""));
});
}
Controller Code:
function listFiles() {
$this->load->helper('file');
$project_id = $this->uri->segment(3);
$builders_id = $this->admin_model->getBuilderID($project_id);
$UPLD_PATH = $this->admin_model->builder_UPLD_PATH($builders_id);
$upload_path = "./application/assets/images/" . $UPLD_PATH;
$files = get_filenames($upload_path);
echo json_encode($files);
}
You should modify your controller action so that it returns an json_encode(array('files'=>$yourFiles, 'filePath'=>$yourFilePath) ); like below :
function listFiles() {
$this->load->helper('file');
$project_id = $this->uri->segment(3);
$builders_id = $this->admin_model->getBuilderID($project_id);
$UPLD_PATH = $this->admin_model->builder_UPLD_PATH($builders_id);
$upload_path = "./application/assets/images/" . $UPLD_PATH;
$files = get_filenames($upload_path);
echo json_encode(array('files'=>$files, 'uploadPath'=>$upload_path) );
exit();
}
Then modify your jquery code to handle the json response and extract the response like below :
listFilesOnServer(project_id);
function listFilesOnServer (project_id) {
var items = [];
uploadURI = uploadURI+'/'+project_id;
console.log(project_id+'--KAL--'+uploadURI);
$.getJSON(uploadURI ,function(data,path) {
//Your upload path
console.info("UPLOAD PATH: "+data.uploadPath);
//Your files
console.log(data.files);
//Your processing logic goes here
$('div #list-group').html("").html(items.join(""));
});
}
Ok so the scenario is currently I am populating a drop down list from my model with the following code
ViewBag.LeaseCompanyID = new SelectList(ContractModelEntity.system_supplier.Where(x => x.Type == "Lease"), "CompanyID", "Name", data.LeaseCompanyID);
This works perfectly, however on my form I have a button located next to the drop down list which adds another option in the database, using ajax and a modal popup.
The controller code for this is here
[HttpPost]
public JsonResult AddSupplier([Bind(Include="Name,Type")] system_supplier data)
{
if (ModelState.IsValid)
{
ContractModelEntity.system_supplier.Add(data);
ContractModelEntity.SaveChanges();
return Json(0, JsonRequestBehavior.AllowGet);
}
return Json(1, JsonRequestBehavior.AllowGet);
}
When the new option is added into the database I then need to refresh my dropdownlist to get this new data (currently if I refresh the page I can see the new option). I am using minimalect plugin for the drop downs.
Does anybody know a way of updating this minimalect list, there must be a way of building the list through an ajax call which returns some JSON data.
Thanks in advance for your help
OK so after doing a bit of research here is my solution, hopefully it will help other poeple. Someone might even have a cleaner solution.
I first created a jsonresult controller method which looked like this
[HttpGet]
public JsonResult RetreiveSuppliers(string contractType)
{
var supplierData = ContractModelEntity.system_supplier.Where(x => x.Type == contractType);
var result = new List<object>();
foreach (var x in supplierData)
{
result.Add(new { Id = x.CompanyID, Name = x.Name });
}
return Json(result, JsonRequestBehavior.AllowGet);
}
That got me the data from the database. then I created a javascript on the page which looks like this
$("body").on("click", "#btn_InsertNewSupplier", function () {
var supForm = $("#addSupData");
$.ajax({
url: "#Url.Action("AddLeaseSupplier", "Contract")",
data: supForm.serialize(),
type: "POST",
success: function (result) {
if (result === 0) {
var inst = $.remodal.lookup[$('[data-remodal-id=modal_AddSupplier]').data('remodal')];
inst.close();
NotificationAlert("success", "New Supplier Created");
GetNewSupplierList();
} else {
NotificationAlert("error", "Failed Adding New Supplier");
}
}
});
});
function GetNewSupplierList() {
var actionurl = "#Url.Action("RetreiveSuppliers", "Contract", new { contractType = "Lease"})";
$.getJSON(actionurl, tempdata);
}
function tempdata(response) {
if (response != null) {
var html = "";
for (var i = 0; i < response.length; i++) {
html += '<option value="' + response[i].Id + '">' + response[i].Name + '</option>';
}
$("#LeaseCompanyID").html(html);
}
}
So once the ajax call is successful it will trigger the GetNewSupplierList function which calls my controller method and returns some JSON data. Once that is returned it calls tempdata, which builds the new HTML for my select picker, once that is built it updates the html on the selectpicker id.
Works like a charm!!!
Thanks to everyone who took a look at this post.
I am using JS to submit data without loading the page and it is working fine, on response i am trying to send JSON which looks like this
{"mes":"<div class=\"alert alert-success\">Your goal has been updated.<\/div>","graph_data":"[['07\/9\/2014',500],['07\/8\/2014',900],['07\/7\/2014',1200],['07\/6\/2014',500],['07\/5\/2014',500],['07\/4\/2014',500],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000]]"}
There are two items in the JSON response mes and graph_data. Now how can i make use of graph_data and mes seperately?
If I do this alert(data); this shows the above JSON response
But if I do the following I cant get them to alert seperately.
alert(data.graph_data);
alert(data.mes);
I will really appreciate if anyone can guide me on how to separate the two.
Update
This is the JS i am using to send and retrieve data on click of a button
$('#goalgraphdatasubmit').click(function () {
$('#goalgraphupdateform').submit();
});
$('#goalgraphupdateform').submit(function (e) {
"use strict";
e.preventDefault();
document.getElementById("goalgraphdatasubmit").innerHTML = "saving..";
var post = $('#goalgraphupdateform').serialize();
var action = $('#goalgraphupdateform').attr('action');
$("#holiday_goal_message").slideUp(350, function () {
$('#holiday_goal_message').hide();
$.post(action, post, function (data) {
$('#holiday_goal_message').html(data);
document.getElementById('holiday_goal_message').innerHTML = data;
$('#holiday_goal_message').slideDown('slow');
document.getElementById("goalgraphdatasubmit").innerHTML = "Submit";
alert(data);
if (data == '<div class="alert alert-success">Your goal has been updated.</div>') {
//$('#divGoal').load('dashboard-goals.php');
$("#holiday_goal_message").hide(2000);
updatetestGraph();
}
});
});
});
Use Like
var data = JSON.parse('{"event1":{"title":"My birthday","start":"12\/27\/2011 10:20 ","end":"12\/27\/2011 00:00 "},"event2":{"title":"My birthday again","start":"12\/27\/2011 10:20 ","end":"12\/27\/2011 00:00 "}}');
arr = []
for(var event in data){
var dataCopy = data[event]
for(key in dataCopy){
if(key == "start" || key == "end"){
// needs more specific method to manipulate date to your needs
dataCopy[key] = new Date(dataCopy[key])
}
}
arr.push(dataCopy)
}
alert( JSON.stringify(arr) )
Demo1
Demo2
Sorry cannot comment so have to answer
I have taken your JSON string in a variable here and it gives me proper result
See here
var d = {"mes":"<div class=\"alert alert-success\">Your goal has been updated. <\/div>","graph_data":"[['07\/9\/2014',500],['07\/8\/2014',900],['07\/7\/2014',1200],['07\/6\/2014',500],['07\/5\/2014',500],['07\/4\/2014',500],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000]]"};
alert(d.graph_data);
alert(d.mes);
So basically I'm making cURL request and getting response that looks like this(var_dump):
string(595) "{"user_id":1,"currency":"eur","purchase_packs":{"1":{"amount":500,"allowed_payment_methods":["ideal","paypal","visa","mc"]},"3":{"amount":1000,"allowed_payment_methods":["mc","ideal","paypal","visa"]},"6":{"amount":2500,"allowed_payment_methods":["mc","ideal","paypal"]},"8":{"amount":5000,"allowed_payment_methods":["ideal"]},"9":{"amount":10000,"allowed_payment_methods":["ideal"]}},"payment_methods":{"ideal":{"name":"ideal","allow_recurring":false},"paypal":{"name":"paypal","allow_recurring":false},"visa":{"name":"visa","allow_recurring":false},"mc":{"name":"mc","allow_recurring":false}}}"
What I want is to access it in the JS file like this:
success: function (data) {
alert(data.user_id);
}
But I don't know how to convert(?) it properly.
And my next step(question) after that will be if I can do a for loop for every purchased pack, so I can create button for each one of them
Probably something like this:
var pack;
var packs = data.purchase_packs;
for (pack= 0; pack < packs.length; pack++) {
console.log(packs[pack]);
}
I'm tried to understand your "question"....
In js:
$.post('/some/url',{query: 'somequery'},
function (data) {
try {
data = JSON.parse(data);
} catch (e) {
return false;
}
console.log(data);
});
In PHP:
data = json_decode(rtrim($myJSONEncodedString, "\0"));
if (!empty($data->purchase_packs)
foreach ($data->purchase_packs as $key => $value)
var_dump($value);
After receiving response using cURL, just echo that json string between <script></script> tag.
Then json string will look like:
<script>
var jsondata = {"user_id":1,"currency":"eur","purchase_packs":{"1":{"amount":500,"allowed_payment_methods":["ideal","paypal","visa","mc"]},"3":{"amount":1000,"allowed_payment_methods":["mc","ideal","paypal","visa"]},"6":{"amount":2500,"allowed_payment_methods":["mc","ideal","paypal"]},"8":{"amount":5000,"allowed_payment_methods":["ideal"]},"9":{"amount":10000,"allowed_payment_methods":["ideal"]}},"payment_methods":{"ideal":{"name":"ideal","allow_recurring":false},"paypal":{"name":"paypal","allow_recurring":false},"visa":{"name":"visa","allow_recurring":false},"mc":{"name":"mc","allow_recurring":false}}};
</script>
Then, your javascript code between <script></script>. Like this:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
alert(jsondata.user_id); // return user_id value
jQuery.each(jsondata.purchase_packs, function(i, val) {
alert(val.amount); // return amount
var paymentMethod = val.allowed_payment_methods;
jQuery.each(paymentMethod, function() {
alert(this); // will return all payment gateway method
});
});
</script>
Hope will help!