Issue with decoding json array in php - javascript

Okay now i am having a weird issue here, sometime back i learned how to encode and decode a json array properly here on stackoverflow but now i am having a weird issue on my godaddy server that i cannot comprehend, maybe i may have made i typo or something somewhere in code but i honestly cannot tell what is wrong here. The code works okay on my localhost but not when i upload it too my godaddy server.
The code here is basically supposed to pass an id as a json to the php server which is then supposed to execute a query using the id as a parameter.
Here is the jquery code:
<script text="text/javascript">
$(document).ready(function() {
$('#download').click(function(e) {
// e.preventDefault();
var tid = $('#id').val().trim();
var data = {
ID:tid
};
$.ajax({
type: "POST",
url: "xxxxx-xxxxxxx.php",
data: {
data: JSON.stringify(data)
},
dataType: "json",
success: function(response) {
}
});
});
});
</script>
and this is the php code:
<?php
if (isset($_POST['data']))
{
$Data = $_POST["data"];
$arr = json_decode($Data);
$id = $arr->ID;
$sql = $pdo->prepare("update ********** set ******** = ******** + 1 where id=:id");
$sql->bindValue("id", $id, PDO::PARAM_INT);
$sql->execute();
unset($_POST['data']);
}
?>
Now i checked if the value was being sent to the server using my browser console and it was. I also checked if the $_POST['data'] on the server contained any data using var_dump and it did in fact have the data i wanted.

in the ajax set the content type to contentType: "application/json",
so:
$.ajax({
type: "POST",
url: "xxxxx-xxxxxxx.php",
data: {
data: JSON.stringify(data)
},
contentType: "application/json",
success: function(response) {
}
});
and in the php use:
$json = file_get_contents('php://input');
$data = json_decode($json);

Related

How to pass data from javascript to php in same page

I want to know how I can pass data from my script javascript to my php code to use the data into a query
I tried many things but it didn't work for me
So this is my script to upload files from input type: file then i get the url in downloadURL variable
var downloadURL;
...
uploadTask.on('state_changed',function(snapshot){
},function(error){
},function(){
downloadURL=uploadTask.snapshot.downloadURL;
alert(downloadURL);
});
Now I want to pass downloadURL to my php so I can use it .
I also tried Ajax to do this task but it didn't work or the code that I used is false
Ajax code :
$.ajax({
type: "POST",
url: '', //same page
data: downloadURL ,
success: function(data)
{
//alert(data);
}
});
EDIT
Php code :
<?php
$user=$_POST['downloadURL'];
echo $user;
?>
Just a normal echo to test if data is Posted or not
Structure the data of your $.ajax request in a name-value pair manner.
Change this:
$.ajax({
type: "POST",
url: '', //same page
data: downloadURL ,
success: function(data)
{
//alert(data);
}
});
To this:
$.ajax({
type: "POST",
data: {"downloadURL":downloadURL} ,
success: function(data)
{
//alert(data);
}
});
I also removed url from your $.ajax request because by default url is set to the current page.
With the above modifications, your PHP code will remain unchanged (e.g., $user=$_POST['downloadURL'];).
Okay change your php with that code:
if(isset($_POST['downloadURL']) {
$response = array(
'user' => $_POST['downloadURL']
);
echo json_decode($response);
exit;
}
Because you are making ajax request you must return json that why we parse our Array to json(object) and then in your javascript ajax request inside success function write
console.log(data);
And after data
...
data: downloadUrl,
Add this
dataType: 'json'
This mean we are telling on our ajax request that we are expecting json response

Jquery Ajax returns 400 BAD request

I'm trying to send data to my local DB server but I keep getting 400 Bad request error when I try to send it.
var studentEmail = "ali#gmail.com";
var dataString = '&questionNumber='+ temp + '&answer='+ value + '&email='+ studentEmail;
$.ajax({
type: "POST",
dataType:'json',
url: "js/dbcon.php",
data: JSON.stringify(dataString),
processData: false,
contentType: "application/json; charset=utf-8"
});
and this is the php file
<?php
$connection = mysql_connect("127.0.0.1", "root", "root"); // Establishing Connection with Server..
$db = mysql_select_db("db", $connection); // Selecting Database
//Fetching Values from URL
$questionNumber=$_POST['questionNumber'];
$answer=$_POST['answer'];
$email=$_POST['email'];
//Insert query
$query = mysql_query("INSERT INTO answers (questionNumber,studentAnswer,studentEmail) VALUES ($questionNumber,$answer,$email)");
echo "succesfully posted";
mysql_close($connection); // Connection Closed
?>
can anyone see what I'm doing wrong?
Thanks in advance!
JSON.stringify() method is used to turn a javascript object into json string.
So dataString variable must be a javascript object:
var data ={questionNumber:temp ,answer: value ,email:studentEmail};
AJAX
$.ajax({
type: "POST",
dataType:'json',
url: "js/dbcon.php",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=utf-8"
});
if you change the post to get you have to replace $_POST with $_GET into your php file.
There is an easier way to pass data that will work correctly for both POST and GET requests
var studentEmail = "ali#gmail.com";
$.ajax({
type: "POST",
dataType:'json',
url: "js/dbcon.php",
data: {questionNumber:temp, answer:value, email: studentEmail},
processData: false,
});
Now jQuery does all the hard work and converts the object full of data to whatever format is required for a POST or GET request
You can send the ajax request this way:
var studentEmail = "ali#gmail.com";
$.ajax({
type: "POST",
dataType:'json',
url: "js/dbcon.php",
data: ({'questionNumber':temp,'answer':value, 'email':studentEmail }),
processData: false,
contentType: "application/json; charset=utf-8"
});
Also the PHP file needs to return a json string as well.
echo "succesfully posted";
is no valid json answer.
Return something like this:
$arr = array('success' => true, 'answer' => "succesfully posted");
echo json_encode($arr);
See also here: http://php.net/manual/de/function.json-encode.php
You should validate the input data, before inserting into the database.

JS array send to php is returning as empty [duplicate]

Im submitting Data to a php file via AJAX using POST.
It worked fine with just submitting strings, but now I wanted to submit my JS Object with JSON and decode it on PHP side.
In the console I can see, that my data is submitted correctly but on PHP side json_decode returns NULL.
I've tried the following:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(this),
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['data'];
echo json_decode($_POST['data']);
echo var_dump(json_decode($_POST['data']));
And:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: {'Absence' : JSON.stringify(this)},
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['Absence'];
echo json_decode($_POST['Absence']);
echo var_dump(json_decode($_POST['Absence']));
The alert was just to check everything is alright...
And yea usual string were echoed correctly :-)
Where you went wrong in your code in the first code is that you must have used this:
var_dump(json_decode(file_get_contents("php://input"))); //and not $_POST['data']
Quoting from PHP Manual
php://input is a read-only stream that allows you to read raw data from the request body.
Since in your case, you are submitting a JSON in the body, you have to read it from this stream. Usual method of $_POST['field_name'] wont work, because the post body is not in an URLencoded format.
In the second part, you must have used this:
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify({'Absence' : JSON.stringify(this)}),
UPDATE:
When request has a content type application/json, PHP wont parse the request and give you the JSON object in $_POST, you must parse it yourself from the raw HTTP body. The JSON string is retrieved using file_get_contents("php://input");.
If you must get that using $_POSTyou would make it:
data: {"data":JSON.stringify({'Absence' : JSON.stringify(this)})},
And then in PHP do:
$json = json_decode($_POST['data']);
Single quotes are not valid for php's json_encode, use the double quotes for both field names and values.
To me, it looks like you should reformat your AJAX object. The url-property should only be the URL for the target php-file and any data that needs to be posted should be in the form of a query-string in the data-property.
The following should work as you expected:
this.getAbsence = function() {
var strJSONData = JSON.stringify(this);
alert(strJSONData);
jQuery.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'ajax/selectSingle.php',
data: 'm=getAbsence&Absence=' + strJSONData,
success: function(data) {
alert(data);
}
});
}
try this
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(vThis),
success : function(data){
alert(data);
}
});
}
EDIT
I think we can also do this!
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
dataType: "json",
url: "ajax/selectSingle.php?m=getAbsence",
data: vThis,
success : function(data){
alert(data);
}
});
}
and in PHP
print_r($_POST);
On PHP side try this:
$sectionValue = htmlspecialchars($_POST['sectionValue'], ENT_QUOTES);
$dataToWrite = json_decode(html_entity_decode($sectionValue, ENT_QUOTES, "utf-8" ), true);

Sending Multidimentional array data, with ajax, to a php script

I have two simple scripts. One client-side jquery that has multidim array & a server-side php script. in php $data stays empty.
jquery
console.log("IN JQUERY");
console.log(inps);
$.ajax({
type: 'post',
cache: false,
url: './gen.php',
data: inps,
success: function(response){
console.log("RESPONSE");
console.log(response);
}
});
gen.php
<?php
$data = file_get_contents('php://input');
$data = json_decode($data, true);
print_r($data);
?>
firefox console output
>POST ..././gen.php [HTTP/1.1 200 OK 1ms]
>"IN JQUERY"
>{isbranch: "1", ismanager: "0", isdept: "1"}
>"RESPONSE"
>""
Is there a way to send Multi Dimensional array to the php with ajax without spliting array?
You should use JSON.stringify to encode your data before send it, also better to add correct contentType to it:
$.ajax({
type: 'post',
cache: false,
url: '/gen.php',
data: JSON.stringify(inps),
contentType: 'application/json',
success: function(response){
console.log("RESPONSE");
console.log(response);
}
});
The key-value pairs should already exist in your $_POST
$isbranch = $_POST['isbranch'];
$ismanager = $_POST['ismanager'];
$isdept = $_POST['isdept'];

Passing an array from PHP to Javascript using JQuery & JSON

I've got a game which refreshes info every 10 seconds from a MySQL database. There will be a JS function which is called each time this happens. I can't get the success function to execute, and I have no idea why. No errors on the console, either.
Javascript:
function refreshStats() {
console.log("number 1");
$.ajax({
url: "refreshData.php",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType : 'json',
data: { },
cache: false,
async: true,
success: function (msg) {
if(msg){
console.log("number 2");
var arr = JSON.parse(msg);
document.getElementById("interface_stats").innerHTML =
"Fatigue: " + arr[0];
}
}
});
}
PHP:
<?php
$username = $_POST['user'];
ini_set('display_errors', 1);
error_reporting(E_ALL);
$con = mysql_connect("localhost","redacted","redacted");
if (!$con)
{
die('SQL error! Aborting: ' . mysql_error($con));
}
$db = mysql_select_db("aftertheend",$con) or die("Database error! Aborting. Inform the admin.");
$query = "SELECT fatigue, food, water, radiation, condition FROM users WHERE username='TheMightyThor'";
$result = mysql_query($query, $con);
$data = mysql_fetch_row($result);
$stats = [
"fatigue" => $data[0],
"food" => $data[1],
"water" => $data[2],
"radiation" => $data[3],
"condition" => $data[4]
];
echo json_encode($stats);
?>
I think your PHP is returning an error, rather than the JSON you are expecting. Since you have dataType: 'json', jQuery attempts to parse the response, but fails. When that happens, jQuery does not call the success callback.
If you can, use Firebug to see what is being returned by the ajax call. Another way would be to temporarily change to dataType: 'html' and then change your success callback to:
success: function(msg) { alert(msg); }
Hopefully when you see the message being returned, it will help identify the problem. One thing you should do though, is add code to handle the cases where the query fails to execute and where no row is fetched from the database. You could add the following code to the PHP file:
$result = mysql_query($query, $con);
if (!$result) {
die('Could not run query: ' . mysql_error($con));
}
if (mysql_num_rows($result) < 1) {
echo 'null';
exit;
}
$data = mysql_fetch_row($result);
There are also a few issues with the Ajax call though:
(1) You are specifying contentType: "application/json; charset=utf-8", but then you are not sending JSON. You should do something like this:
data: JSON.stringify({}),
But if you do this, you cannot get the data on the server using the $_POST function. Therefore, you might want to get rid of the contentType setting instead. See this SO answer for more information.
(2) When you specify dataType: 'json', JQuery will parse the response to an object before calling the success callback, so the msg parameter should already be an object. Therefore, you should not call JSON.parse(msg).
(3) You are returning an associative array from the PHP file. That will be converted to a JavaScript object, not an array.
I think you should try the following:
$.ajax('refreshData.php', {
type: 'post',
dataType: 'json',
data: { },
cache: false,
success: function (data) {
if (data) {
$('#interface_stats').html('Fatigue: ' + data.fatigue);
}
}
});

Categories

Resources