Loop Array to Modify Values (JavaScript to PHP and Back to JavaScript) - javascript

I'm working with JavaScript and PHP using arrays, the first step is create the array, here
var ListaA=[];
var i = 0, len = options.length;
while (i < len){
var tmp = {
'proyecto':'test',
'pendientes1':0,
'pendientes2':0,
'terminadas1':0,
'terminadas2':0,
'solucion':0
};
ListaA.push(tmp);
i++;
}
Then i send it to my PHP file like this
var laLista = JSON.stringify(ListaA);
$.get("php/operation.php?test="+ {'test' : laLista }, function( data ){
var tmp = {
'proyecto':""+value['proyecto']+"",
'pendientes1':""+value['pendientes1']+"",
'pendientes2':""+value['pendientes2']+"",
'terminadas1':""+value['terminadas1']+"",
'terminadas2':""+value['terminadas2']+"",
'solucion':""+value['solucion']+""
};
ListaA.push(tmp);
});
As you can see above i have ready the code to get the data which represents the array sent by the PHP file, so i got covered that part, my issue here is in my PHP file, here.
$arrayWork = json_decode($_POST['test']);
Then i want to loop, this time, just for testing i'm just taking one of the values and incresing it to watch the result, like this
foreach($arrayWork as $value){
$value['pendientes1']++; // this is not working for me
}
I got the following: "invalid argument supplied in foreach". So, what's wrong with my code? and which is the properly way to loop it and return it to my JavaScript?
I hope you can help me out with this issue. Thank you for your time and attention, good night.

Using this code
$arrayWork = json_decode($_POST['test']);
your json isn't really converted into an associated array, look at below
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
assoc
When TRUE, returned objects will be converted into associative arrays.
To convert json object into an array just add true to the second parameter to it
$arrayWork = json_decode($_POST['test'], true);**strong text**
To increment an index value in an array
foreach($arrayWork $key => as $value){
$arrayWork['pendientes1']++;
}
Edited.
also since you are using $_POST method change your ajax from $.get to $.post
$.post("php/operation.php?test="+ {'test' : laLista }, function( data ){
var result = JSON.parse(data); // parse json string into json object
...
});

If you want to read $_POST, you have to make a POST request:
$.ajax({
url:'php/operation.php',
type:"POST",
data: { test: ListaA },
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
...
}
})
You can't use $.post, because you have to set the contentType to JSON.
Important: you don't need to run JSON.stringifyyourself, jQuery will take care of it for you - so pass the original ListaA array.

Related

How can i get value?

How can I extract value from response?
Output of alert is [{"maturitydays":"120"}]
I only want value!!
$("#selectCrop").change(function(){ //this ajax will bring default configured crop data
var cropid = $("#selectCrop option:selected").val();
var url = "<?php echo base_url();?>index.php/user/cropConfig/getData";
$.ajax({
data : {'cropid':cropid},
type : 'post',
url : url,
success :function(response) {
alert(response);
}
})
});
It appears your response is inside an array due to the square brackets, this means you need to get the value through:
response[0]['maturitydays']
So your code will look like:
$("#selectCrop").change(function(){ //this ajax will bring default configured crop data
var cropid = $("#selectCrop option:selected").val();
var url = "<?php echo base_url();?>index.php/user/cropConfig/getData";
$.ajax({
data : {'cropid':cropid},
type : 'post',
url : url,
success :function(response) {
alert(response[0]['maturitydays']);
}
})
});
It's json.
Use json_decode to make it array then grab the value from the array (if you must).
$array = json_decode('{"maturitydays":"120"}',true);
$value=$array["maturitydays"];
Echo $value;
https://3v4l.org/Uc51m
The data that you get as response is a JSON array with a number of JSON objects. JSON (JavaScript object notation) can be used as a JavaScript object right away (as long as its not in string form, in which case it has to be parsed with JSON.parse).
When you receive the response you can access it as you would with a normal JavaScript array (in case you are sure its ALWAYS only 1 object, you can select the first index right away):
let obj = response[0];
When you got the object, just access the value you want as you would with a normal JavaScript object:
let val = obj.maturitydays;

Getting null in when trying to get array in servlet

I have a below set of code to get the table data in an array and pass the same to servlet through ajax call. But i am getting null. Please someone help me on what my mistake / how to get the required data since i am new to this servlet and web app. So far i tried with some examples given in SO. but i am clueless to get my expected data.
var myTableArray = [];
$("table#itemtable tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
alert(myTableArray);
$.ajax({
url:"insertmasteritem",
type:"POST",
dataType:'json',
data: {json:myTableArray},
success:function(data){
// codes....
},
});
Servlet code
String[] myJsonData = request.getParameterValues("json[]");
System.out.println("myJsonData.length"+myJsonData.length);
for (int i = 0; i < myJsonData.length; i++) {
String[] innerArray=myJsonData[i].split(",");
System.out.println(myJsonData[i]);
}
Send your Json data like this
$.ajax({
url:"insertmasteritem",
type:"POST",
dataType:'json',
data:myTableArray,
success:function(data){
// codes....
},
});
and In Servlet Class
JSONObject jsonObj= new JSONObject(request.getParameter("myTableArray"));
Iterator it = jsonObj.keys();
while(it.hasNext())
{
String jsonKey = (String)it.next();
String jsonValue = jsonObj.getString(jsonKey);
System.out.println(jsonKey + " --> " + jsonValue );
}
Well, you need to send a properly formatted JSON object (as a string) to the servlet. Possibly the easiest way to do this is to create some javascript objects and fill an array with these objects. The array data should then be
converted to a JSON string (using JSON.stringify). I'm going to hardcode object values (but you will get them from your table)
Javascript code
function generateJson(){
var myObjArr = [];
//you will typically have just one object (e.g. myObj, which you will fill in your ajax table loop
//myObj.v1 = v1_val;
//myObj.v2 = v2_val;
...
//myObjArr[i] = myObj; //
myObj1 = { "v1": "Orange", "v2": "ABC", "v3":10,"v4":"OK" };
myObj2 = { "v1": "Apple", "v2": "XYZ", "v3":25,"v4":"OK" };
myObjArr[0] = myObj1;
myObjArr[1] = myObj2;
var jsonObjStr = JSON.stringify(myObjArr);
//you can now use jsonObjStr to send your data to the servlet
// document.getElementById("json").innerHTML = jsonObjStr;//this is just added for testing purposes
}
The generated JSON
[{"v1":"Orange","v2":"ABC","v3":10,"v4":"OK"},{"v1":"Apple","v2":"XYZ","v3":25,"v4":"OK"}]
As you can see, the json string starts with a [ (which denotes an array). You may have to change this to start with a { (and with a } ) depending on how your JSON parser works ({} denote an object).
For the servlet part, it depends on the actual JSON parser you're using. Try to use some of the suggestions provided by others. I can provide some code using Jackson though, but you will have to add the Jackson library to your classpath.
why you are getting parameter value as JSON[]
String[] myJsonData = request.getParameterValues("json[]");

object_to_array and encode - php to js opbject

I send Ajax call to AjaxHandler.php page, the AjaxHandler page call other function in Functions.php (other page).
On success i need to return object from AjaxHandler.php, the object need to have 2 params.
Here is the ajax call:
var month_number = document.getElementById("Month").innerHTML;
var year_number = document.getElementById("Year").innerHTML;
$.get("AjaxHandler.php", { "year": year_number, "month": month_number }, function (encodedata) {
var data = JSON.parse(encodedata);
$("#LinesPlace").html(data);
});
Here is the AjaxHandler.php code the need to handle that:
if(isset($_GET['year'],$_GET['month']))
{
$year = $_GET['year'];
$month = $_GET['month'];
$a = getExpenses($year, $month);
echo $a->pharama;
echo $a->pharamb;
$b = object_to_array($a);
echo $b;
return json_encode($b);
}
Now when i put that url:
http://xxxxxxxxx.com/AjaxHandler.php?year=2015&month=09
Its show me the echo of pharama and pharamb but when i try to convert the object to array and then decode it its just not working, i tryed alot but nothing.
Here is the object_to_array function:
//convert php object to array
function object_to_array($data){
if(is_array($data) || is_object($data))
{
$result = array();
foreach($data as $key => $value) {
$result[$key] = $this->object_to_array($value);
}
return $result;
}
return $data;
}
*I taked that function from this site from other question..
Please advice =]
Regards,
Rafael.
If you need to decode the JSON as an array or object, json_decode has a parameter specifically for that: http://php.net/json_decode
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
...
assoc
When TRUE, returned objects will be converted into associative arrays.
For example:
$json_as_object = json_decode($json, false);
$json_as_array = json_decode($json, true);
Attempting to manually convert an object into an array should be unnecessary.
You need to encode it very specifically with JSON_UNESCAPED_UNICODE like this:
$jsonObj = json_encode ( string $json, JSON_UNESCAPED_UNICODE);
I have this code in a standard function for this sort of thing
http://php.net/manual/en/function.json-last-error.php
PS. I think you are over checking it in your object to array function. I would probably choose something like: if(is_array($param)){ .. }
Rafael I cant comment need 50 rep or something:D You say: What you mean unnecessary? you mean i can return the object php as is?
Half of what if am saying: you know the things you put into the function obj_to_array() rigth? That what goes in and it ain't an object so why check it? Who will send it? Do you foresee a $_POST incomming all wrapped up as a nice object and ready to go? Like normally the form does a $_POST / $_GET and provides arrays by default as far as I know? And if you produce an obj elsewhere in your code why put use it as input for this function? Don't you know what you are doing somewhere else in your code? Sure you do and as long as you are concise and precise it will never suddenly be a object returned form $_POST or any function normally outputting arrays or integers etc. Check your output as you created it in the first place? Check your web inputs very well (1 time! and for js injections), then only check your types for validating ambiguous output / inputs of your own like an output that can produce an array or a true / false return value. Checking this output for a value of 1 for a TRUE value of the boolean can result in disappointment because:
if the value of $a is 1 in if($a) do something; then a 1 can be the TRUE value returned as the result of the function that produced the thing that we are checking or the result of count($a). If we then assume the array is length 1 because of a misinterpretation of the value of $a then this can give unintended results? You want to be sure that it is the array in $_array($a) that's doing the talking and not the array for example? Thats all to it I think? Or am I rambling (again)?

How do I differentiate array values from PHP in Ajax success function?

I am echoing two array values from PHP. How do I differentiate these values in ajax.
if(#mysql_select_db("trainer_registration"))
{
$select_query_num = #mysql_query("select program_id,facilitator_id,availability_status from program_facilitator");
$select_query_name = #mysql_query("select facilitator_id,firstname,lastname,email_id from facilitator_details");
$num_rows = #mysql_num_rows($select_query_num);
$trainerdetails = [];
$traineravaildetails = [];
$i = 0;
while($row = #mysql_fetch_assoc($select_query_num))
{
$trainerdetails[$i]['pgidi'] = $row['program_id'];
$trainerdetails[$i]['facilitatorid'] = $row['facilitator_id'];
$trainerdetails[$i]['avail_status'] = $row['availability_status'];
$trainerdetails[$i]['idi'] = $row['facilitator_id'];
$i++;
}
while($row1 =#mysql_fetch_assoc($select_query_name))
{
$traineravaildetails[$i]['facilitatorid'] = $row1['facilitator_id'];
$traineravaildetails[$i]['firstname'] = $row1['firstname'];
$traineravaildetails[$i]['lastname'] = $row1['lastname'];
$traineravaildetails[$i]['emailidvalue'] = $row1['email_id'];
$i++;
}
echo json_encode($trainerdetails);
echo json_encode($traineravaildetails);
}
?>
function loadavailabletrainers (m) {
$.ajax({
url: 'assignavailtrainers.php',
data: { action:'test' },
type: 'post',
success: function(output) {
console.log(output);
}
});
}
I've seen a examples of multiple return values from php and handling them in ajax, but I didn't understand them. Can someone please explain how to differentiate output values in my case?
OUTPUT:
[[{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"1","avail_status":"2","idi":"1"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"1","avail_status":"2","idi":"1"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"2","avail_status":"2","idi":"2"}],{"7":{"facilitatorid":"1","firstname":"Vignesh","lastname":"Anand","emailidvalue":"v*******#gmail.com"},"8":{"facilitatorid":"2","firstname":"Vignesh","lastname":"Anandakumar","emailidvalue":"vign*****#gmail.com"},"9":{"facilitatorid":"3","firstname":"Vignesh","lastname":"Anand","emailidvalue":"v*****#hotmail.com"},"10":{"facilitatorid":"4","firstname":"Vignesh","lastname":"Anand","emailidvalue":"****#live.com"}}]
It's a nice practice to send only one stream of values so you can process it all at once.
First, you could create a container array:
$data = array('trainerdetails' => $trainerdetails,
'traineravaildetails' => $traineravaildetails);
Then
echo json_enconde($data);
This will generate a merged output.
The encoded string returned by your PHP code needs to be decoded in the client side (more details: Parse JSON in JavaScript?). Because of that, you could use $.getJSON(), which is an alias for a specific call to $.ajax (doc: http://api.jquery.com/jquery.getjson/).
The 'success' function will pass a 'key'=>'value' array data. In this case you'd need to treat the value as they may contain extra levels of arrays. It helps if you can visualize your data structure as tree view, like this: http://jsonviewer.stack.hu/ (paste your output there).
I hope it helps!

Accessing elements within a data structure

I've had a good search and am stumped. It may be a simple answer, but after 80 hours of work so far this week, I just can't see it...
In my app I pass some variables to a Web Service, which passes back a single structure containing key/value pairs.
$.ajax({
type: "POST",
url: "it_submitcall.php",
data: {callService: "getcall", callid: $("#callNumber").val()},
dataType: "HTML",
success: function(data){
//do stuff here
},
error: function(data){
// unable to communicate with web service stuff here
}
});
The response I get back is
Array
(
[CALLID] => 44497
[CALLERNAME] => Chris
[TEAMID] => 1175
)
How do I access the elements above in javascript? Any pointers would be greatly appreciated...
Many thanks.
On the PHP side use json_encode to turn the Array into JSON e.g:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Then on the JavaScript side use JSON.parse() to get a JavaScript object back - in your case:
success: function(data){
var obj = JSON.parse(data);
},
As #phenomnomnominal notes, you can use json_encode() on a PHP object to turn it to JSON (and, notably, json_decode() to turn it from JSON to a PHP object)
Once you've got that down, nicely, PHP and JS "hash"-like objects act a lot alike (in PHP, we call these associative arrays and in JavaScript, object literals).
In php, you access an array $your_var like this:
$value = $your_var[ 'key' ];
You can also use variables:
$key = 'key';
$value = $your_var[ $key ];
In JavaScript, it's very similar:
var value = your_var[ 'key' ];
Alternatively:
var key = 'key';
var value = your_var[ key ];
And there's one more syntax that's helpful and more efficient when you don't need variable access to a key:
var value = your_var.key

Categories