Passing an array to parse through AJAX - javascript

I'm trying to pass an array through an AJAX call to the backend, the array gets pushed to the backend, but I'm getting the error "Trying to get property 'id' of non-object"
This is the
var items = [];
$("input:checkbox[name='refundcheck']:checked").each(function(){
let id = $(this).val();
let item = {
"id": id,
"quantity": $('#quantity'+id).val()
};
items.push(item);
});
$.ajax({
type: "GET",
url: '{{url("/")}}/products',
data: {items:items},
dataType: 'JSON',
beforeSend:function (){
//$("#loadingDiv").show();
} ,
success: function( msg ) {
}
});
This is the console log for that array
I've tried both of these possibilities
$productarraylist = $request->items;
foreach($productarraylist as $item){
$product= dbtable::find($item->id);
}
AND
foreach($productarraylist as $i=> $item){
$product= dbtable::find($item->id);
}
This is the var_dump result of the array in the backend.
I tried to JSON.decode the array on the backend, and it says I need to pass a string, not an object.

You are dealing with arrays and not objects, try this:
foreach($productarraylist as $item){
$product= dbtable::find($item['id']);
}

Related

Parsing associative array via AJAX

I have the following associative array and i try to send it to the server via AJAX.
Checking my console, in the network tab, it's posted but nothing is parsed.
Array creation:
var FiltersArray = [];
FiltersArray['category'] = this.category.val();
FiltersArray['Type1'] = this.type1.val();
FiltersArray['Type2'] = this.type2.val();
Assoc array (console.log):
[category: "6", Type1: "998", Type2: "20100100"]
Request:
$.ajax({
type: POST,
url: 'something.php',
data: {
data: FiltersArray
}
}).done(function(data) {
console.log('Server Response: ' + data);
})
Complete code:
$(document).ready(function() {
var filters = {
category: $("#categoryInp"),
type1: $("#type1Inp"),
type2: $("#type2Inp"),
button: $("#FilterBtn"),
returnArray: function() {
var FiltersArray = [];
FiltersArray['category'] = this.category.val();
FiltersArray['Type1'] = this.type1.val();
FiltersArray['Type2'] = this.type2.val();
return FiltersArray;
},
sendRequest: function(type, URL) {
$.ajax({
type: type,
url: URL,
data: JSON.stringify(this.returnArray()),
beforeSend: function() {}
}).done(function(data) {
console.log('Server Response: ' + data);
}).fail(function() {
alert("An error occurred!");
});
}
};
filters.button.on('click', e => {
console.log(filters.returnArray());
filters.sendRequest('POST', 'Modules/Products.order.module.php');
});
});
There is no such thing as an associative array in JavaScript.
There are objects, which hold key:value pairs of data.
There are arrays, which are a type of object that provides special behaviour when the key name is an integer.
jQuery distinguishes between arrays and other kinds of objects when you pass one in data.
If you pass an array it will not do anything with key:value pairs where the key is not an integer.
Use a plain object and not an array for this.
Aside: Variable names beginning with a capital letter are traditionally reserved for storing constructor functions in JavaScript. Don't use that naming convention for other kinds of data.
var filters = {};
filters['category'] = this.category.val();
filters['Type1'] = this.type1.val();
filters['Type2'] = this.type2.val();
It would be easier to just collect all the data as you create the object though:
var filters = {
category: this.category.val(),
Type1: this.type1.val(),
Type2: this.type2.val()
};
Aside
data: {
data: FiltersArray
}
This will create a (seemingly pointlessly) complex data structure that you'll need to access in PHP as $_POST['data']['category'].
You probably want just:
data: filters
Aside
data: JSON.stringify(this.returnArray()),
This will send JSON instead of form encoded data.
If you do that then you'll also need to:
Set the contentType of the request to indicate that you are sending JSON
Explicitly parse the JSON in PHP
So you probably don't want to do that.

How to get value in JavaScript array

I'm trying get a value inside a JavaScript array from the output of an AJAX request.
Ajax request:
$.ajax({
url: "ajax-test.php",
type: "POST",
data: "sku=800270",
dataType: "html"
}).done(function(resposta) {
console.log(resposta);
}
Ajax-Test.php:
$produto[] = array('sku' => $product->getSku(),
'name' => $product->getName());
var_dump($produto[0]);
Returns:
array(6) {
["sku"]=>
string(6) "000188"
["name"]=>
string(80) "Cuba Gastronômica Aço Inoxidável para Buffet GN 1/2×65mm (325x265mm) - 812-2"
}
I need to access the values inside the array, something like:
var sku = resposta["sku"]
In my tests if I try to print resposta["sku"] its giving me "undefined variable".
On php side you need to change var_dump($produto[0]); to echo json_encode($produto[0]). On JS side you need to change your request to dataType: "json", because it is not a html response. Then you can access the fields by the property names.
var sku = resposta.sku;
var name = resposta.name;
Your aproach is not wrong to, to access by a string:
var sku = resposta["sku"];
var name = resposta["name"];
So for conclusion, your php:
$produto[] = array(
'sku' => $product->getSku(),
'name' => $product->getName()
);
echo json_encode($produto[0]);
Your AJAX request:
$.ajax({
url: "ajax-test.php",
type: "POST",
data: "sku=800270",
dataType: "json"
}).done(function(resposta) {
var sku = resposta.sku;
var name = resposta.name;
console.log(sku, name);
}
Set a proper dataType for ajax object as dataType: "json"
Change your Ajax-Test.php file content as shown below(to send a proper json responce):
$produto[] = ['sku' => $product->getSku(), 'name' => $product->getName()];
echo json_encode($produto[0]);

code igniter - how to submit an ajax javascript object to the database with jQuery

I have a javascript array of data that I want to submit to my codeigniter database:
[
{
"name": "title",
"value": "myTitle"
},
{
"name": "content",
"value": "myContent."
}
]
I want to submit this data to codeigniter, and have it update the database. Note that this is not data coming from a form, so I can't just use the typical code igniter form_open() / serialize() method. I am using an ajax post and dynamically building the data:
var submissionData = [];
instanceFields.each(function(index){
var $thisField = $(this);
var thisData = {};
thisData.name =$thisField.attr('data-name');
thisData.value = $thisField.text();
submissionData.push(thisData);
});
var submissionString = {arr: JSON.stringify(submissionData)};
var submissionURL = baseURL + 'instances/edit';
$.ajax({
type: "POST",
url: submissionURL,
data: submissionString,
success: function(data){
console.log("success:",data);},
failure: function(errMsg) {
console.error("error:",errMsg);
}
Normally, for data posted from a form, I could access it like this in code igniter:
$this->input->post('title')
But if I echo that out here, I get an empty string.
I would then insert the data like this:
$data = array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
);
return $this->db->insert('extra_instances', $data);
If I decode the JSON and do a var dump, it looks like this:
success: array(5) {
[0]=>
object(stdClass)#19 (2) {
["name"]=>
string(5) "title"
["value"]=>
string(21) "myTitle"
}
[1]=>
object(stdClass)#20 (2) {
["name"]=>
string(7) "content"
["value"]=>
string(238) "myContent"
}
}
How can I modify this to insert into the database?
If I understand you, you mean that you want to send directly the object to insert into the database so
Javascript: You send the array into the $_POST key 'insertData'
var submissionData = [];
instanceFields.each(function(index){
var $thisField = $(this);
var thisData = {};
thisData.name =$thisField.attr('data-name');
thisData.value = $thisField.text();
submissionData.push(thisData);
});
var submissionURL = baseURL + 'instances/edit';
$.ajax({
type: "POST",
url: submissionURL,
data: {
insertData : submissionData
},
success: function(data){
console.log("success:",data);
},
failure: function(errMsg) {
console.error("error:",errMsg);
}
});
PHP Controller: Receive the post, and you can insert an array directly to do both inserts.
$data = $this->input->post('insertData');
return $this->db->insert('extra_instances', $data);

Loop in a json codeigniter object with jquery

I searched in many questions but doesn't worked for me, I want to loop through a json object returned by a controller, let me show you the code:
MODEL
public function traer_pasajero($id){
$this->db->select('*');
$this->db->from('pasajeros');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->result();
}
CONTROLLER
public function traer_pasajero(){
$pasajero = $this->pasajeros_model->traer_pasajero($this->input->post('id'));
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($pasajero));
return $pasajero;
}
JS
function modificarPasajero (id) {
$.ajax({
type: "POST",
url: "http://localhost/xxx/xxx/traer_pasajero",
data: {id: id},
dataType: "text",
cache:false,
success:
function(data){
$.each( data, function( key, value ) {
alert(value);
});
}
});
}
And I receive this error in firebug:
TypeError: invalid 'in' operand a
This is the json object that I see in firebug:
[{"id":"1","primer_nombre":"xxxx","segundo_nombre":"","primer_apellido":"xxxx","segundo_apellido":"","ci":"xxx","nacionalidad":"Uruguayo","fecha_nacimiento":"5/7/1910","vencimiento":"5/5/1910","asiento":"12","habitacion":"Sgl","levante":"","telefono":"","observaciones":"","id_envio":"2"}]
dataType should be "json" instead of "text", and try to console.log(data) before each loop.
try removing this statement
return $pasajero;
as it is overwriting your json..
you can simply return
return json_encode($pasajero);
and then try
also cahnge
datatype : "json"
now to iterate you can use eval(string) or JSON.parse(string). but note that eval is dangerous
var obj = eval("("+data+")");
or
var obj = parseJSON(data);
$.each( obj, function( key, value ) {
alert(value);
});

Send array with ajax request to php

I created array like this ["9", "ques_5", "19", "ques_4"]. Now I want to send it from JS to PHP but I'm not getting proper results. My JS code is:
$(".button").click(function(e) {
e.preventDefault();
$.ajax({
type : 'post',
cache : false,
url : 'test/result.php',
data : {result : stuff},
success: function(resp) {
alert(resp);
}
});
});
In the above code stuff is an array which contains records. How can I send this array with above code and then in PHP I want to process this array like ques_5 is the key and 9 become the value for that key.
You can pass the data to the PHP script as a JSON object. Assume your JSON object is like:
var stuff ={'key1':'value1','key2':'value2'};
You can pass this object to the php code in two ways:
1. Pass the object as a string:
AJAX call:
$.ajax({
type : 'POST',
url : 'result.php',
data : {result:JSON.stringify(stuff)},
success : function(response) {
alert(response);
}
});
You can handle the data passed to the result.php as :
$data = $_POST["result"];
$data = json_decode("$data", true);
//just echo an item in the array
echo "key1 : ".$data["key1"];
2. Pass the object directly:
AJAX call:
$.ajax({
type : 'POST',
url : 'result.php',
data : stuff,
success : function(response) {
alert(response);
}
});
Handle the data directly in result.php from $_POST array as :
//just echo an item in the array
echo "key1 : ".$_POST["key1"];
Here I suggest the second method. But you should try both :-)
If you want to send key value pairs, which is what I am seeing, it would be better to use a PHP JSON library (like this one... http://php.net/manual/en/book.json.php)
Then you can send actual key value pairs, using JSON format like...
{"ques_5" : "19", "ques_4": "19"}
Try this
var array = ["9", "ques_5", "19", "ques_4"];
console.log(array.join(","));
above code will output string with comma separated like 9,ques_5,19,ques_4then paste it to ajax call.
And then in php explode that string.
Other possible solutions.
First
var obj = { 'item1': 'value1', 'item2': 'value2' };
$.ajax(
{
type: 'post',
cache: false ,
url: 'test/result.php',
data: { result : JSON.stringify(obj) },
success: function(resp)
{
alert(resp);
}
});
Second
var a = $.JSON.encode(obj);
$.ajax(
{
type: 'post',
cache: false ,
url: 'test/result.php',
data: { result : a },
success: function(resp)
{
alert(resp);
}
});
In PHP File
<?php
$json = $_POST["data"]
var_dump(json_decode($json));
?>
You can send the array in json format to the php and then use json_decode function to get back the array like
In ajax call you have to send json for that you need to first make array of the values so that you get it in right form
so that you json look like {"ques_5":"9","ques_4":19}
and use in ajax call
data: JSON.stringify(`your created json`),
contentType: "application/json; charset=utf-8",
dataType: "json",
IN PHP it look like
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
?>
I would like to share a complete example that works for me in order to avoid making each JavaScript function for each PHP function
// on the HTML side a simple JavaScript call from a link
<a href="javascript:CargaZona('democonllamada', 'tituloprin', {'key1':'value1','key2':'value2'})" >test</a>
<div id='tituloprin' >php function response here!</div>
// on JavaScript side
function CargaZona(fc, div, params) {
var destino = "#" + div;
var request = $.ajax({
url : "inc/phpfunc.php",
type : "POST",
data : {
fc : fc,
params : JSON.stringify(params)
},
dataType : "html"
});
request.done(function (msg) {
$(destino).html(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
// on phpfunc.php page
<?php
$params = "{'key1':'value1','key2':'value2'}";
$fc = 'def';
if (isset($_POST['fc'])) { $fc = $_POST['fc']; }
if (isset($_POST['params'])) { $params = $_POST['params']; }
switch ($fc) {
default:
call_user_func($fc,$params);
}
function democonllamada($params) {
$params = json_decode("$params", true);
echo "ok llegaron".$params['key1'];
}
?>

Categories