i'm using ajax to get data from model by controller every thing is running nice i think and when i check with console.log(response) i get
Object {buyTemps: Object}
and in side the object i found All data inside the array up to now every thing is good
ajax
$(".buy-tr").click(function(e){
var
data = {},
$row = $(this).closest("tr"), // Finds the closest row <tr>
$tds = $row.find("td:nth-child(1)"); // Finds the 2nd <td> element
$.each($tds, function() { // Visits every single <td> element
data={buyId:$(this).text()};
});
// $(this).find('input:radio').prop('checked', true);
$(".buy-tr").click(function(e){
var
data = {},
$row = $(this).closest("tr"), // Finds the closest row <tr>
$tds = $row.find("td:nth-child(1)"); // Finds the 2nd <td> element
$.each($tds, function() { // Visits every single <td> element
data={buyId:$(this).text()};
});
$.ajax({
url : "/buy/selectTable",
type : 'GET',
dataType : 'json',
data : data,
success : function(response) {
console.log(response);
$('#buyItem-table tbody').empty();
$.each(response,function(index, v){
$('#buyItem-table tbody').append(
"<tr><td>" + v.buyItemTempId
+ "</td><td>" + v.itemName
+ "</td><td>" + v.itemExpire
+ "</td><td>" + v.buyPrice
+ "</td><td>" + v.buyBox
+ "</td><td>" + v.itemPacking
+ "</td><td>" + v.buyQty
+ "</td></tr>" );
});
},
error : function(response) {
swal("error");
}
at my controller
public function selectItemTable()
{
$buyId = Input::get('buyId');
$buyTemps = DB::table('vbuytemp')->where('buyId',$buyId)->paginate(10);
return Response::json(compact('buyTemps'));
}
the consol.log(v)
Object {total: 1, per_page: 10, current_page: 1, last_page: 1, next_page_url: null…}current_page: 1data: Array[1]0: Objectbarcode: "08815408"buyBox: 30buyId: 2buyItemTempId: 2buyPrice: "2.500"buyQty: 90itemExpire: "2018-01-04"itemId: 2itemName: "Panadol Extra tab"itemPacking: 2minQty: 1roofId: 1sellingForm: 1__proto__: Objectlength: 1__proto__: Array[0]from: 1last_page: 1next_page_url: nullper_page: 10prev_page_url: nullto: 1total: 1__proto__: Object__defineGetter__: __defineGetter__()__defineSetter__: __defineSetter__()__lookupGetter__: __lookupGetter__()__lookupSetter__: __lookupSetter__()constructor: Object()hasOwnProperty: hasOwnProperty()isPrototypeOf: isPrototypeOf()propertyIsEnumerable: propertyIsEnumerable()toLocaleString: toLocaleString()toString: toString()valueOf: valueOf()get __proto__: get __proto__()set __proto__: set __proto__()
the result all table cell fill with undefined
Your issue is that you are looping through response data at the wrong point. When you call $.each you are actually looping through all of the pagination metadata (total, per_page, etc.). The actual data you want is contained inside the data array. So just loop through that array instead and it should work.
$.each(response.data,function(index, v){
//now v.buyItemTempId and other properties exist
}
Related
I am trying to fetch values from mysql database through AJAX Request in json format. So basically AJAX gets php script. For some reason it does not get proper values, instead it shows "undefined".pic from database
pic of result
ot5a.html
pic from html document
ot5a.js
$(document).ready(function() {
$.ajax({
url: "ot5a.php",
type: "GET",
success: function(result) {
tulostaluettelo(result);
},
error: function(xhr) {
console.log(xhr.status);
}
});
function tulostaluettelo(result) {
var luettelo = "<table><thead><tr><th>id</th><th>Joukkue</th><th>Voitot</th><th>Tasapelit</th><th>Tappiot</th></tr></thead><tbody>";
var i;
for(i = 0; i < result.length; i++) {
luettelo += "<tr><td>" + result[i].id + "</td><td>" + result[i].joukkue + "</td><td>" + result[i].voitot + "</td><td>" + result[i].tasapelit + "</td><td>" + result[i].tappiot + "</td></tr>";
}
luettelo += "</tbody></table>";
$("#tulostusalue").html(luettelo);
} });
ot5a.php
php code
config.php
enter image description here
Add breakpoint/debugger in client,php and config file and check what is the result it is returning. That way you will come to know where exactly is the problem.
Also I see that "luettelo" is a variable type, but you are iterating it like an array object. Change that as well and see if that works.
I am trying to unpack my json object send via http post request in a php controller:
$products = $_POST['products'] ?? '';
foreach($products as $purchase){
$productId =$purchase['productid'];
$qty = $purchase['quantity'];
$params = array(
'form_key' => $this->formKey->getFormKey(),
'product' => $productId,
'qty' => $qty
);
//Load the product based on productID
$_product = $this->product->load($productId);
$this->cart->addProduct($_product, $params);
$this->cart->save();
}
This is the format of my json object being sent, stored in a variable called list.
0: {productid: "2910", quantity: "2"}
1: {productid: "2911", quantity: "1"}
2: {productid: "2913", quantity: "4"}
3: {productid: "2914", quantity: "3"}
This is my post request (content type is also set to application/json):
$.post("http://dev.website.co.uk/batchorder/index/addtocart",
{
products:list,
},
function(data, status){
console.log("Data: " + data);
console.log("Status: " + status);
});
This has always worked for me before so i cannot see where i am going wrong with it.
The error i am getting is Warning: Invalid argument supplied for foreach(). but i am assuming it has something to do with my json object.
EDIT:
$("#AddToCartButton").click(function(){
var list = [];
$("#tabCollection :input").each(function(){
var input = $(this);
if($(this)[0].value > 0){
var myArray = {'productid': $(this)[0].id, 'quantity': $(this)[0].value};
list.push(myArray);
}
});
var JSONStringlist = JSON.stringify(list);
var JSONlist = JSON.parse(JSONStringlist);
console.log(JSONlist);
$.ajaxSetup({
headers:{
'Content-Type': "application/json",
}
});
$.post("http://dev.website.co.uk/batchorder/index/addtocart",
{
"products":JSONlist,
},
function(data, status){
console.log("Data: " + data);
console.log("Status: " + status);
});
});
EDIT 2:
example of JSON String:
[{"productid":"2182","quantity":"1"},{"productid":"2183","quantity":"1"},{"productid":"2184","quantity":"1"},{"productid":"2185","quantity":"1"}]
$products = $_POST['products'] ?? '';
foreach($products as $purchase){
Your $products is either "something that is iterable" or a empty string.
In case it's a array, it's iterable, and the foreach will succesfully execute. But in case it's a empty string, it's going to complain about "Warning: Invalid argument supplied for foreach()", cause a string is not really iterable.
So what you need to do is make sure, that $products is always an array, either an empty or filled with json objects.
If you change:
$products = $_POST['products'] ?? '';
to:
$products = json_decode($_POST['products']) ?? array();
The foreach won't complain, and if $_POST['products'] is empty nothing will be saved in the cart.
In your javascript file change:
$.post("http://dev.website.co.uk/batchorder/index/addtocart",
{
"products":JSONlist,
},
function(data, status){
console.log("Data: " + data);
console.log("Status: " + status);
});
});
to:
$.post("http://dev.website.co.uk/batchorder/index/addtocart",
{
"products":JSONStringlist,
},
function(data, status){
console.log("Data: " + data);
console.log("Status: " + status);
});
});
You are parsing an JavaScript object to JSON, and then you're reparsing it back to an JavaScript object.
PHP does not really understand JavaScript objects, but understands JSON objects.
This may be the duplicate question but I would like to mention that other answers have not solved my problem.
As the question says, I want to populate the dropdown using ajax/jquery. I am able to send and recieve data in the JSON format successfully but it does not append with the dropdown. Following is my code:
View
<select name="guard_id" id="guard_id" style="width:100%;">
<option>select guard</option>
<optgroup label="Previously assigned guard" id="trained_guards">
</optgroup>
</select>
Jquery/Ajax call
function checkTrainedGuards(sid) {
$.ajax({
dataType: 'JSON',
type: 'POST',
url: '<?php print site_url('roster/check_trained_guards'); ?>',
data: { sid: sid},
beforeSend:function() {
// this is where we append a loading image
$('#sid').addClass('loader-roster');
},
success:function(data) {
var appenddata;
$.each(data, function (key, value) {
appenddata += "<option value = '" + value.gid + " '>" + value.gname + " </option>";
});
$('#trained_guards').html(appenddata);
},
error:function(){
// failed request; give feedback to user
}
});
}
Controller
public function check_trained_guards(){
$this->load->model("guard");
$sid=$this->input->post("sid");
$trainedGuards=$this->guard->getGuardAlreadyWorkedOnSite($sid);
foreach ($trainedGuards as $guard) {
print json_encode(array(
'gid' => $guard->gid,
'gname' => $guard->guard_name
));
}
}
}
When I test it using firebug, I an see the data is coming correct and it is in JSON format as shown below:
[{"gid":"293","gname":"Abc"},{"gid":"96","gname":"guard2"},{"gid":"101","gname":"guard3"},{"gid":"91","gname":"guard4"}]
However, I am just wondering why it is not appending the result into dropdown box?
I, Also tested this by alert(value.gid) in the jquery each loop it says undefined.
Any help will be highly appreciated.
You JSON seems to be in wrong format . Your php part should look like follows :
$arr = array();
foreach ($trainedGuards as $guard) {
$arr[] = $guard;
}
print json_encode($arr);
Now this code will return a valid JSON as Follows. JOSN will the array of objects shown below :
[{"gid":"2","gname":"Gurd1"},{"gid":"3","gname":"Guard2"}]
In your ajax response write following code
var data = [{"gid":"2","guard_name":"Gurd1"},{"gid":"3","guard_name":"Guard2"}];
//This is the response format You can also use JSON.parse if its in the string format
var appenddata = "";
$.each(data, function (key, value) {
appenddata += "<option value = '" + value.gid + " '>" + value.gname + " </option>";
});
$('#trained_guards').html(appenddata);
I tell you what, getting AJAX to work is one pain in the wazoo! It took me ages to get a simple string to pass and then I got a json array working and felt good, now I've tried to make a little adjustment and broke the whole thing again. Why is following giving an ajax error and how can I get under the hood to see what's going on?
jQuery:
$('#upload_form option[value="addnew"]').click(function(){
// Show modal window
$('#add-new').modal('show');
// Get the class
var Classofentry = $(this).attr("class");
//console.log(Classofentry);
$('#add-new-submit').on('click', function(){
// Get new option from text field
var value = $('#add-new-text').val();
console.log(value);
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>main/change_options",
data: {new_option: value, new_option_class: Classofentry},
//dataType: "html",
dataType: "json",
error: errorHandler,
success: success
});
function success(data)
{
if (data[1]) // Only add new entry if unique
{
// Add new entry
//$('#animal_species').append("<option value='" + data + "'selected=\"selected\">" + data + "</option>");
$('#'+Classofentry).append("<option value='" + data[0] + "'selected=\"selected\">" + data[0] + "</option>");
//alert(data[0]);
}
else
{
// Select the nonunique value by emptying it and appending
$('#'+Classofentry).empty("<option value=''selected=\"selected\">" + data[0] + "</option>").append("<option value='" + data[0] + "'selected=\"selected\">" + data[0] + "</option>");
//alert(data[1]);
}
alert(data[1]);
//alert('Success!');
}
function errorHandler()
{
//alert('Error with AJAX!');
alert(data[0]);
}
$('#add-new-submit').unbind('click'); // This fixes the problem for multiple entries
$('#add-new').modal('toggle');
});
});
php:
public function change_options()
{
# Receives and sends back user-entered new option and adds it to database
# Get strings from ajax in view
$value = $_POST['new_option'];
$value_class = $_POST['new_option_class'];
#Make array to send to model
$value_array = array('Options' => $value);
$unique = true;
echo json_encode(array($value, $unique));
}
In the console I get: ReferenceError: data is not defined. I've spent the last couple days working on logic to determine $unique and now the ajax won't work, even when I strip it back to it's bare bones. What going on here?
Th code I posted should've worked. I found the issue and it wasn;t with ajax, it was with me passing the wrong thing to the model. Here's the working code, with the logic to determine $unique:
(BTW, this solves the problem posed in Form Validation in Codeigniter: using set_rules to check text input from a modal window without using Form Validation):
public function change_options()
{
# Receives and sends back user-entered new option and adds it to database
# Get strings from ajax in view
$value = $_POST['new_option'];
$value_class = $_POST['new_option_class'];
//print_r($value_class); die;
#Make array to send to model
$value_array = array('Options' => $value);
$unique = true;
$this->load->model('data_model');
$elements = $this->data_model->get_options($value_class);
foreach ($elements as $element)
{
if (preg_match("/$element/", $value, $matches))
{
$unique = false;
break;
}
}
# Add new option to dropdown in database
if ($unique) {$this->data_model->add_option($value_class, $value_array);}
//echo $value;
echo json_encode(array($value, $unique));
}
i return this json from my php page but jquery cannot decode it,result is always null.
{
"City": [
{
"CityID": "1",
"CityName": "istanbul"
},
{
"CityID": "2",
"CityName": "Ankara"
}
]
}
Jquery Code:
$.getJSON("handlers/cityhandler.php", function(json){
var result = jQuery.parseJSON(json);
console.log(result[0].City.CityID);
Jquery alternate code:
$.getJSON("handlers/cityhandler.php", function(json){
$.each(json, function(i,City){
$("#selectcity").append('<option value="' + City.CityID + '">' + City.CityName + '</option>');
});
console.log(json.City[0].CityID);
The data is already parsed when you receive it, you don't need to call $.parseJSON. Furthermore, the reason why you are getting a null pointer exception is because result[0] doesn't exist: result is an associative array, not a regular array.
$.getJSON("handlers/cityhandler.php", function(json){
console.log(json.City[0].CityID);
});
Your second attempt isn't right either; if you're trying to loop over the cities you must loop over the inner array:
$.getJSON("handlers/cityhandler.php", function(json){
$.each(json.City, function(i, val){
$("#selectcity").append('<option value="' + val.CityID + '">'
+ val.CityName + '</option>');
});
});
Your JSON output is valid JSON, so the issue is not coming from there. Are you sure that this is exactly what the jQuery handler receives?
Side note, result[0] doesn't exist! Your top element is an object and not an array!