json_decode $_POST not receiving Javascript JSON - javascript

I'm trying to send json formatted values to php but $_POST on php returns null when i call the function. This procedure is similar to w3schools php json example found here https://www.w3schools.com/js/js_json_php.asp at the bottom but still don't get the same result. The values next to the strings in json are variables with values in it. Here's what i've done:
var args = {'name': name, 'birthday': birthday, 'policy': policy, 'cl': cl, 'claim': claim, 'incoming': incoming, 'theDate': theDate,
'xora': xora, 'treatment': treat, 'session': sess, 'inpat': inpat, 'outpat': outpat, 'daycase': daycase,
'radioBtn': radioBtn, 'admDate': admDate, 'invDate': invDate, 'invNum': invNum, "nomisma": nomisma,
'provSelect': provSelect, 'specSel1': specSelect1, 'prescSel': prescSelect, 'specSel2': specSelect2, 'amount': amount,
'deduct': deduct, 'dedColl': dedColl, 'copay': copay, 'copayColl': copayColl, 'totalAm': totalAm, 'comms': comms,
'diagnosiDesc': diagnosiDesc, 'diagnosiCode': diagnosiCode, 'nonAmount': nonAmount, 'reason': reason, 'categs': category };
var json = JSON.stringify(args);
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
//alert("Saved and Continue");
window.open("PHP/SaveAndCont.php?q="+json); // Test
}
};
xmlhttp.open("POST","PHP/SaveAndCont.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("q="+json);
And here is my php file:
include('Connection.php');
header("Content-Type: application/json; charset=UTF-8");
$parse = $_POST['q']; // undefined index q
$obj = json_decode($parse, false);
var_dump($parse, $obj); // NULL

Set the content type header to application/json.
In PHP with raw request you won't have variables filled in $_POST but instead you need to get json via raw request to get it:
Check if the request type is post if not exit
PHP
<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
die("wrong type of request");
}
// get raw json post object and decode it
$json = json_decode(file_get_contents("php://input"));
var_dump($jsonString);
JS:
var args = {'name': name, 'birthday': birthday, 'policy': policy, 'cl': cl, 'claim': claim, 'incoming': incoming, 'theDate': theDate,
'xora': xora, 'treatment': treat, 'session': sess, 'inpat': inpat, 'outpat': outpat, 'daycase': daycase,
'radioBtn': radioBtn, 'admDate': admDate, 'invDate': invDate, 'invNum': invNum, "nomisma": nomisma,
'provSelect': provSelect, 'specSel1': specSelect1, 'prescSel': prescSelect, 'specSel2': specSelect2, 'amount': amount,
'deduct': deduct, 'dedColl': dedColl, 'copay': copay, 'copayColl': copayColl, 'totalAm': totalAm, 'comms': comms,
'diagnosiDesc': diagnosiDesc, 'diagnosiCode': diagnosiCode, 'nonAmount': nonAmount, 'reason': reason, 'categs': category };
var json = JSON.stringify(args);
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
//alert("Saved and Continue");
alert(xmlhtml.responseText); // this should print the response
} else if(this.status !== 200) {
alert(this.status); // maybe it'll be 404 or 500 if so then correct the url in xmlhttp.open it depends on your server configuration but it needs to be accessed via http://localhost/ or host defined by you
}
};
xmlhttp.open("POST","php/saveandcont.php", true); // this should be path that can be opened via browser
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send(json);

Both $parse and $obj NULL variables means that $_POST['q'] is not defined.
I think the problem in this string:
xmlhttp.open("POST","PHP/SaveAndCont.php",true);
The second argument is an URL: https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp
But you set it as a path to a file.
Try to replace it to
xmlhttp.open("POST","SaveAndCont.php",true);
or
xmlhttp.open("POST","http://fullserverurl/SaveAndCont.php",true);

Related

'Cross Origin' error message resulting from local XmlHttpRequest

I am using AJAX to display upcoming events on a website. To that end, I call a JavaScript function via onload="showEvents(3);", see the function below:
function showEvents (amount) {
// are there Events?
if (document.getElementById("eventsDiv")) {
document.getElementsByClassName("info")[0].innerHTML = 'Loading events...';
// initialize XML Http Request
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("eventsDiv").innerHTML = xmlhttp.responseText;
}
}
// send request
xmlhttp.open("GET", "./events.php?number=" + encodeURIComponent(amount), true);
xmlhttp.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
xmlhttp.send();
}
}
The file events.php is a PHP file in the same directory, and it connects to the database to fetch the upcoming events. The HTML header of the main website includes
<base href="http://www.my-domain.com/">
The problem: I get a "Cross Orign" error message (in Firefox), preventing my parent index.html file accessing the events.php. As I understand, this error message should not appear since I am using a resource from the same directory.
Ok that's ok, you also can do like this...
if($_SERVER['HTTP_ORIGIN'] == "http://your-domain.com") {
header('Access-Control-Allow-Origin: http://your-domain.com');

Undefined _POST variable when using XMLHttpRequest()

I am trying to use Ajax to insert data into database with POST method. But php can not recognize the post variables.
ajax:
function createUser() {
var _id=document.getElementById('new_id').value;
var _name=document.getElementById('new_name').value;
var params = "id="+_id+"&name="+_name;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
console.log(xmlhttp);
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if(xmlhttp.responseText=="")
alert("New User is created!");
else
document.body.innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("POST","resource/create_profile.php",true);
xmlhttp.send(params);
}
php:
<?php
$id = $_POST["id"];
$name = $_POST["name"];
$conn = oci_connect(....);
$query = "....";
$result = oci_parse($conn, $query);
oci_execute($result);
oci_close($conn);
?>
if i uncomment the request header content type then nothing happens, no error is shown. if i comment it then php shows error. i am giving a screenshot.
http://imgur.com/CdKO84V
what am i supposed to do? if i use get method then it is working good but i can not use it since i need to upload file.
At last I have found the solution! I had to add the setRequestHeader() method below the open method. So in the end the code looks like:
xmlhttp.open("POST","resource/create_profile.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

How to send a string to php with POST [duplicate]

This question already has answers here:
Send POST data using XMLHttpRequest
(13 answers)
Closed 8 years ago.
I'm sending a string via xmlhttp in javascript using the following code:
function SendPHP(str, callback) {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(xmlhttp.responseText); //invoke the callback
}
}
xmlhttp.open("GET", "testpost.php?q=" + encodeURIComponent(str), true);
xmlhttp.send();
}
and some test php:
$q = $_GET['q'];
echo $q;
That worked fine until I started sending a larger string in which case I get the "HTTP/1.1 414 Request-URI Too Long" error.
After a bit of research I found out I need to use "POST" instead. So I changed it to:
xmlhttp.open("POST", "sendmail.php?q=" + str, true);
And:
$q = $_POST['q'];
echo $q;
But this does not echo anything when using POST. How can I fix it so it works like when I was using GET but so it can handle a large string of data?
edit I'm now trying it with:
function testNewPHP(str){
xmlhttp = new XMLHttpRequest();
str = "q=" + encodeURIComponent(str);
alert (str);
xmlhttp.open("POST","testpost.php", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
alert (xmlhttp.responseText);
}
}
};
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(str);
}
You should not provide your href with URL parameters, instead of this you should send() them. For addition, you should always encode your parameters with encodeURIComponent() (At least when your request is using the Content-type "application/x-www-form-urlencoded").
your javascript function :
function testNewPHP(){
var str = "This is test";
xmlhttp = new XMLHttpRequest();
str = "q=" + encodeURIComponent(str);
alert (str);
xmlhttp.open("POST","testpost.php", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
alert (xmlhttp.responseText);
}
}
};
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(str);
}
javascript :
function testNewPHP(){
var str = "This is test";
xmlhttp = new XMLHttpRequest();
str = "q=" + encodeURIComponent(str);
alert (str);
xmlhttp.open("POST","testpost.php", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
alert (xmlhttp.responseText);
}
}
};
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(str);
}
testpost.php in your home directory :
<?php
var_dump($_POST);
OUTPUT :
array(1) {
["q"]=>
string(12) "This is test"
}

How to make Ajax send JSON to PHP script

I am working on a webpage that needs to store data on the server in a .json file.
Here is what I have tried so far:
Javascript code:
// variable j = our json
var j;
function loadDoc(){
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
j = xmlhttp.responseText;
}
}
xmlhttp.open("GET","things.json",true);
xmlhttp.send();
}
loadDoc();
function rewrite(){
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
};
};
xhr.open("POST", "write.php", true);
xhr.send("data=" + j);
};
The PHP file:
<?php
$data = $_POST['data'];
file_put_contents('things.json', $data);
?>
Note, in other parts of my code the j variable is changed.
My problem is that after the PHP script is making the JSON file blank. Am I doing anything wrong? Is php receiving the JSON properly? If so, how can I fix that?
Cheers!
If you vote down, please tell me why.
To POST data like an HTML form, add an HTTP header with setRequestHeader(). (w3school page)
so it must be :
xmlhttp.setRequestHeader("Content-type","application/json");

Javascript does not return servlet response

I have wriiten welcome screen which basically use below javascript to call creditCheck servlet. Within servlet, there is method which will check the username and password. Servlet returns value properly. alert is not getting generated after servlet excutation within javascript.
however if execute simple servlet ( not doing anything, just printing variables), it will generate alert.
below is my javascript within JSp file:
############################################
<script type="text/javascript">
function getXmlHttpRequestObject(){
var xmlHttp = false;
if (window.XMLHttpRequest){
return new XMLHttpRequest(); //To support the browsers IE7+, Firefox, Chrome, Opera, Safari
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP"); // For the browsers IE6, IE5
}
else {
alert("Error due to old verion of browser upgrade your browser");
}
}
var xmlhttp = new getXmlHttpRequestObject(); //xmlhttp holds the ajax object
function servletPost() {
if(xmlhttp) {
var username = document.getElementById("uname");
var password = document.getElementById("pass");
xmlhttp.open("POST","CredCheck",true);
xmlhttp.onreadystatechange = handleServletPost;
req.onreadystatechange = callback;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("uname=" + username.value + "&pass=" + password.value );
}
}
function handleServletPost() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
else {
alert("Ajax calling error");
}
}
}
</script>
#
I have changed xmlhttp.open("POST","CredCheck",true); to
xmlhttp.open("POST","CredCheck",false);
xmlhttp.onreadystatechange = handleServletPost;

Categories

Resources