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);)
Related
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);
});
im trying to pass javascript arrays in a jquery .post, but it's not showing on the page. What am i doing wrong? i see that my arrays are filled, but the data is not showing on the page post. The console log shows the p element also i dont know why it's doing that.
jquery code:
$("#submitboeking").click(function(event) {
event.preventDefault();
//Cursisten
var voornamen = [];
var achternamen = [];
var geslachten = [];
var geboortedata = [];
$("[id^='txtCursistVoornaam']").each(function() {
voornamen.push($(this).val());
});
$("[id^='txtCursistAchternaam']").each(function() {
achternamen.push($(this).val());
});
$("[id^='radCursistGeslacht']:checked").each(function() {
geslachten.push($(this).val());
});
$("[id^='txtCursistGeboortedatum']").each(function() {
geboortedata.push($(this).val());
});
// console.log(voornamen);
// console.log(achternamen);
// console.log(geslachten);
// console.log(geboortedata);
$.post('/wp-content/themes/tweb/processboeking.php',
{
voornamen: voornamen,
geslachten: geslachten,
voornamen: voornamen,
achternamen: achternamen,
geboortedata: geboortedata,
})
.done(function(data)
{
console.log(data)
$('#overzichtboeking').html(data);
}).fail(function(data) {
alert(response.responseText);
});
var li_count = $('.nav-tabs li').length;
var current_active = $('.nav-tabs li.active').index();
if (current_active < li_count) {
$('.nav-tabs li.active').next('li').find('a').attr('data-toggle', 'tab').tab('show');
var txt = $(".oplselect option:selected").text();
var val = $(".oplselect option:selected").val();
$('.showoplnaam').html('Uw selectie: ' + txt);
}
});
console.log data:
Array
(
[voornamen] => Array
(
[0] => G.F.
)
[geslachten] => Array
(
[0] => Dhr.
)
[achternamen] => Array
(
[0] => martens
)
[geboortedata] => Array
(
[0] => 25-10-1993
)
)
<p id="overzichtboeking"></p>
processboeking.php
<?php
include '/home/vhosts/tweb.nl/httpdocs/wp-content/themes/tweb/db/dbcon.php';
print_r($_POST);
?>
<p id="overzichtboeking"></p>
Get complete form data as array and json stringify it.
var formData = JSON.stringify($("#myForm").serializeArray());
You can use it later in ajax. Or if you are not using ajax; put it in hidden textarea and pass to server. If this data is passed as json string via normal form data then you have to decode it using json_decode. You'll then get all data in an array.
$.ajax({
type: "POST",
url: "serverUrl",
data: formData,
success: function(){},
dataType: "json",
contentType : "application/json"
});
Taken from this stackoverflow post: How to send a JSON object using html form data
To go from JSON input on the server side, take a look at this article for converting back to a PHP array: https://www.dyn-web.com/tutorials/php-js/json/decode.php
<?
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"}
I am getting json response from ajax like this
echo json_encode($data);
Ajax code:
$.ajax({
url:"PaymentSlip/check",
data:{val:val},
type: 'POST',
success:function(ajaxresult)
{
$("#jgoli").html(ajaxresult);
}
});
Result I am getting is:
[{"paymentId":"2","paymentLabNo":"MR-622-040618",paymentTestId":"1"}]
Now I want to access my json array in javascript by index like
ajaxresult[0] = 2; i.e paymentId=2
ajaxresult[1] = 2; i.e paymentLabNo=MR-622-040618
How would I achieve that?
Note: I have tried many examples on stackoverflow, I know this question must have answered earlier. But I am still stuck. Any help would be appreciated.
$(document).ready(function(){
var data = [{"paymentId":"2","paymentLabNo":"MR-622-040618","paymentTestId":"1"}];
//Loop on the object as key=>value
$.each(data, function(key, value){
//And diplay it in the result div
$('#result').append('<p>'+data[key]['paymentId']+'</p>');
$('#result').append('<p>'+data[key]['paymentLabNo']+'</p>');
$('#result').append('<p>'+data[key]['paymentTestId']+'</p>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="result"></div>
What you are getting is a string of encoded JSON, to use it as an object you must parse it.
Check this answer
$(document).ready(function(){
$.get("ajax_call.php", function(data){
//console.log(data);
var result = JSON.parse(data);
$.each(result, function(key, value){
$('#data').append('<tr><td>'+result[key]['username']+'</td><td>'+result[key]['email']+'</td><td>'+result[key]['mobile']+'</td></tr>');
console.log(result[key])
});
});
});
$.ajax({
url:"PaymentSlip/check",
data:{val:val},
type: 'POST',
datatype: "json", // add this
success:function(ajaxresult)
{
// access return results as
//ajaxresult[0].paymentId;
//ajaxresult[0].paymentLabNo;
//ajaxresult[0].paymentTestId;
//$("#jgoli").html(ajaxresult);
}
});
I am trying to create an associative array with the record id as the key and order as the value. I then want to pass this via ajax to php where I will foreach through the array and update the records. But it is not working I seem to be getting null at json_decode($_REQUEST['orderArray'], true);
Whats wrong with the code:
jquery :
//Make project task table rows sortable
$('#Task_table tbody').sortable({
items: "tr:not(.disable_sort)",//disable sortable on header row
helper: fixHelperModified, //call helper function
update: function(event, ui) {
var order = {};//create object
$('#Task_table tr').each(function(){//loop through rows
var id = $(this).children('td:first-child').find(".order_number").attr("rel");
var order_number = $(this).children('td:first-child').find(".order_number").val();
//fill object array with keys(task->id) and values (task->order_number)
order[id] = order_number;
});
//convert array to json
var jsonArray = JSON.stringify(order);
//prepare POST data
var dataString = { 'orderArray':jsonArray };
$.ajax({
type: "POST",
url: "index.php?module=Project&action=update_order",
data: dataString,
success: function() {
// location.reload();
}
});
}
});
this sends via post:
orderArray {"4b0df1da-8b2d-7776-0026-52d0b3cefbfa":"3","161699ae-6db0-43d6-e85b-52ca07767b0f":"1","8da4cfc3-b56d-12da-e34c-52d09ed0b310":"2"}
The php:
//updates the order of the tasks
function action_update_order(){
//create object/array from json data
$orderArray = json_decode($_REQUEST['orderArray'], true);
var_dump($orderArray);
foreach($orderArray as $id => $order_number){
$GLOBALS['log']->fatal('order: '.$order_number[$id]);
$task = new ProjectTask();
$task->retrieve($id);
$task->order_number = $order_number;
$task->save();
}
}
As I said I cant seem to foreach through the result of the jasondecode. Also hard to debug as its ajax.
can you try change this
var dataString = { 'orderArray':jsonArray };
to
var dataString = { 'orderArray': order };
For some reason JSON.stringify(order) is adding the Html entity version of " to my string so I need to use htmlspecialchars_decode(); in my php first before json_decode. It seems to work.