Getting array values in php from jQuery post - javascript

I am trying to send an array from jQuery post to PHP.
But I am not getting any values with the below code.
Could anyone help ?
jQuery
$("body").on("click", ".js-form",function(event){
var arr = [];
i = 0;
$('.addcolor').each(function() {
if( $(this).text()=="done"){
arr[i++]= $(this).data('request-id');
}
});
alert(arr);
$.post("../ajax/save_Request.php", {requestids:arr, action:'save_request' })
});
alert(arr)-> prints 11,24,35 (eg)
But I am not getting any values in the following PHP variable.
PHP
$ids = ( isset($_POST['requestids']) ) ? $_POST['requestids'] : 0;

Try with this 'choices[]'
$.post( "test.php", { 'choices[]': [ "Jon", "Susan" ] } );
See more in : jQuery.post and search the key "Pass arrays of data to the server". I think that you missed []. Try it and return me the result.

Try converting the array to a JSON string first, using
var json = JSON.stringify(arr);
Now that it's a JSON string, you can simply pass it through a hidden field. Then, once you get the string back from the PHP page, you can turn it back into an array using
$array = json_decode($arr, true);
where $arr is the JSON string.
I had a similar problem with trying to pass an array from JQuery to another PHP page and this worked for me.

Related

Create javascript array which have the same structure with php array

In the sever side i have an array with structure like that:
array ('_1489378560544_544' => array (
'customer_group_id' => '0',
'permission_id' => 'disable_products_price',),
'_1489740032764_764' => array (
'customer_group_id' => '',
'permission_id' => '',),)
So now in the client side i want to create an javascript array with the same structure to server side. Is there any possible way to do that?
So after i got all data separately how can i organize my array look like this
var arr = [{_1489378560544_544 : [customer_group_id : 0 , permission_id : 'permission_id'] }]
Here is my javascript get data function:
$('#category_permission > tbody > tr').each(function() {
var id = $(this).attr("id");
var customer_group_id = $(this).children('td:first').children('select:first').val();
var permission_id = $(this).children('td:nth-child(2)').children('select:first').val();
});
Thanks for your help.
You can use json_encode to convert your PHP array to a JSON string and use JSON.parse() to obtain the equivalent Javascript object. Take a look here: https://www.w3schools.com/js/js_json.asp
Something like this :
var arr = [{_1489378560544_544 : [customer_group_id : 0 , permission_id : 'permission_id'] }]
in your php view file
jsStr = '<?php echo json_encode($array)?>'
jsObj = JSON.parse(jsStr);
console.log(jsObj.keyname);
like that all keys can be accessed to get the value. javascript don't support alphanumerical keys for array.
Answer from #Mistalis should help.

JQuery unable to parse JSON string created by json_encode

I am currently in a bind, JQuery is unable to parse the following json strings
{ "query":"Unit",
"suggestions":
[ {"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79} ] }
{"query":"Unit",
"suggestions":
[{"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79}]}
The above strings when parse through JSON.parse create the following arror:
SyntaxError: JSON.parse: unexpected non-whitespace character after
JSON data at line 1 column 112 of the JSON data
The PHP code which creates the string above is this:
public function getCustomerSuggestions($name){
$customers = $this->model->where('name','LIKE','%'.$name.'%')->show();
if(count($customers)>=1){
foreach($customers as $customer){
$list[] = ['value' => ucfirst($customer->name),'data' => $customer->id];
}
}
else{
$list[] = ['value' => 'No Customers Found', 'data'=> NULL];
}
$full_list['query'] = 'Unit';
$full_list['suggestions'] = $list;
return json_encode($full_list);
}
As you can see I am using the function json_encode to create the JSOn string so there should be no issue but it still doesnt work.
Edit
The json is sent using an autocomplete tool called DevBridge Autocomplete which takes the JSON strings and creates a suggestion list. The code I am using is
$('input[name=\"customer\"]').devbridgeAutocomplete({
serviceUrl: '".SITE_PATH."/ajax/admin/quotes/getcustomer',
minChars: 1,
onSearchStart: function (query){
var searchinput = $(this).val();
$('.autocomplete-suggestions').html('Searching: '+searchinput);
},
onSelect: function(suggestion){
var selection = $(this).val(suggestion.value);
$('input[name=\"customerid\"]').val(suggestion.data);
$.get('".SITE_PATH."/ajax/admin/quotes/getcustomerdetails',{id: suggestion.data},
function(response){
var obj = $.parseJSON(response);
$.each(obj, function(key, value){
$('#'+key).val(value);
});
});
}
});
It seems you have two JSON objects after each other. That's simply invalid. There can only be a single value at the root of a JSON "document". If you want to send down multiple objects, you need to put them in an array.
It seems getCustomerSuggestions is called multiple times and the return value of each call is returned to the client. Instead, the method should return an array, the caller should collect the return values in an array and JSON encode that array.
Well, your JSON string is NOT valid.
It should be,
[
{ "query":"Unit",
"suggestions":
[ {"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79} ] }
,
{"query":"Unit",
"suggestions":
[{"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79}]}
]
But as Felix Kling said, check your PHP code.

Convert a SQL BIT into JSON through to jQuery and finally display in HTML?

I'm working with checkboxes and JSON and I'm trying to find the cleanest way to set a checkbox on a JSON return. The JSON pulls from a BIT field out of SQL, and the code below works but I don't really like it...
PHP:
$outputArray = array(
'submissionaddress' => htmlentities($row['StateSubmissionAddress'], ENT_COMPAT, 'UTF-8'),
'isactive' => $row['IsActive']);
return json_encode($outputArray);
JSON:
{"submissionaddress":"Temp","isactive":"1"}
jQuery:
success: function(data) {
var checked = (parseInt(data.isactive, 10) === 1) ? true : false;
$('#submissionAddressCheckBox').attr('checked', checked);
}
Javascript didn't like (data.isactive) and that always returned false, so I parsed it to an int. I assume that's because JSON returns "isactive":"1" and it's interpreted as a string.
What's the best way to interpret a BIT value into JSON, and than transfer that value into a checkbox in HTML?
You can convert the string to an int with + and then the !! converts to a boolean.
success: function(data) {
var checked = !!+data.isactive;
$('#submissionAddressCheckBox').attr('checked', checked);
}
Does your Ajax request has dataType set to json? If not you should parse it.

JSON format issue in JavaScript

Following is my JavaScript code to get JSON data:
$(document).ready(function()
{
$.support.cors = true;
$.getJSON('http://example.com/root_dir/test_json.php', function(data1)
{
alert("data1= "+data1);
});
});
but the above alert shows me JSON in following format-
If I hit my php script URL in browser, it shows JSON data in expected formate as shown below-
[{"name":"AB","std":"7","number":"82"},{"name":"CD","std":"9","number":"90"},{"name":"PQ","std":"12","number":"79"}]
Following is my test_json.php code-
<?php
//Create an array
$json_response = array();
$row_array['name'] = 'AB';
$row_array['std'] = '7';
$row_array['number'] = '82';
array_push($json_response,$row_array);
$row_array['name'] = 'CD';
$row_array['std'] ='9';
$row_array['number'] = '90';
array_push($json_response,$row_array);
$row_array['name'] = 'PQ';
$row_array['std'] = '12';
$row_array['number'] = '79';
//push the values in the array
array_push($json_response,$row_array);
echo json_encode($json_response);
?>
getJSON decodes the JSON into a JavaScript data structure.
Concatenating it with a string will implicitly call toString() on it. That will turn arrays in to a comma-seperated format and plain objects into "[Object object]".
Nothing is going wrong. That is the expected behaviour.
If you want to see the data in JSON format, then use JSON.stringify(data) or use .ajax instead of .getJSON and access the raw text data in the jqXHR object.

How could I JSON.parse nested object inside array

I'm trying to pass this structure on a PHP/Ajax response:
{"asn":"167", "jte":"[[1381547700000,0.0], [1381548600000,0.0]]", "visitas":"[{x:1380596400000,text:'HELLO WORLD.',title:'X'}]"}
But JSON.parse returns an error.
SyntaxError: JSON.parse: expected property name or '}'
Without the "visitas" object everything runs fine. Is it possible to "nest" as this?
UPDATE:
Ajax Part:
$.ajax({
type: 'post',
url: 'cxxx.php',
data: { asn: asn },
success: function(p){
p = JSON.parse(p);
jusante=JSON.parse(p.jusante);
montante=JSON.parse(p.montante);
vazao=JSON.parse(p.vazao);
minima=JSON.parse(p.minima);
fator=JSON.parse(p.fator);
visitas=JSON.parse(p.visitas)
and PHP part:
$v="[";
while(odbc_fetch_row($res)){
$datavisita = odbc_result($res, "DATA_VISITA");
$descricaovisita = odbc_result($res, "DESCRICAO_VISITA");
$login = odbc_result($res, "LOGIN");
$descricaomotivo = odbc_result($res, "DESCRICAO_MOTIVO");
$id_motivo=odbc_result($res, "ID_MOTIVO");
$datavisita=date("U", strtotime($datavisita))*1000;
$descricaovisita=preg_replace("/\r|\n/", "", $descricaovisita);
$v.="{x:$datavisita,text:'$descricaovisita',title:'$id_motivo'}, ";
}
$v=rtrim($v,", ")."]";
echo "{\"asn\": \"$asn\", \"description\": \"$description\", \"jusante\": \"$o\", \"montante\": \"$m\", \"vazao\": \"$f\", \"minima\": \"$mn\", \"fator\": \"$fp\", \"visitas\": \"$v\" }";
the Json you are using is valid, I checked it on JSONLint, so your problem might be with serialization, just make sure your "visitas" object is serialized correctly because the problem might be happening because it's the only member with an object value inside
Remove the quotes around the visitas array:
var json = JSON.parse('{"asn": "167","jte": "[[1381547700000,0.0], [1381548600000,0.0]]", "visitas": [{"x": "1380596400000", "text":"HELLOWORLD.","title":"X"}]}');
While the outermost JSON object looks fine, there might be a problem with the nested one!
If you are trying to parse the nested JSON element "visitas" you might have a problem in the fact that your property names (e.g. x, text and title) are not enclosed in quotation marks ("). This is of course a bit tricky since you are trying to include the visitas element as a string.
A solution might be to include the visitas element as a proper JSON element instead.
You need to escape the single quotes. I imagine you are surrounding the above in single quotes when you pass it to JSON.parse.
The below works.
JSON.parse('{"asn":"167", "jte":"[[1381547700000,0.0], [1381548600000,0.0]]", "visitas":"[{x:1380596400000,text:\'HELLO WORLD.\',title:\'X\'}]"}');
Note the slashes before the single quotes inside the string.
I would do the following:
var jsondata = {
"asn": "167",
"jte": "[[1381547700000,0.0], [1381548600000,0.0]]",
"visitas": "[{x:1380596400000,text:'HELLO WORLD.',title:'X'}]"
};
jsondata = JSON.stringify(jsondata);
then send it to php
var postdata = { data : jsondata};
var url = "<?php echo base_url(); ?>"+"test";
$.post(url, postdata, function(result){
console.log(result);
});
sice your php result is echoed the wrong way you should fix that first. Create arrays so that you can easily use the JSON_ENCODE function like so:
$array = array(
"asn" => "test_asn",
"description" => "description_test",
"jusante" => "jusante_test",
"montante" => "montante_test",
"vazao" => "vazao_test",
"minima" => "minima_test",
"fator" => "fator_test",
"visitas" => "visitas_test"
);
$json = json_encode($array);
echo $json;

Categories

Resources