Returned JSON not displaying a value - php

I have a jQuery script that returns JSON data and for some reason a specific value is not displayed and I don't know why since all the other properties are displayed fine. The value that is not working correctly is data.code.
$(document).ready(function() {
$(".cos").click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
var produs_href = $(this).closest('.productinfo').find('a:first').attr('href');
var id_prod = $(this).data('id');
var color = $(this).closest(".col-sm-4").find(".selected").data("color");
if (typeof color === 'undefined') {
alert ("selecteaza o culoare!");
} else {
$.getJSON(href + '&color=' + color).done(function(data) {
$.each(data, function(key, val) {
$("#cnt").empty();
$("#cnt").append('' + val.cnt + '');
$.ajax({
url: "/engine/shop/produse_cos_popup.php?id=" + id_prod + "&color=" + color,
type: "GET",
datatype: 'json',
success: function(data) {
$('#qty').html('Cantitate: ' + data.qty + '');
$('.nr_prod').html('' + data.qty_total + 'produse în cosul dvs');
$('#nume').html('' + data.nume + '');
$('#pret').html('' + data.pret_total + '');
if (data.poza!='') {
$('.produs_img').html(data.poza);
} else {
$('.produs_img').html('<img class="img-responsive" src="/images/no_photo.jpg">');
}
$('#cod').html('<b>Cod Produs:</b ' + data.code + '');
$('#culoare').html('<b>Culoare:</b> ' + data.culoare + '');
$('#greutate').html('<b>Greutate:</b> ' + data.greutate +'');
$('#viteza').html('<b>Viteza maximă:</b> ' + data.viteza + '');
$('#autonomie').html('<b>Autonomie:</b> ' + data.autonomie + '');
$('#putere').html('<b>Putere motor:</b> ' + data.putere + '');
$('#detalii_prod').modal('show');
}
});
});
});
}
});
});
Here is the JSON returned. As you can see the variable code is there. It displays `Cod Produs: but without the value.
{
"qty": "4",
"poza": "<img class=\"img-responsive\" src=\"images\/trotineta_verde.png\">",
"id": "1",
"nume": "Eco",
"code": "etw1",
"greutate": "10.7 kg",
"viteza": "27 km\/h",
"autonomie": "30 km",
"putere": "350 Watt",
"culoare": "verde",
"pret_total": "37560",
"qty_total": "18"
}

You are not closing the </b
Change
$('#cod').html('<b>Cod Produs:</b ' + data.code + '');
For
$('#cod').html('<b>Cod Produs:</b> ' + data.code + '');

Related

How to to create as much dynamicEl, as we received from PHP

On main page have Gallery, on click a image need open lightGallery slideshow with images that found on ftp directory, with gallery name that clicked on main page.
PHP for finding images and count it:
<?php
header("Content-Type: application/json");
$dirname = $_POST["galleryName"];
$imgGallery = glob("../gallery/" . $dirname . "/".$dirname."_*.*");
$thumbGallery = glob("../gallery/" . $dirname . "/thumb_*.*");
$countImages = count($imgGallery);
echo json_encode(array("imgNormal" => $imgGallery, "imgThumb" => $thumbGallery, "imgCount" => $countImages));
?>
JS:
$('.info').click(function() {
var galleryName = $(this).closest('.imgGallery').find('img.img-thumbnail').attr('name');
$.ajax({
url: "gallery/imgFinder.php",
dataType: "json",
type: "post",
data: {
galleryName: galleryName
},
success: function(xhr) {
if (xhr.imgCount != 0) {
console.log(xhr.imgNormal);
console.log(xhr.imgThumb);
console.log(xhr.imgCount);
for (var i = 1; i <= xhr.imgCount; i++) {
$(this).lightGallery({
dynamic: true,
dynamicEl: [{ //We need to create as much as we received w "xhr.imgCount"
"src": "/gallery/" + galleryName + "/" + galleryName + "_" + i + ".jpg",
"thumb": "/gallery/" + galleryName + "/" + galleryName + "_" + i + ".jpg"
}]
})
return;
}
} else {
console.log('Gallery \'' + galleryName + '\' has no images');
return;
}
},
error: function(xhr) {
console.error("Some error found");
}
});
});
We need to create as much dynamicEl with image/thumb variables, as we received xhr.imgCount
To get something like this:
dynamicEl: [{
"src": '...',
'thumb': '...'
}, {
'src': '...',
'thumb': '...'
}, {
'src': '...',
'thumb': '...'
}, {
'src': '...',
'thumb': '...'
}]
inside your JS code you needs to be updated something like below:
if (xhr.imgCount != 0) {
console.log(xhr.imgNormal);
console.log(xhr.imgThumb);
console.log(xhr.imgCount);
var dynamicEls = [];
for (var i = 0; i <= xhr.imgCount; i++) {
dynamicEls[i] = {
"src": "/gallery/" + galleryName + "/" + galleryName + "_" + i + ".jpg",
"thumb": "/gallery/" + galleryName + "/" + galleryName + "_" + i + ".jpg"
};
}
dynamicEls.pop(); //For remove unrealized last url/data
$(this).lightGallery({
dynamic: true,
dynamicEl: dynamicEls
});
}
So, I am using and temp variable dynamicEls and after the loop filling it in correct position.

jQuery ajax request giving error : undefined

I'm trying to recieve data in JSON from online php code, I'm getting undefined error
The website i'm retrieving from is https://www.orba.com.ng/getemployees.php
I'm using jQuery
localStorage['serviceURL'] = "https://www.orba.com.ng/";
var serviceURL = localStorage['serviceURL'];
var scroll = new iScroll('wrapper', { vScrollbar: false, hScrollbar:false, hScroll: false });
var employees;
$(window).load(function() {
setTimeout(getEmployeeList, 100);
});
function getEmployeeList() {
$('#busy').show();
$.getJSON(serviceURL + 'getemployees.php', function(data) {
$('#busy').hide();
$('#employeeList li').remove();
employees = JSON.parse(data.items);
$.each(employees, function(index, employee) {
$('#employeeList').append('<li><a href="employeedetails.html?id=' + employee.id + '">' +
'<img src="img/' + employee.picture + '" class="list-icon"/>' +
'<p class="line1">' + employee.firstName + ' ' + employee.lastName + '</p>' +
'<p class="line2">' + employee.title + '</p>' +
'<span class="bubble">' + employee.reportCount + '</span></a></li>');
});
setTimeout(function(){
scroll.refresh();
});
});
}
$(document).ajaxError(function(event, request, settings, thrownError) {
$('#busy').hide();
alert("Failed: " + thrownError.error);
});
I'm getting error code undefined
It was a CORS issue, Quite easy to fix. Search on google

How to get ajax value and store in PHP variable?

custom.js file:
$(document).ready(function() {
$("#company_name").keyup(function() {
$.ajax({
type: "POST",
url: "http://localhost/capms_v2/ca_autocomplete/getcompanyName",
data: {
keyword: $("#company_name").val()
},
dataType: "json",
success: function(data) {
//alert(data);
if (data.length > 0) {
$('#DropdownCompany').empty();
$('#company_name').attr("data-toggle", "dropdown");
$('#DropdownCompany').dropdown('toggle');
} else if (data.length == 0) {
$('#company_name').attr("data-toggle", "");
}
$.each(data, function(key, value) {
if (data.length >= 0)
$('#DropdownCompany').append('<li role="displayCountries" ><a role="menuitem DropdownCompany" id=' + value['company_id'] + ' Address1=' + value['company_address1'] + ' Address2=' + value['company_address2'] + ' city=' + value['company_city'] + ' state=' + value['company_state'] + ' pincode=' + value['company_zip'] + ' class="dropdownlivalue">' +
value['company_name'] + '</a></li>');
});
}
});
});
$('ul.txtcountry').on('click', 'li a', function() {
$('#company_name').val($(this).text());
$('#company_id').val($(this).attr("id"));
// $('#company_address1').val($(this).text());
$('#tableCityID').html($(this).attr("id"));
$('#tableCityName').html($(this).text());
$('#Address1').html($(this).attr("Address1"));
$('#Address2').html($(this).attr("Address2"));
$('#city').html($(this).attr("city"));
$('#state').html($(this).attr("state"));
$('#pincode').html($(this).attr("pincode"));
});
});
I was getting id in span id="tableCityID" but if I store the value and pass the value to mysql it was not fetching the value
$com = '<span id="tableCityID">';
and if I echo the select query
echo $sql="select * from ca_job WHERE job_status!='Closed' AND job_customer_name = '".$com."'";
I get the result with not completed single codes
select * from ca_job WHERE job_status!='Closed' AND job_customer_name = '15
If anybody faces this problem, please help me. Thanks in advance.
just use the </span>
like this
$com = '<span id="tableCityID"></span>';

ajax function doesn't work when referred to from instagram

My function seems to return nothing for the destination element when the link is referred to from Instagram. It works fine if I directly visit the page.
function getTeamsByLeague(league) {
//console.log("League Set: " + league);
$.ajax({
url: "<?php echo SITE_BASE_URL; ?>json.php",
data: {method: "getteamsbyregion", league: league},
success: function (data) {
if (data && data.length > 0) {
$("#destination").empty();
var selected = "";
$.each(data, function (index, item) {
if (item.team == teamSelected) {
selected = " selected";
$("#latitude").val(item.lat);
$("#longitude").val(item.lng);
} else {
selected = "";
}
$("#destination").append('<option ' + selected + ' value="' + item.lat + ',' + item.lng + '">' + item.team + '</option>');
if (index == 0) {
$("#latitude").val(item.lat);
$("#longitude").val(item.lng);
}
});
}
},
type: "GET",
dataType: "json"
});
}

Form validation not working when using Ajax

I'm currently using ajax to auto-save a form. Codeigniter's form validation function doesn't seems to be working when using ajax. Anyone knows whats the problem here?
PHP:
function autoSavePublicationDetails()
{
$this->form_validation->set_rules('first_author', 'First author', 'required');
if ($this->form_validation->run() == FALSE)
{
$data['message'] = validation_errors();
}
else
{
$newRow = json_decode($_POST['json']);
$claim_id = $_POST['claim_id'];
//$this->publicationClaim_model->updateClaim($newRow,$claim_id);
//$data['claim_id'] = $claim_id;
$data['message'] = "Success";
}
print json_encode($data);
}
Jquery:
setInterval(function(){
var date = new Date();
var dateFormat = date.getFullYear() + "-" + ("0" + date.getMonth()).slice(-2) + "-" + ("0" + date.getDate()).slice(-2) + " " + ("0" + date.getHours()).slice(-2) + ":" + ("0" + date.getMinutes()).slice(-2) + ":" + ("0" + date.getSeconds()).slice(-2);
var claimObj = {
first_author : $('#first_author').val(),
authors : $('#authors').val(),
publication_title : $('#publication_title').val(),
source : $('#source').val(),
publication_submitted : $('#publication_submitted :selected').val(),
research_bank_number : $('#research_bank_number').val(),
research_code_1 : $('#research_code_1 :selected').val(),
research_code_2 : $('#research_code_2 :selected').val(),
research_code_3 : $('#research_code_3 :selected').val(),
issn : $('#issn').val(),
type_of_publication : $('#type_of_publication :selected').val(),
claim_type : $('input[name="claim_type"]').val(),
claim_author : $('input[name="claim_author"]').val(),
claim_date : dateFormat,
user_id : $('input[name="user_id"]').val()
};
var json_data = JSON.stringify(claimObj);
var className;
$.post("autoSavePublicationDetails",
{
'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>',
'json' : json_data,
'claim_id' : $('#claim_id').val()
},
function(data,status){
console.log("Status: " + status);
var jsonReturn = $.parseJSON(data);
alert(jsonReturn.message);
if (jsonReturn.message == "Success")
{
className = 'label label-success';
$('#message').addClass(className);
$('#message').text('Data saved.');
}
else
{
className = 'label label-danger';
$('#message').addClass(className);
$('#message').text('Form not saved.');
}
$('#message').fadeIn();
setTimeout(function() {
$('#message').fadeOut();
$('message').removeClass()
}, 1000);
});
}, 10000);
I tried alerting the validation errors. It says that my first_author field is empty even when I already entered the some text inside.
Json that is passed to controller:
instead of $.post() try to use $.ajax()

Categories