I try to take object from my controller, when I console.log(response) it show the value correctly which is in
[
{
"itemValue":100,
"itemUnit":"2"
}
]
unfortunately I try to use the object like response.itemValue when I console it show undefined. I try var object = response. during the console it show the same value. Please I want to use the response data.
if(itemID){
$.ajax({
type:'POST',
url:'?syspath=ajax&controller=ajax&action=getActItemDose',
data: { 'itemId': itemID, 'itemType': itemType },
success:function(response){
// var obj = jQuery.parseJSON(data);
console.log(response);
var object = response;
var value = object.itemValue;
var unit = object.itemUnit;
console.log(object);
console.log(value);
}
});
}
This is controller where I encode the object into Json
$row = $getProcess->fetch();
$object[] = array(
'itemValue' => $row['each_dose'],
'itemUnit' => $row['unit_dose']
);
echo json_encode($object);
I recommend using the jQuery library. For parsing JSON, simply do
var obj = JSON.parse(data);
// Accessing individual value from JS object
alert(obj.itemValue);
alert(obj.itemUnit);
It worked, by changing this few item
$object[] = array();
into
$object = array();
and JSON.parse(data)
var object = JSON.parse(data);
value = object.itemValue;
unit = object.itemUnit;
Your response is an array. So you need to access it like
response[0].itemValue
or you can loop through the array
response.forEach(element => {
console.log(element.itemValue);
});
Below is the example
const response = JSON.parse(`[
{
"itemValue":100,
"itemUnit":"2"
}
]
`);
response.forEach(element => {
console.log(element.itemValue);
});
Related
i have file.txt
apple <--line 1
banana <--line 2
and this is my script
url = 'file.txt';
homelists = [];
$.get(url, function(data) {
var lines = data.split("\n"); <--i want to split it by line
$.each(lines, function(n ,urlRecord) {
homelists.push(urlRecord); <--add it to my homelists array
});
});
console.log(homelists); <-- returns array
console.log(homelists[0]); <--undefined
my problem is i cant get the inside value of homelists
how can i get homelists[0] or homelists[1]..(javascript or jquery(preferrable))
Javascript/Jquery ajax is an Async call meaning the code $.get and console.log on your example will be executed parallelly (immediate or the same times), so to parse the result of your file.txt, you need to do it inside the function (which will be executed after ajax called is done).
url = 'file.txt';
homelists = [];
$.get(url, function(data) {
var lines = data.split("\n");
$.each(lines, function(n ,urlRecord) {
homelists.push(urlRecord);
});
console.log(homelists);
console.log(homelists[0]);
});
I know this is too simple answer and may sound stupid to others but i have an idea!
why not store in the session the $.get data
url = 'file.txt';
$.get(url, function(data) {
localStorage['homelists'] = data;
});
then assign a variable to that session
homelists = localStorage['homelists'];
then make the session = null
localStorage['homelists'] = null
when you do console.log outside
console.log(homelists); <-returns string which you can manipulate to turn it into array
console.log(localStorage['homelists']); <-returns null
I dont know yet what could be the bad side/effect of this with my project.. any idea?
Since you are using jQuery, It would be better if you use AJAX. !
const ImportData = function(file){
let arrayData = undefined;
$.ajax({
url: file,
type: 'GET',
error: (err) => { throw new Error(err) },
success: ( data ) => {
arrayData = MakeArray( data );
//Do whatever you want here
console.log( arrayData );
}
});
}
const MakeArray = function(plaintext){
const array = [];
plaintext.split('\n').forEach( (line) => {
line = line.trim();
array.push( line );
} );
return array;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
const file = "https://www.w3.org/TR/PNG/iso_8859-1.txt";
document.addEventListener('DOMContentLoaded', function(){
ImportData( file );
});
</script>
I'm trying to pass my JS array to PHP array and all of the solutions that I have found here is useless or I can integrate these solutions to my problem.
Javascript
$('#siparisButon').click(function(){
var splitListe = $('#siparis-block span').text();
splitListe = splitListe.split("- ");
splitListe = JSON.stringify(splitListe);
$.post("menu.php",{'siparisListe[]': splitListe});
// I have a div that shows the result of PHP function and it says undefined index.
$('#fonksiyon').show();
})
PHP
function ekleme(){
if($_POST['siparisListe']){
$liste = $_POST['siparisListe'];
echo $liste;
}
}
instead of this
$('#siparisButon').click(function(){
var splitListe = $('#siparis-block span').text();
splitListe = splitListe.split("- ");
splitListe = JSON.stringify(splitListe);
$.post("menu.php",{'siparisListe[]': splitListe});
// I have a div that shows the result of PHP function and it says undefined index.
$('#fonksiyon').show();
})
modify you code in to this
$('#siparisButon').click(function(){
var splitListe = $('#siparis-block span').text();
splitListe = splitListe.split("- ");
var input_data = new FormData();
$.each(splitListe,function(index,value){
input_data.append("siparisListe["+index+"]",value)
});
$.ajax({
url: "menu.php",
data: input_data,
type: "POST",
success: function(data) {
$("#passwordMatch").html(data);
},
error: function(data) {}
})
// I have a div that shows the result of PHP function and it says undefined index.
$('#fonksiyon').show();
})
Remove the [] from the POST field name and pass it an array (jQuery will JSON encode it for you).
$('#siparisButon').click(function() {
let splitListe = ($('#siparis-block span').text() || '').split('- ');
if (splitListe) {
$.post("menu.php", { siparisListe: splitListe });
$('#fonksiyon').show();
}
});
Then in your PHP to verify:
function ekleme() {
if ($liste = $_POST['siparisListe']) {
var_dump($liste);
}
echo 'No $liste array in POST.';
}
<?
function phpfunction(){
//insert data to database //some codes work inside this.
$return_arr[] = array($arrResult, // include only one value
$response_array['status'] );//success or not success value
return $return_arr;
}
?>
This $return_arr[] value return to the javascript ajax file >>
$.ajax({
url: 'PHPMethodCalls_AL.php',
type: 'post',
data: {... post many values to php function.. },
success: function(data) {
alert(data);
//data is successfully come as this format >> [[["Testing123"],"success"]]
var results = JSON.parse(data);
alert(results);
// this alert got >> Testing123,success
},
//this one is post value to function
$newCIarrayList = array();
$newCIarrayList = phpfunction(..data include );
echo json_encode($newCIarrayList);
What should I do to get each value as "Testing123" and "success" value separately? I tried with split(",") function but it didn't work.
You can seperate in php function before response to ajax like below .Then you can get easy
<?
function phpfunction(){
//insert data to database //some codes work inside this.
$return_arr = array("data" =>$arrResult, // include only one value
"status" =>$response_array['status'] );//success or not success value
return $return_arr;
}
?>
var results = JSON.parse(data);
alert(results.data || results.status);
What you get back in success: function(data) is a stringified json of a nested array: [[["Testing123"],"success"]].
To get your status and payload out of this structure, you can use the following snippet.
var data = '[[["Testing123"],"success"]]';
var parsedData = JSON.parse(data);
console.log(parsedData); // quite nested
var status = parsedData[0][1];
console.log(status);
var payload = parsedData[0][0][0];
console.log(payload);
Or using ES6 destructuring:
var data = '[[["Testing123"],"success"]]';
var parsedData = JSON.parse(data);
[[[payload], status]] = parsedData;
console.log(status);
console.log(payload);
I would however suggest that you revise your php-side code, and make it so that it forms a simpler structure, ideally:
{"status": "success", "payload": "Testing123"}
from controller Json is returned and in function i get an object which contains
{
"readyState":4,
"responseText":"{\"Success\":0,\"Failed\":0}",
"responseJSON":{
"Success":0,
"Failed":0
},
"status":200,
"statusText":"OK"
}
How can I take Success and Failed values?
data.Successand JSON.parse(data) is not working
You dont need to parse that because that IS already an object:
var obj = {"readyState":4,"responseText":"{\"Success\":0,\"Failed\":0}","responseJSON":{"Success":0,"Failed":0},"status":200,"statusText":"OK"};
var failed = obj.responseJSON.Failed;
var success = obj.responseJSON.Success;
var json_data = '{"readyState":4,"responseText":"{\"Success\":0,\"Failed\":0}",
"responseJSON":{"Success":0,"Failed":0},"status":200,"statusText":"OK"}';
var obj = JSON.parse(json_data);
alert(obj.responseJSON.Success); // for success that in responseJSON
alert(obj.responseJSON.Failed);
Thanks :)
I have PHP associative array and I use JQuery AJAX to get the result array but my problem is when that result is pass to jquery and use looping to extract each Sequence,Percent and Date then that extracted data will store to new Jquery Array for data manipulation purposes. Please see my sample code so far.
sample code PHP ARRAY:
$Sequence=array(
array("Seq1","20%"),
array("Seq2","40%"),
array("Seq3","60%"),
array("Seq4","80%"),
array("Seq5","100%")
);
****For loop here****
$ResultArray[$arrayIndex]=array(
'Sequence' => $Sequence[$arrayIndex][0],
'Percent' => $Sequence[$arrayIndex][1],
'Date' => $row['exactDate']
);
echo json_encode($ResultArray); // then pass result array to jquery
JQUERY :
$(document).ready(function(){
var ListOfSequence = []
var ListOfPercentage = [];
var ListOfDates = [];
$("#button").click(function(){
var _WOID = $('#txtWOID').val();
$.ajax({
url:'getStatus.php',
type:'POST',
data:{id:_WOID},
dataType:'json',
success:function(output){
//here is where the problem begin
for (var key in output) {
if (output.hasOwnProperty(key)) {
//here where extracted data will store to designated array
ListOfSequence.push(key);//<---store extracted Sequence
ListOfPercentage.push(key);//<---store percentage
ListOfDates.push(output[key]);//<---store dates
}
}
ListOfPercentage.reverse();
console.log(ListOfPercentage);
console.log(ListOfDates);
console.log(ListofSequence);
}
});
});
});
and here's the console.log:
Thank you in advance
Since you are already using jQuery you could use $.each() :
$(document).ready(function(){
var ListOfSequence = []
var ListOfPercentage = [];
var ListOfDates = [];
$("#button").click(function(){
var _WOID = $('#txtWOID').val();
$.ajax({
url:'getStatus.php',
type:'POST',
data:{id:_WOID},
dataType:'json',
success:function(json){
$.each(json, function(index, object){
ListOfSequence.push(object.Sequence);
ListOfPercentage.push(object.Percent);
ListOfDates.push(object.Date);
});
}
});
});
});
You should set the json response header before sending the content to the browser like so:
header('Content-type: application/json');
die(json_encode($ResultArray);)