Well I followed this question, but cannot send array to php it returns me always empty:
JS:
values = [];
values['mpsRegnomer'] = $('#mpsRegnomer').val();
values['mpsMarka'] = $('#mpsMarka').val();
values['mpsMarkaOther'] = $('#mpsMarkaOther').val();
values['engineType'] = $('#engineType').val();
values['seatNumberInput'] = $('#seatNumberInput').val();
values['carColor'] = $('#carColor').val();
values['mpsChassiNum'] = $('#mpsChassiNum').val();
values['mpsModel'] = $('#mpsModel').val();
values['mpsModelOther'] = $('#mpsModelOther').val();
values['mpsManufactureDate'] = $('#mpsManufactureDate').val();
values['mpsfor'] = $('#mpsfor').val();
values['VehicleType'] = $('#VehicleType').val();
values['dvigatelInput'] = $('#dvigatelInput').val();
values['engineMaxPower'] = $('#engineMaxPower').val();
values['is_automatic'] = $('#is_automatic').val();
console.log(values);
$.ajax({
type: 'POST',
url: 'assets/clients/services/saveDataMPS.php',
async: false,
dataType: "JSON",
data: {"values": JSON.stringify(values)},
success:function(response){
alert(1);
}
});
console.log(values) show me that array is OK.
PHP code:
<?php
var_dump(json_decode($_POST["values"])); exit;
It returns me always empty, also tried only with var_dump($_POST); same result.. Where am I wrong?
Result from console.log(values):
You defined values as an array and therefore when you stringify it, you get an empty array. Define it as an object like values = {}; and it will work.
You don't use associative arrays in javascript because
If you use named indexes, JavaScript will redefine the array to a
standard object. After that, some array methods and properties will
produce incorrect results.
Thats's why you need to define it as object in the beginning.
values = {};
values['mpsRegnomer'] = $('#mpsRegnomer').val();
values['mpsMarka'] = $('#mpsMarka').val();
values['mpsMarkaOther'] = $('#mpsMarkaOther').val();
Here is a working JSFiddle.
http://jsfiddle.net/pk97fe0b/
Related
I'm trying to send object array to node.
If i'm sending it without stringify, i'm getting an array with the same length that i sent, but empty (["", ""]);
if i send it with JSON.stringify , this it the result:
{'[{"itemNumber":"13544","currentShelf":"1A1","amount":"1","newShelf":"","actionType":"in","whareHouse":"Main"},{"itemNumber":"13544","currentShelf":"1B1","amount":"1","newShelf":"","actionType":"in", "whareHouse":"Main"}]': '' }
This is how i'm sending it:
for (var i=1; i<=m; i++){
itemIdTemp= document.getElementById("itemIdShell"+i).value;
shellTemp= document.getElementById("id_shell"+i).value.toUpperCase();
newShellTemp= document.getElementById("id_shell_new"+i).value.toUpperCase();
shellAmountTemp = document.getElementById("amountShell"+i).value;
itemAmount=0;
let itemData={
itemNumber:itemIdTemp,
currentShelf:shellTemp,
amount:shellAmountTemp,
newShell:newShellTemp,
actionType:direction,
whareHouse:"Main",
};
console.log(itemData);
itemsObject.push(itemData);
}
console.log(itemsObject);
$.post('/itemShell/updateMulti',
JSON.stringify(itemsObject),
function(data){
console.log(data);
});
The object contain a string of the array and i can't get it.
I tried Json.Parse(), it won't work in this case.
any suggestions?
Have a look at this example code
const jsObjectArray = [
{name: "Homer", age:56 },
{name: "Marge", age:50 },
];
const buf = JSON.stringify(jsObjectArray);
console.log("Stringified object: "+buf);
//
// Now convert it back to an object
//
const newObject = JSON.parse(buf);
console.log("Reconstituted object: "+newObject);
It's in this codepen too:
https://codepen.io/mikkel/pen/KRayye
I found the problem.
It must be declare as JSON type when post to Node, so u need to use ajax:
$.ajax({
url: '/itemShell/updateMulti',
type:"POST",
data:JSON.stringify(dataTosend),
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){}
}
and i also change it to object type like this:
dataToSend={dataArr:itemsObject}
So in node it's appearing as array
My Guy work a little bit on the string before sending it
First get the string the stringify is returning
var json_string = JSON.stringify(itemsObject);
var string = json_string.replace("'", "\'");
string = '{\'[{"itemNumber":"13544","currentShelf":"1A1","amount":"1",
"newShelf":"","actionType":"in","whareHouse":"Main"},
{"itemNumber":"13544","currentShelf":"1B1","amount":"1",
"newShelf":"","actionType":"in", "whareHouse":"Main"}]\': \'\' }';
first_str = string.split("': "); // remove the last useless chars
second = first_str[0].substring(2, first_str[0].length); // remove the first two chars
$.post('/itemShell/updateMulti', second,
function(data){
console.log(data);
});
the second should have the correct string.
GOODLUCK
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[]");
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.
I have an ajax response in json format. Then in my javascript (ajax response success) i have the two arrays stringify. Now I need to place data in one curly bracket to 2 variables and then other curly bracket in another 2 variables.
Here's the code
var results = JSON.stringify(result).substr(1,JSON.stringify(result).length-2);
Here's the ajax(.js file)(part of it now whole code)
$.ajax({
url: "ajax/default_q.php",
dataType: "json",
type: 'POST',
data: {dtime: n},
success: function(result) {
var results = JSON.parse(result);
var mtime = results.microtime;
var srp = results.srp;
alert(mtime);
alert(srp);
Here's the php
$sql = "SELECT microtime,srp FROM loading WHERE submit_id = 'XXXXXXXXXXXXXXXXXX' AND microtime BETWEEN UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 day)) and 1480573758";
$res = mysqli_query($GLOBALS['link'],$sql);
while($row = mysqli_fetch_assoc($res)){
$content[] = $row;
}
echo json_encode($content);
Ok. I want the microtime which is highligthed in yellow be stored in variable a so if I alert the a it will look like the photo below although not exactly the same. And same as the srp.
How will I achieve that. PLease help/.
You can parse your JSON ajax response and traverse it as a object rather than using substr to break the string.
var results = JSON.parse(result);
var mtime = results[0].microtime;
var srp = results[0].srp;
Update
Since you have already used dataType: "json" jQuery has already parsed JSON string into object. You don't have to explicitly parse JSON again. Here is the updated code:
var mtime = results[0].microtime;
var srp = results[0].srp;
You can loop through the array to traverse through all values.
I am storing my array in hidden field
var myarray = [];
if ($(this).prop('checked')) {
myarray.push(val);
$('#myhidden').val(JSON.stringify(myarray));
}
how can I retrieve that array ? because I want that array to past it to other page using jquery.ajax
I tried this
var retarray = $('#myhidden').val();
["110","118"]
when I send that using jquery.ajax
$.ajax({
type: 'post',
dataType: 'json',
url: 'tootherpage.php',
data: 'param1=' + param1 + '¶m_array=' + retarray,
success: function(data) {
}
});
it gives me error because it is not an array.
Thank you in advance.
You're converting your array to a string here:
$('#myhidden').val(JSON.stringify(myarray));
If you need it to be an array, then you need to parse this array back from the string
var retarray = JSON.parse($('#myhidden').val());
for example:
var array = [1,2,3,4]; // create an array
var stringarray = JSON.stringify(array); // convert array to string
var array2 = JSON.parse(stringarray); // convert string to array
Try this
var retarray = encodeURIComponent($('#myhidden').val());
Your ajax request is is using the method POST and you have specified a data type of json which means your http request is sending json in the body.
So you can send your whole request message as json, like this:
// get json from input
var retarray = $('#myhidden').val();
// parse json into js
var arr = JSON.parse(retarray);
// create your request data
var data = { param1: param1, param_array: arr };
// stringify
var json = JSON.stringify(data);
$.ajax({
type: 'post',
dataType: 'json',
url: 'tootherpage.php',
data: json, // the json we created above
success: function(data) {
}
});
Then in your php script you can deserialize the json message to a php object like so:
$json = file_get_contents('php://input'); $obj = json_decode($json)
You can do this :
$('#myhidden').val(myarray.split("|")); //set "0|1".split("|") - creates array like [0,1]
myarray = $('#myhidden').val().join("|"); //get [0,1].join("|") - creates string like "0|1"
"|" is a symbol that is not present in array, it is important.