Array values returns null - php

I am making post request with ajax and sending data with json format.Then I am fetching json with php and decode it into an array.When I print out whole array there is no problem. I can see the key value pairs.But when I try to print out this array's one of index value it returns null.What could be the problem?Here is my ajax request
$(function() {
$("#del").click(function() {
var file_id = 32
var file_update = 1321321
var obj = {
file_id: file_id,
file_update: file_update
};
$.ajax({
type: "post",
url: "config/ajax.php",
data: {
"file_update": JSON.stringify(obj)
},
success: function(response) {
alert(response);
}
})
})
})
Here is my php code
if (isset($_POST["file_update"])) {
$file_update = json_decode($_POST["file_update"], true);
$x = $file_update[0];
var_dump($x);
var_dump($file_update);
}

The $file_update array is associative, therefore it doesn't have integer keys, its keys are strings.
$file_update[0] does not exist and this statement should throw an error given you have proper error reporting configured.
If you want to access specific array values use:
$file_update['file_id'];
$file_update['file_update'];
If you want to access the first element of an associative array you can use the following:
$key = array_keys($file_update)[0];
$value = $file_update[$key];

Related

How to check whether json data array returns a value or not

I am trying to check if an object of an array contains empty data in jquery but it doesn't seemed to work.
It returns the array values if the value passed exist in the database but if the value passed isn't correct it doesn't return any error.
Here is what I have tried so far:
PHP code
if(isset($_POST['name'])){
$json = array();
$id = trim($_POST['name']);
$query = "SELECT regiNo, firstName, middleName, lastName FROM student WHERE regiNo = ?";
$statement = $mysqli->prepare($query);
$statement->bind_param('s', $id);
$statement->execute();
$statement->bind_result($rno, $fname, $mname, $lname);
while ($statement->fetch()){
$user=array('rno'=>$rno,'fname'=>$fname,'mname'=>$mname,'lname'=>$lname);
array_push($json,$user);
}
echo json_encode($json, true);
}
jQuery
<script>
$(document).ready(function(){
$(".Student_reg_code").blur(function () {
var id = $(".Student_reg_code").val();
var data = 'name=' + id;
$.ajax({
type: "POST",
url: "process.php",
data: data,
dataType: 'json',
success: function (data) {
if (data) {
for (var i = 0; i < data.length; i++) { //for each value in the json response
$(".Student_reg_code").val(data[i].id);
$(".regno").val(data[i].rno);
$(".lname").val(data[i].lname);
$(".mname").val(data[i].mname);
$(".fname").val(data[i].fname);
} // for
} // if
else {
alert('Empty value return for that'+ id);
}
} // success
}); // ajax
});
});
</script>
Since json_encode is always returning a value; the data parameter will always be truthy. You can further test the returned data with the following expression:
if (Array.isArray(data) && data.length) {
...
}
Array.isArray will determine if data truly is an array and data.length will be your truthy/falsy to determine if it's empty or not.
In JavaScript, a truthy value is a value that translates to true when
evaluated in a Boolean context. All values are truthy unless they are
defined as falsy (i.e., except for false, 0, "", null, undefined, and
NaN).
Another way for testing out whether an array is empty or not is this:
if(Array.isArray(data) && typeof data[0] !== 'undefined') {
console.log("We got an array");
}
What's the advantage of this over using the length property? Well if you had a very large array the length would have to iterate the entire array, whereas this doesn't.

Ajax + PHP: null instead of an array

Ajax call is made in the background
var signupValidate = function(elementID){
var value = $('#' + elementID).val();
if (value !== ''){
$('#'+elementID+'-status').css("background-image", "url(img/signup/spinner.gif)");
var data = {elementID: value};
var json = JSON.stringify(data);
$.ajax({
url: 'php/validator_signup.php',
dataType: 'json',
type: 'post',
data: json,
success: function(data){
var parsedResponse = JSON.parse(data);
console.log(parsedResponse);
/*
if(data.response === 1){
$('#'+elementID+'-status').css("background-image", "url(img/signup/no.png)");
}else if(data.response === 0){
$('#'+elementID+'-status').css("background-image", "url(img/signup/yes.png)"); }
*/
}
});
}
}
validator_signup.php received the call. So far in test mode PHP will receive the string, parse it and encode again to return to JS:
$post = $_POST['data'];
$data = json_decode($post, true); //decode as associative array
$details = $data[0];
echo json_encode($details);
JS then needs to print this in console.
I get this:
null
instead of the value which I expect back.
Result is same whether I parse returned data or not.
If I understand it correctly, the problem is on PHP side?
There does not appear to be any value in converting to json when your data is so simple, you can just use a regular js object that jquery will convert to form data.
Also, as both the key and value you send are unknown, i would suggest sending the data in a different structure so its easy to retrieve:
var signupValidate = function(elementID){
var value = $('#' + elementID).val();
if (value !== ''){
$('#'+elementID+'-status').css("background-image", "url(img/signup/spinner.gif)");
$.ajax({
url: 'php/validator_signup.php',
type: 'post',
// ▼key ▼value ▼key ▼value
data: { id: elementID, val: value},
success: function(response){
console.log(response.message);
}
});
}
}
In php you can access the data via $_POST, and as you know the keys, its simple:
<?php
$id = $_POST['id'];
$val = $_POST['val'];
//set correct header, jquery will parse the json for you
header('Content-Type: application/json');
echo json_encode([
'message'=>'Request received with the id of: ' . $id . 'and the value of: ' . $val,
]);
die();
Change:
data: json,
To:
data: { data: json},
This is because you aren't giving the sent data a POST parameter to then be used server side to retrieve it.
Then, you can simply fetch the code server-side like this:
$data = json_decode($_POST['data']);
Hope this helps!
Here, since you are checking whether data is being post, if you see in Network, no data is being posted. To fix it, change this part:
var data = {elementID: value};
To this:
var data = {data: {elementID: value}};
Consider removing conversion of Data
PHP automatically handles the $_POST as an array! So you don't need to use the reconversion. Please eliminate this part:
var json = JSON.stringify(data); // Remove this.
And in the server side:
$data = json_decode($post, true); // Remove this
$data = $_POST['data']; // Change this
Update
OP said data[elementID]:gh is sent to the PHP file.
If this is the case, then if the data needs to be "gh" in JSON, then:
$res = $_POST["elementID"];
die(json_encode(array("response" => $res)));
This will send:
{
"response": "gh"
}
And in the client side, you don't need anything other than this:
$.post('php/validator_signup.php', function (data) {
var parsedResponse = JSON.parse(data);
console.log(data);
});
JSON data is sent to the server as a raw http input it is not associated with query name like $_POST['data'] or anything like that which means you must access the input string not a data post value to do so you need to use
$rawInput = json_decode(file_get_contents('php://input'), true);
$elementValue = $rawInput['elementId'];
thats it
$_POST = json_decode(file_get_contents('php://input'), true);
$data = $_POST['data'];

Can't print the json from ajax post using json_decode

I am using ajax to post data to a php script for work to be done... Basically, I'm taking all the form variabes, and creating json... Then taking this json and sending it to the controller script:
function createJSON() {
jsonObj = [];
$("input[class=form-control]").each(function() {
var id = $(this).attr("id");
var value = $(this).val();
item = {}
item [id] = value;
jsonObj.push(item);
});
jsonData = JSON.stringify(jsonObj);
var request = $.ajax({
url: "../../../../ajax/signupController.php",
type: "POST",
data: jsonData,
dataType: "html"
});
request.done(function( msg ) {
console.log(msg);
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
}
My code gets to the php script fine, and when I use "print_r" in php to print the output, I get this:
Array
(
[0] => stdClass Object
(
[mail-firstname] => FName
)
[1] => stdClass Object
(
[mail-lastname] => Lname
)
)
My problem is, I can't GET AT the elements... I have tried:
$data = json_decode(file_get_contents('php://input'));
foreach ($data as $key => $value) {
print "<p>$key | $value</p>";
}
but I can't get at the array elements... I get an error... What am I missing about accessing the array after decoding the file contents?
Thanks.
Update:
Modified foreach:
foreach($data as $key=>$value){
print $value->ccyear;//now I can get at individual elements
}
BUT ANY VALUE THAT HAS A DASH IS CAUSING THE SCRIPT TO FAIL... For example, if the name is "mail-firstname" PHP thinks it's mail AND firstname...
The problem is that your values are nested an extra level in your data. And they each have different keys, so it's hard to get at them. It would be better if you use the id as the keys of the top-level array, rather than nesting them:
jsonObj = {};
$("input[class=form-control]").each(function() {
var id = this.id
var value = this.value;
jsonObj[id] = value;
});
Then you should change your PHP to use the second argument to json_decode(), so you get an associative array instead of a stdClass object:
$data = json_decode(file_get_contents('php://input', true));
I'm not really sure why you need to send JSON. Why not just use:
data: jsonObj;
Then you can access the inputs as $_POST['mail-firstname'], etc.

How to create a two-dimensional array in PHP and iterate through it with Javascript

Im currently trying to do the follow:
Request a PHP file from my image.js code
In the request call - query out data from my mysql database and save
it in a PHP array
Return the array to image.js as a JSON object.
I got nr 1 + nr 3 covered - what im strugling with is how to save my database attributes correctly into the PHP array and afterwards iterate through each record from the json callback.
Database attribute example:
player_id (unique key) || player_name || player_country || player_image || player_league ||
Question/Challenge 1: Saving the Array (this is what im not sure of)
while ($row = mysql_fetch_assoc($res))
{
$myCallbackArray[] = array($row['player_id'], $row['player_name'], $row['player_country'], $row['player_image']);
}
- The following array, will just be one "flat-array" with no dimension based on saving all corresponding attributes under seperate player_id's?
To give some some context - and assuming the array is fine, we then in a 'next-step' send it back to JS
$callback = $myCallbackArray;
echo json_encode(array('returned_val' => $callback));
Question/Challenge 2: Accessing the array values in JS (this is what im not sure of)
//Save the data
var url = "request.php"; //
var request = $.ajax({
type: "POST",
url: url,
dataType: 'json',
data: { user_id: id},
success: function(data)
{
//HERE WE HANDLE THE RETURNED ARRAY
if(data.returned_val) {
for( var i = 0; i < data.returned_val.length; i++ ){
//HERE I WOULD LIKE TO MAKE THE DIFFERENT ATTRIBUTES ACCESSABLE
}
},
error:function() {
//FAILURE
}
});
return false;
-So in this part im not sure how to actually handle the multi-dimensional array from PHP. I assume we need to save it out in a Javascript array and then we can probably iterate / access each value through an foreach loop - but yet again,- how im not entirely sure?
I'll suggest to use json_encode:
$myCallbackArray []= (object) array(
"player_id" => '...',
"player_name" => '...',
"player_country" => '...',
"player_image" => '...',
"player_league" => '...'
);
$json = json_encode($myCallbackArray);
$json is actually the following:
[{"player_id":"...","player_name":"...","player_country":"...","player_image":"...","player_league":"..."}]
which is valid JSON and you could easily use it in javascript.
I think your accessing the data wrong in your success function, the data comes back as an array. Here is an example:
var request = $.ajax({
type: "POST",
url: url,
dataType: 'json',
data: {user_id: id},
success: function(data){
var myval = data["returned_val"];
alert(myval);
},
error:function() {
//FAILURE
}
});

How Print json Array in Javascript

PHP: Code:
$category_searchresult = $db->db_query("SELECT category_code, category_name, category_comment FROM qa_categories WHERE ".$search_by." LIKE '%".$search_string."%'");
$i=1;
$qa = array();
while($categories_query_result = mysql_fetch_array($category_searchresult))
{
$qa[$i][] = $categories_query_result['category_code'];
$qa[$i][] = $categories_query_result['category_name'];
$qa[$i][] = $categories_query_result['category_comment'];
$i++;
}
echo json_encode($qa);
JS Code:
$.ajax({
type: "POST",
url: "ajax_js.php",
data: search_data,
cache: false,
success: function(search_result) {
//Print Here
});
Current Output IS from PHP:
{"1":["4BA3CC","Fontaneria","Para la Casa"],"2":["CF0345","Herramientas","Herramients de Hogar"],"3":["1265CA","Luces","Luces de todo tipo"],"4":["4C4C9F","Vidrios","Reflectores de auto"]}
Many Thank's
Add a
dataType: 'json'
to your .ajax() call. That will tell jQuery to decode the JSON string from PHP back into a native Javascript data structure. Alternatively, you can take the data parameter in the success handler and explicitly do the decoding yourself:
success: function(data) {
var data = jquery.parseJSON(data);
}
Not quiet sure what the output should be but this is the code you can use to traverse a json object:
for(var key in search_result) {
var result = search_result[key];
//result is an array, so you can traverse or access each value by the key
// or you can join all the values together
var joinedValues = result.join(' | ');
//joinedValues will be something like '4BA3CC|Fontaneria|Para la Case'
}
You may want to set those values into a container object in the page to diplay them of course.
Hope this helps.

Categories