How to get value in JavaScript array - javascript

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]);

Related

Passing an array to parse through AJAX

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']);
}

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);

Appending JSON array to select

I am trying to append this JSON array to a select box
{
"10":"Branche",
"2":"Marketing & Comunicatie",
"8":"Test Branche 1",
"9":"Test Branche 2",
"6":"Test Branche 3",
"7":"Test Branche 4",
"1":"Webdevelopment & design"
}
But it doesn't work I encoded it from a PHP array. This is how I am trying to loop through it.
this.addOption = function(name, table, value){
$.ajax({
type: "POST",
data: {action:'add', table:table, value:value},
url: "index.php",
})
.done(function( obj ) {
$("#"+name+"-select").empty()
console.log(name);
$.each(obj, function( key, value ) {
$("#"+name+"-select").append('<option value='+key+'>'+value+'</option>');
});
});
}
Where obj is the JSON array.
It is giving me this error:
It appears that your PHP is outputting the JSON with a content type of text/html and because you haven't told jQuery you're expecting JSON, it won't parse the response, and in the end you're trying to call $.each on a string.
Add a dataType to tell jQuery to explicitly parse the response as JSON:
$.ajax({
type: "POST",
data: {action:'add', table:table, value:value},
url: "index.php",
dataType: 'json'
})
Alternatively, set the correct content type in your PHP:
header('Content-type: application/json');
echo json_encode(...);
Yes you can use following way:
for(k in obj) {
$("#branch-select").append('<option value='+k+'>'+obj[k]+'</option>');
}

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'];
}
?>

How to post an array of JSON objects to a Struts2 action using jQuery?

Using Struts2.
In my Action I have a List<Person> persons;
In javascript, I have this function:
function mytestfunction() {
var url = "MyAction_mytestfunction.action";
var params = {};
var arr = [];
var p1 = { "firstname" : "John", "lastname" : "Doe"};
var p2 = { "firstname" : "Rob", "lastname" : "Smith"};
arr.push(p1); arr.push(p2);
params["persons"] = arr;
$.post(url, params, function(data) {
console.log("done");
});
}
Problem is, the post() never reaches the action. There are no errors in the logs, nothing.
This all changes if instead of posting objects I post primitives. So when I have a List<Integer> nums in the Action and params["nums"] = [1,2,3]; in javascript, everything is posted fine.
So, is there a way to post JSON objects to a Struts2 action via javascript/jquery?
I should mention that I'm using the struts-jquery plugin, not dojo.
I don't know anything about struts, but this is how I POST objects with json:
$.ajax({
type: "POST",
data: JSON.stringify(SOME_JAVASCRIPT_OBJECT),
contentType: "application/json; charset=utf-8"
// etc: etc
});
you can try as following example:
$.ajax({
type: "Post",
url: "action_name", //you can pass through querystring like actionname?paramname=value
data : {
//here comes your param or array
},
dataType:"json",
contentType: "application/json; charset=utf-8",
});
If you want to pass through querystring type must be GET

Categories