How to access multidimensional associative json arrays from AJAX jquery function - javascript

I have to return a return a multidimensional associative arrays from PHP page for a jQuery AJAX function.
This is my PHP page called 'seachsongs.php'
<?php
$brano = $_POST['brano'];
$sql = "SELECT Titolo, Autore FROM Brani WHERE Titolo = '$brano';";
$ris = $conn->query($sql);
while ($row = $ris->fetch_array()) {
$arr[] = $row;
}
echo json_encode(array('data' => $arr));
?>
This is my jQuery AJAX function
$(document).ready(function () {
$('#nBrano').keyup(function () {
nomeBrano = $(this).val();
$.ajax({
type: "POST",
data: {brano: nomeBrano},
url: "searchsong.php",
success: function (data) {
document.write(data);
//alert("Prova" + data['data'][0]["Titolo"]);
/*if (msg != 'null') {
$('#similarSongs').css('display', 'block');
/*$.each(prova, function (key1, value1) {
$.each(value1['two']['three'], function (key1, value1) {
document.write('test');
});
})
$('#similarSongs table').html(tabella);
}
if (msg == 'null') {
$('#similarSongs table').html("Nessun brano simile trovato");
$('#similarSongs').css('display', 'block');
}*/
},
error: function () {
//alert('errore');
}
});
});
});
How can I access to array data from jQuery? What is the correct statement?
alert(data)
print this
{"data":[{"0":"Animals","Titolo":"Animals","1":"Martin Garrix","Autore":"Martin Garrix"},{"0":"Animals","Titolo":"Animals","1":"Maron V","Autore":"Maron V"}]}{"data":[{"0":"Animals","Titolo":"Animals","1":"Martin Garrix","Autore":"Martin Garrix"},{"0":"Animals","Titolo":"Animals","1":"Maron V","Autore":"Maron V"}]}
PS: sorry form my bad english.

I've set the data type of this request to be json, so the response returned should be a json object. You can access it by this way:
$(document).ready(function () {
$('#nBrano').keyup(function () {
nomeBrano = $(this).val();
$.ajax({
type: "POST",
data: {brano: nomeBrano},
url: "searchsong.php",
dataType:'json',
success: function (response) {
for(var i=0; i<response['data'].length; i++){
console.log(response['data'][i][/*your_target_index*/]);
}
},
error: function () {
//alert('errore');
}
});
});
});
see more about ajax

Related

When I do two operations when select change in javascript error

When I request different data than pressing select, it does not perform a single operation, and when they are combined, only one operation is performed,
It does a process called getStatesByCountryId but it doesn't call get_shipping_price, and because I'm requesting information from two different tables I can't merge them,
And when we merge them, the information is not sent to the span text, so I preferred to separate them,
I using a php codeigniter framework
javascript code:
$("select[name='country']").change(function () {
var countryId = $(this).val();
$.ajax({
url: "/Ajax/getStatesByCountryId",
method: "post",
data: { countryId },
success: function (data) {
var rJson = $.parseJSON(data);
if (rJson.status === true) {
$("select[name='state']").html("");
$.each(rJson.data, function (e, v) {
$("select[name='state']").append(
"<option value='" + v.id + "'>" + v.name + "</option>"
);
});
} else {
$("select[name='state']").html("");
}
}
});
});
$("select[name='country']").change(function () {
var countryname = $(this).val();
$.ajax({
url: "/Ajax/get_shipping_price",
method: "post",
data: { 'countryname': countryname },
success: function (data2) {
if (data2) {
$("span[name='shipping_price']").text(data2.shipping_price);
} else {
$("span[name='shipping_price']").text("");
}
}
});
});
Ajax Code:
public function get_shipping_price()
{
$countryName = $this->request->getPost("countryname");
$result = $this->con->query("SELECT shipping_price FROM table2 WHERE country = '{$countryName}'")->getResult();
if ($result) {
$data2 = array('shipping_price' => $result[0]->shipping_price);
} else {
$data2 = array('shipping_price' => 0);
}
echo json_encode($data2);
}
public function getStatesByCountryId()
{
$countryId = $this->request->getPost("countryId");
$states = $this->con->query("select * from table where ID = {$countryId}")->getResult();
if ($states) {
$data = [
"status" => true,
"data" => $states
];
} else {
$data = [
"status" => false
];
}
echo json_encode($data);
}
and here respon:

How can I filter the office id using codeigniter?

I am a student who is practicing Codeigniter. This is the script that I have formed.
$(document).ready(function () {
$('#hiddenDO').each(function () {
$('#displayoffice').val($("#hiddenDO option:selected").val());
$.ajax({
type: "GET",
url: '<?= site_url('client/displayoffice') ?>',
data: {"msg":msg},
dataType:"json",
success: function (data) {
console.log(data);
}
});
return false;
});
}
Controller
public function displayoffice() {
$data = $this->input->post();
$result['hiddenDO'] = $data;
echo json_encode(array($result));
exit(0);
}
and my Model
function filterOffice() {
$data = '3'; //In this part I want to call the value to filter
$query=$this->db->query("SELECT bi_emplname, bi_empfname, bi_emppic FROM `tblemployee`
INNER JOIN `tbl_office` ON ji_off_id=off_id
INNER JOIN `tbl201_basicinfo` ON bi_id=ji_bi_id
WHERE ji_off_id='$data'");
return $query->result_array();
}

CodeIgniter Ajax call

ajax call does not hit to controllers function, what is the reason and why I am not understanding kindly guide me
I am trying to send ajax call to controller update the record this is my ajax code
$(document).ready(function() {
$(".update").click(function(event) {
debugger;
event.preventDefault();
var vehno = $("input#vn").val();
var vbrand = $("input#vb").val();
var vmodel = $("input#vm").val();
var vcolor = $("input#vcol").val();
debugger;
$.ajax({
type: "ajax",
method:"Post",
url:'<?php echo base_url('index.php/vehicleCtrl/FunUpdate')?>',
//async:false,
dataType: 'json',
data: {vehicle: vehno, brand: vbrand, vmodel:vmodel,vcolor:vcolor},
success: function(res) {
alert("working");
// if (res)
// {
// // Show Entered Value
// jQuery("div#result").show();
// jQuery("div#value").html(res.username);
// jQuery("div#value_pwd").html(res.pwd);
// }
},
error:function(res){
alert(res);
}
});
});
});
this Controller's Function
this is a codeigniter controller
public function FunUpdate()
{
$as= $this->input->post('vehicle');
$id=-1;
$vehicleArray = array('vehicleNo' => $this->input->post('vehicle'),
'Brand' => $this->input->post('brand'),
'Model' => $this->input->post('vmodel'),
'Color' => $this->input->post('vcolor'),
);
echo json_encode($vehicleArray);
$Result=$this->VehicleModel->Update($vehicleArray,$no);
if($Result)
{
$data= array('error' =>'Vehicle Update Successful');
$data["DetailList"]=$this->VehicleModel->FunDetailSearch($no);
$data["EditTrack"]=$this->VehicleModel->EditTrackDetail($id);
$data["NewVehicle"]=$this->VehicleModel->FunfindVehicle($no);
$this->load->view('Layout/header');
$this->load->view('vehicle/create',$data);
$this->load->view('Layout/footer');
}
}
ajax request should look like this
$('#buttonid').click(function(){
var vehno = document.getElementById('vehno').value;
var brand = document.getElementById('brand').value;
$.ajax({
url:'<?=base_url()?>index.php/Controller/function',
method: 'post',
data: {vehno: vehno, brand: brand},
dataType: 'json',
success: function(response){
alert('data updated');
}
});
});
function
public function updateDetails(){
// POST data
$postData = $this->input->post();
//load model
$this->load->model('Main_model');
// get data
$data = $this->Main_model->updateVehicle($postData);
echo json_encode($data);
}
Modal
function updateVehicle($postData){
$response = array();
if($postData['id'] ){
$this->db->where('id',$postData['id']);
return $this->db->update('vehicle',$postData);
}
Hope Now You Update Your Data With Ajax

Not able to display the JSON success output in the view or alert

I am using CodeIgniter, I have a three input field called as name, emp_id,crm_id. I am entering the id value and sending to the controller to get all the information related to that id using AJAX an JSON. Now the issue is, I am getting the correct output in the network tab but not able to display in the view page even alert is also not displaying in the JSON.
Sometimes I am getting below error because of JSON is empty
[Show/hide message details.] SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
I think there is some issue with JSON.
Ajax
$("form[name='search_addSalaryrecord']").validate({
// errorElement: 'div',
submitHandler: function(form) {
//alert(baseUrl);
var employee_name = $('#employee_name').val();
var crm_id = $('#crm_id').val();
var employee_id = $('#employee_id').val();
$.ajax({
url: baseUrl + "/Employee_control/search_addSalaryrecord",
method: "POST",
dataType: "json",
data: {employee_name: employee_name,crm_id:crm_id,employee_id:employee_id},
success: function(response) {
//$('.search_record tbody').html(response);
// var data = JSON.parse(response);
//alert(data.status);
if (response.status === 'error')
{
alert(response.msg);
}
if (response.status === 'success') {
//alert('data avaliable');
alert(response.records);
console.log(response.records);
}
}
//error: function(error) { console.log(error); }
});
}
});
Controller
public function search_addSalaryrecord()
{
$employee_name=trim($this->input->post('employee_name'));
$emp_crmid=trim($this->input->post('crm_id'));
$employee_id=trim($this->input->post('employee_id'));
if((!empty($employee_name)) ||(!empty($emp_crmid)) || (!empty($employee_id))){
$arr_result =$this->Employee_model->get_salary_search_emp_id($employee_name,$emp_crmid,$employee_id);
if (!empty($arr_result)){
foreach ($arr_result as $row)
{
$result[] = array(
"name" => $row->firstname.' '.$row->lastname,
"mobileno" => $row->mobileno,
"email_id" => $row->email_id,
"employee_id" => $row->employee_id,
"month_year" => $row->month.' '.$row->year
);
}
//print_r($result);
$respnonse['status'] = 'success';
$respnonse['records'] = $result;
}
else
{
$respnonse['status'] = "error";
$respnonse['records'] = "No record found";
}
}
echo json_encode($arr_result);
exit;
}
Hope this will help you :
Use dataType: "json" in your ajax to avoid further parsing of response and return json_encode data with exit from your controller
Your ajax should be like this :
$("form[name='search_record']").validate({
submitHandler: function(form)
{
var employee_id = $('#employee_id').val();
$.ajax({
url: baseUrl + "/Employee_control/search_addSalaryrecord",
method: "POST",
dataType: "json",
data: {employee_id:employee_id},
success: function(response) {
//alert(data.status);
if (response.status == 'error')
{
alert(response.msg);
$('.personel_info').empty();
}
if (response.status == 'success')
{
alert(response.records);
$('.personel_info').empty();
$('.personel_info').show();
var trHTML = '';
$.each(data.records, function (i, o){
$('#name_emp').text(o.name);
$('#mobileno_emp').text(o.mobileno);
$('#employee_email').text(o.employee_email);
});
}
}
});
}
});
Your controller's method search_addSalaryrecord should be like this :
public function search_addSalaryrecord()
{
$employee_id = trim($this->input->post('employee_id'));
if(!empty($employee_id))
{
$arr_result = $this->Employee_model->get_salary_search_emp_id($employee_id);
if (! empty($arr_result))
{
foreach ($arr_result as $row)
{
$result[] = array(
"name" => $row->firstname.' '.$row->lastname,
"mobileno" => $row->mobileno,
"email_id" => $row->email_id,
);
}
$respnonse['status'] = 'success';
$respnonse['records'] = $result;
}
else
{
$respnonse['status'] = "error";
$respnonse['records'] = "No record found";
}
}
echo json_encode($respnonse);
exit;
}

how to append data in after success in laravel

},
submitHandler: function (form) {
var form_data = $(form).serialize();
console.log(form_data);
$.ajax({
type: 'post',
url: SITE_URL+url,
data: form_data,
success: (function (json) {
if (json.type == "success") {
$.each(json, function(i, item) {
$('#div1').append("value"+item.name+) ;
})
var type = 'Created';
if(json.value===1 && typeof json.value != 'undefined'){
type = 'Update';
}
//$("#showDetail form").append();
resetform($(form).attr('id'));
successMessage('Subscription '+type+' Successfuly');
getPosts('show='+$('.custome-show-option select').val()+'&page='+$('#PcurrentPage').text());
} else {
$("#error_div").html('Module already exist');
}
}),
error: (function (response) {
$("#error_div").html('Error in processing');
})
});
this code is proper work but not show append data of form data where success::function(json) {} where j console.log(json) show output only 1
I don't know what is actually your problem but:
in your javascript code you should add:
dataType:'json'
In laravel in controller you should have something like this:
return response()->json(['type' => 'success', 'value' => 1, 'items' => $arrayOfItems]);
This part should be something like this:
$.each(json.items, function(i, item) {
$('#div1').append("value" + item.name) ;
});

Categories