Cannot read NULL variable in PHP after posting JSON array through .ajax() - javascript

I'm having a problem like many other people, being able to read a PHP array variable after having sent it through ajax() post. Ajax is succeeding and displaying the returned data, which is NULL. I have already thoroughly researched SO solutions for this JSON/PHP problem, and my problem description shows 'almost' EVERY solution on SO so far.
On the PHP side I've tried:
$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);
(Skipping over $HTTP_RAW_POST_DATA (deprecated) because it's equal to file_get_contents('php://input')
and also:
$data = json_decode($_POST["a_arr"], true);
I've already tried clearing the UTF-8 BOM with the sed command
sed '1s/^\xEF\xBB\xBF//' < index.html > index2.html
My .ajax() looks like this:
$.ajax ({
url:"file.php",
method:"post",
contentType: "application/json; charset=utf-8",
data: { a_arr : JSON.stringify(arr) },
})
.done(function(response){
$("#status").html(response);
});
On the Javascript side here is my array:
var arr = [{"name":_name, "phone":_phone, "email":_email, "repname":repname, "repnumber":repnumber, "office":office}];
ajax_post(arr);
I've checked to make sure there is no JSON formatting error, the following successfully shows me a valid JSON formatted array:
var data_arr = JSON.stringify(arr);
document.getElementById("status").innerHTML = data_arr;

You need to change to:
data: JSON.stringify(arr),
When you give an object to the data: option, it converts it to URL-encoded format, not JSON.
Or you can leave the data: option as it is, but get rid of the contentType: option, and then you should use
$data = json_decode($_POST['a_arr'], true);

Related

How to fetch data from the database into a javascript file and store it in array?

I am building a currency converter app for my school project and at the moment I am trying to get data from the database into a .js file. The exact goal is to get data from the database and save it into an array within a .js file.
As far as I know there is no way to get data from the database directly into a JavaScript file, so I am trying to make use of JQuery and PHP combination as pointed out in this thread.
I have a database called 'currencies' which has six columns: id, basecur1, basecur2, basecur3, basecur4, basecur5.
id field is for user id, and basecur_ fields are for storing user's prefered currencies and can only contain three characters of a currency code (like USD or GBP) or be empty. I need to get a result looking like const array_name = ["EUR", "GBP", "USD"];
Please note that I am using CodeIgniter PHP framework for back-end.
In this file query.php I am trying to create an array from the data fetched from the database and echo it:
<?php
$current_user = $this->session->user_id;
$query = $this->db->get_where('currencies', array('id' => $current_user));
$row1 = $query->row();
$base_currencies = array($row1->basecur1, $row1->basecur2, $row1->basecur3, $row1->basecur4, $row1->basecur5);
$post_data = json_encode($base_currencies);
echo $post_data;
?>
Unfortunately, I don't have deep understanding of JavaScript, so I can't really say what's wrong with this JS code, which is taken from the thread mentioned above, but it doesn't really work for me:
jQuery.extend({
getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'json',
async: false,
success: function(data) {
result = JSON.stringify(data);
}
});
return result;
}
});
var array_name = $.getValues("query.php");
Any help will be much appreciated.
Because of these line you already have a valid json string:
$post_data = json_encode($base_currencies);
echo $post_data;
exit;
and since you already set the dataType: 'json' jquery will parse the result as a json string regardless of the header.
Thus:
success: function(data) {
result = data;
}
You can debug using console.log it is a valuable tool for learning and making sure you are getting what you want at various points in your code. As another user suggested, make sure you aren't getting any 404 errors in the console. query.php doesn't look like a valid CodeIgniter route.
In your php file.
header('Content-Type: application/json');
in your ajax function
success: function(response){
console.log(resposne)
}
see if you are getting anything
I think you are not passing a valid url
try adding an error function to get some info:
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'json',
async: false,
success: function(data) {
result = data
},
error: function(error) {
alert(error);
}
});
return result;
Update: Try to output the variable directly as alex has suggested

Extract Json response

I am trying to to extract a Json response in jquery sent from a php file.
This is the .js code:
$.ajax({
url: 'index.php?page=register', //This is the current doc
type: 'POST',
datatype: 'json',
data: {'userCheck': username},
success: function(data){
// Check if username is available or not
},
error: function(){
alert('Much wrong, such sad');
}
});
This is the response from the php file:
if($sth->fetchColumn()!=0){
//$response = array("taken");
$response = array("username"=>"taken");
echo json_encode($response);
//echo '{"username':'taken"}';
}else{
//$response = array("available");
$response = array("username"=>"available");
echo json_encode($response);
//echo '{"username":"available"}';
}
I have tried all combinations I can think of in both files, but nothing seems to work. It is a simple check for a username in the database. If I console log the data I get from the response, I get this:
{"username":"available"}<!DOCTYPE html>
// The rest of the page html
So the info is there, but how do I access it? I have tried several syntaxes found around the internet, but no luck so far. I seem to recall that a json response only can contain valid json, so is the problem the html? I don't think I can avoid this due to the structure of my application, so hopefully it is possible to access the json with my present structure.
in you Ajax
EDIT:
change
datatype:"json",
the case of parameter name was not respected, the t must be T
dataType:"json",
now retry please
$.ajax
({
url: 'index.php?page=register', //This is the current doc
type: 'POST',
dataType: 'json',
data: {'userCheck': username},
success: function(data)
{
// Check if username is available or not
switch(data.username)
{
case "available":
// do you want
break;
case "taken":
// do you want
break;
}
},
error: function()
{
alert('Much wrong, such sad');
}
});
in PHP
simply that, and don't forget to exit; to avoid include html page in your json response !
This is the code coming after the }".... who break your json output
and make it unreadable by javascript (worste, it simply break your javascript !)
echo json_encode(["username"=> ($sth->fetchColumn()!=0) ? "taken":"available"]);
exit;
When you're responding to an AJAX call, you should just return the JSON response, not the HTML of the page. Add:
exit();
after this code so you don't display the HTML after the JSON.
In the JS code, use if (data.username == 'available') to tell whether the username is available.
The other problem in your code is that you have a typo here:
datatype: 'json',
It should be dataType, with an uppercase T.
You can also put:
header("Content-type: application/json");
before echoing the JSON in the script, and jQuery will automatically parse the response.
Also you can set request headers in your jQuery ajax call beforeSend function like follows
beforeSend: function (xhr) {
xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
xhr.setRequestHeader('Accept', 'application/json');
}
So you're strictly declaring the data type to be json

Ajax receive a collection of objects from Laravel

I currently am attempting to create my own instant messenger for my site (NOT using a plugin - am attempting to hand make this for learning purposes) and I am looking to try to send an ajax request to the server for a list of all messages between two users. My question is this: can ajax 'read' a collection of Message objects sent from Laravel (doubt it) or does it need to be formatted in a certain way/manner? I initially thought to use lists to get the sender_id along with the message (the order is by date by default), however, I don't think that javascript can read PHP's (not)-arrays. The only viable solution I have came up with thus far is to send either 1 array with sender_id followed by the message for the entire conversation OR 2 arrays- one with all sender_id's in order and a second with all messages in order.
Thanks.
You can use JSON for communicating between PHP and JavaScript (look up PHP json_encode and json_decode functions), it'll allow you to pass complex arrays almost natively between the languages.
EDIT: a few examples to give some indication how it works, I'm using jQuery for my examples here
Requesting information from a PHP script via AJAX:
$.ajax({
method: 'GET',
dataType: 'json',
success: function(data) {
for (i in data.messages) {
output(data.messages[i]);
}
}
});
var output = function(message) {
console.log(message.id);
console.log(message.sender.id);
};
The PHP script can output:
$messages = array(
array(
'id' => 1,
'message' => 'Awesome',
'sender' => array(
'id' => 1, 'name' => 'John',
),
),
);
echo json_encode(array('messages' => $messages));
Sending information using JSON via AJAX:
// Example data object, you can have this infinitely nested
var data = [
{id: 1, "message": "test" }
];
$.ajax({
method: 'POST',
dataType: 'json',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
});
var output = function(message) {
console.log(message.id);
console.log(message.sender.id);
};
The PHP script can then read this using:
$data = json_decode(file_get_contents('php://input'), true);
// This becomes a simple 2D PHP array which is an exact representation as your JS object. The above example data can be output as:
foreach ($data as $message) {
echo $message['id'] . ' - ' .$message['message'];
}

json_encode to send data back to js

Im creating a simple upload script. I use a simple form to let people upload a picture and then a external php script will upload the picture and return some vars to the upload page.
But I cant get the part to return some vars to work. currently im using this:
The page that also contains the form:
form_data.append('file', file_data);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(response){
document.getElementById("titel" + amount).innerHTML = response['naam'];
});
The upload page that should return some data:
echo json_encode(array('naam'=>$naam));
This scripts returns undefined..
If I remove the ['naam'] after response on the form page it will print out:
{"naam":"test.png"}
Hope someone know what im doing wrong.
Thanx in advance!
You said:
dataType: 'text', // what to expect back from the PHP script, if anything
… so jQuery will ignore what the server claims the data is (which seems to be HTML as you haven't changed the Content-Type header in your PHP) and process the response as if it was plain text.
response will therefore be a plain text string and not the results of parsing JSON.
Change dataType to "json".
The response you get from the server is the string. To use it as object, you need to parse it to JSON format using JSON.parse().
var obj = JSON.parse(response);
Then you can use:
obj.naam;
to get the value of naam from the object.
Please change datatype from "text" to "json" then parse that JSON using JSON.parse(//return value ").
Var jsonObject = JSON.parse("Ajax Response object");
then use it jsonObject.keyName and it will return the value.

Posting JSON string to PHP page

Okay, I'm having some suicidal issues posting a JSON string to a PHP page. I have literally been through the top ten results on Google and plenty of SO questions related to my problem, but still can't work out what I'm doing wrong.
I have multiple forms on a page and want to collect all form fields, turn them into a JSON string and post them to a PHP page, where a script iterates each item and updates the relevant database tables.
This is my jQuery/JS script to collect the data from all the forms:
var photo_annotations = {};
$('form').each(function(i) {
var id = $(this).attr('id');
photo_annotations[id] = {
caption: $('#'+id+'_caption').val(),
keywords: $('#'+id+'_keywords').val(),
credit: $('#'+id+'_credit').val(),
credit_url: $('#'+id+'_credit_url').val()
};
});
If I console.log my photo_annotations object, this is what is produced, based on a two form example:
({11:{caption:"Caption for first photo.", keywords:"Keyword1,
Keyword2, Keyword3", credit:"Joe Bloggs",
credit_url:"www.a-domain.com"}, 12:{caption:"Caption for Lady Gaga.",
keywords:"Keyword3, Keyword4", credit:"John Doe",
credit_url:"www.another-domain.com"}})
I then need to POST this as a string/JSON to a PHP page, so I've done this:
$.ajax({
type: 'POST',
dataType: 'html',
url: 'ajax/save-annotations.php',
data: { data: JSON.stringify(photo_annotations) },
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data) {
$('#form_results').html(data);
} else {
alert("No data");
}
}
});
And on my PHP page, I've got this:
<?php
//print_r($_POST['data']);
$decoded = json_decode($_POST['data'],true);
print_r($decoded);
?>
Now, this isn't the only thing I've tried. I've tried to remove all the JSON settings from the AJAX script, in a bid to just send a pure string. I've tried removing contentType and JSON.stringify but still won't go. My PHP page just can't get the data that I'm sending.
Please help push me in the right direction. I've got to the point where I can't remember all the variations I've tried and this little script is now on day 2!
MANAGED TO FIX IT
I rewrote my AJAX function and it worked. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
Try:
$.ajax({
// ...
data: { data: JSON.stringify(photo_annotations) },
// ...
});
If you just set the "data" property to a string, then jQuery thinks you want to use it as the actual query string, and that clearly won't work when it's a blob of JSON. When you pass jQuery an object, as above, then it'll do the appropriate URL-encoding of the property names and values (your JSON blob) and create the query string for you. You should get a single "data" parameter at the server, and it's value will be the JSON string.
Try urldecode or rawurldecode as follows:
<?php
$decoded = json_decode(urldecode($_POST['data']), true);
print_r($decoded);
?>
I rewrote my AJAX function and it now works. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
The only thing I can think of is that the order of AJAX settings needed to be in a particular order. This is my old AJAX script which does not send POST data successfully - well it does send, but cannot be read!!
var the_obj = JSON.stringify(photo_annotations);
var data_str = "annotations="+the_obj;
$.ajax({
type: 'POST',
dataType: 'html',
data: data_str,
url: 'ajax/save-annotations.php',
success: function(data) {
$('#form_results').html(data);
}
});
in your ajax call try resetting the dataType to json
dataType: "json",
You wouldn't have to use the JSON.stringify() either. On your php script you won't have to decode [json_decode()] the data from the $_POST variable. The data will be easy readable by your php script.

Categories