Undefined _POST variable when using XMLHttpRequest() - javascript

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");

Related

json_decode $_POST not receiving Javascript JSON

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);

works in all browser except Firefox

Tried everything. It works on Chrome, Vuze and Opera. But not on FirefoxThe code for the PHP file is this:
$sql= "SELECT * FROM `tarotAntwoord` WHERE `kaart` = '".$kaart."'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
$kaarter = utf8_encode ($row['kaart']);
echo $kaarter;
$test ="this is a test";
echo $test;
I use this echo, for an ajax response in a modal.
The modal outputs
this is a test
But it doesn't output the value $kaarter I got from the database.
It works in every browser except Firefox. (And it didn't work in chrome at my girlfriend).
Do I have to use an operator on the string from mysql or something? The Ajax script works, because it displays the test variable. I've tried with and without the utf8 encode.
This is the client side. No error in chrome debugging (f12)
function hedenFunction(){
var verleden = document.getElementById("tarot2").src;
// document.getElementById("verledenAntwoord").innerHTML = "hoi dit is een modal test";
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) {
document.getElementById("hedenAntwoord").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","tarotantwoord.php?q="+verleden,true);
xmlhttp.send();
}

Data not getting passed via Ajax to PHP script

I'm trying to send the value of a variable number via ajax to a PHP script. But the PHP script is not printing the desired output on opening on a browser. Tried but couldn't find whats wrong here.
Any pointers ?
index.html
<button type="submit" class="btn btn-success" id = 'first' onclick='process();'>Submit</button>
<script>
var number = 0;
function process()
{
number++;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "num=" + number;
xhr.open("POST", "index.php", true);
xhr.send(data);
}
</script>
index.php
<?php
session_start();
$number = $_POST['num'];
$_SESSION['numb'] = $number;
echo $_SESSION['numb'] ;
?>
Editing my long winded lame answer since you fixed the close curly bracket... but bloodyKnuckles is right you also need something in your 'process' function to take the response from your PHP page and output it... or whatever you want to do. You can basically use the method 'onreadystatechange' in the XMLHttpRequest object and then look for a 'readyState' property value of 4 which means everything is done. Here is a simple example of that just outputting the results to the console (which you can view using developer tools in your browser of choice).
<script>
var number = 0;
function process()
{
number++;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "num=" + number;
xhr.onreadystatechange = function(){
if (xhr.readyState==4 && xhr.status==200){
console.log('xhr.readyState=',xhr.readyState);
console.log('xhr.status=',xhr.status);
console.log('response=',xhr.responseText);
}
else if (xhr.readyState == 1 ){
xhr.send(data)
}
};
xhr.open("POST", "ajax-test.php", true);
}
</script>
As you go further you may want to update your PHP page to only update the session when the POST value is there.
<?php
//ini_set('display_errors',1);
//ini_set('display_startup_errors',1);
//error_reporting(-1);
if(isset($_POST['num'])){
session_start();
$_SESSION['numb'] = $_POST['num'];
echo $_SESSION['numb'];
}
?>
You can uncomment those ini_set and error_reporting lines to try to figure out what is going on with your PHP script.
This is because you are not sending header information with request...
Append this code
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", data.length);
xhr.setRequestHeader("Connection", "close");
after
xhr.open("POST", "index.php", true);

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");

sending data to php with ajax.send

Can someone help me with sending this data to a .php page where I could receive it on my PHP page
javascript:
postToSql(){
var ajax;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
ajax=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
ajax=new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && ajax.status==200)
{
alert(ajax.responseText); //receiving response
}
};
var name = $("#entry_1274804157").val();
//alert(name);
var company= $("#entry_1828184698").val();
var phone=$("#entry_2039177352").val();
var email=$("#entry_1545475878").val();
var comments=$("#entry_1846523632").val();
var params = {
"name":name,
"company":company,
"phone":phone,
"email":email,
"comments": comments
};
//var jsonText = JSON.stringify(params);
ajax.open("POST", "view/templates/includes/insertgoogle.php", false);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send("totalJsonStr="+params);
//alert(totalJsonStr);
// alert(params);
return true;
}
</script>
HTML:
<form action="https://docs.google.com/asgsasdfasg/formResponse" method="POST" id="" target="_self" onsubmit="return postToSql();">
EDIT:
This is how I am receiving it:
if(isset($_POST['totalJsonStr']))
{
$jsonVal = json_decode($_POST['totalJsonStr']);
$jsonVal2 = json_decode($jsonVal);
var_dump($_POST['totalJsonStr']);
var_dump($jsonVal);
var_dump($jsonVal2);
$name = $jsonVal2->{'name'};
$company= $jsonVal2->{'name'};
$phone= $jsonVal2->{'name'};
$email= $jsonVal2->{'name'};
$comments= $jsonVal2->{'name'};
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
mysql_query("INSERT INTO `testgoogle` ( Name, Company, Phone, Email, Comments )
VALUES ('$name','$company', '$phone', '$email', '$comments')");
Print "Your information has been successfully added to the database.";
return;
}
else
{
die("No Data Found");
}
Where do you create the "ajax" object?
var ajax;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
ajax=new XMLHttpRequest();
}
else
{// code for IE6, IE5
ajax=new ActiveXObject("Microsoft.XMLHTTP");
}
from here: http://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asp
If you want to use $_GET then,
Remove:
ajax.open("POST", "view/templates/includes/insertgoogle.php", true);
Add:
ajax.open("GET", "view/templates/includes/insertgoogle.php", true);
Helpful link: http://www.degraeve.com/reference/simple-ajax-example.php
Using POST Method,
The perfect solution would be, store all values in an array and send the array as a json request using json.stringify().
In php, Use json_decode() to decode your json string.
UPDATE
Add this to your javascript,
<script type="text/javascript">
function postToSql(){
var ajax;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
ajax=new XMLHttpRequest();
}
else
{// code for IE6, IE5
ajax=new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && ajax.status==200)
{
alert(ajax.responseText); //receiving response
}
}
var name = "1234";
var company= "1234";
var phone="1234";
var params = {
"name":name,
"company":company,
"phone":phone,
};
var jsonText = JSON.stringify(params);
ajax.open("POST", "view/templates/includes/insertgoogle.php", true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send("totalJsonStr="+jsonText);
}
</script>
<form action="https://docs.google.com/asgsasdfasg/formResponse" method="POST" id="" target="_self" onsubmit="postToSql();return false;">
Add this to php
<?php
if(isset($_POST["totalJsonStr"]))
{
$jsonVal = json_decode($_POST["totalJsonStr"]);
print $jsonVal->{'name'};
print $jsonVal->{'company'};
print $jsonVal->{'phone'};
}
else
{
die("No Data Found");
}
?>
since nothing was working for me, I finally used jquery ajax which worked.

Categories

Resources