Unable to pass value to php POST via javascript - javascript

I am trying to update the text from textbox to database using the onclick event and calling a javascript function.
This is the javascript code
function send_post()
{
var hr = new XMLHttpRequest();
var url ="send_post.php";
var fn = document.getElementById("post").value;
var vars = "post="+fn;
hr.open("POST",url,true);
hr.setRequestHeader("Content-type","application/x-www-form-urlencode");
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status ==200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("status").innerHTML = fn;
}
This is the php file code
<?php include 'inc/connect.inc.php';
$post =#$_POST['post'];
if ($post != "") {
$date_added = date("Y-m-d");
$added_by = "test123";
$user_posted_to = "test123";
$sqlCommand = "INSERT INTO posts VALUES('','$post','$date_added','$added_by','$user_posted_to')";
$query = mysql_query($sqlCommand) or die (mysql_error());
}
else{
echo "Write something to post.";
}
?>
But I get this error from the php :
Undefined index: post on line 3

The MIME type you are trying to use is application/x-www-form-urlencoded (with a d on the end).
PHP doesn't know how to parse data encoded as application/x-www-form-urlencode (without the d) so it doesn't populate $_POST for your code.

Javascript part:
<script>
function getXMLObject(){
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e2) {
xmlHttp = false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}
var xmlhttp = new getXMLObject();
function send_post() {
if(xmlhttp) {
var post = document.getElementById("post").value;
xmlhttp.open("POST","send_post.php",true);
xmlhttp.onreadystatechange = resultPost;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("post=" + post);
}
}
function resultPost() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
}
</script>
PHP part:
<?php
include 'inc/connect.inc.php';
if(isset($_POST['post']) && trim($_POST['post']) != '') $post = mysql_real_escape_string(trim($_POST['post']));
else $post = '';
if ($post != '') {
$date_added = date("Y-m-d");
$added_by = "test123";
$user_posted_to = "test123";
$sqlCommand = "INSERT INTO posts VALUES('','$post','$date_added','$added_by','$user_posted_to')";
$query = mysql_query($sqlCommand);
if(mysql_affected_rows($link) == 1){
echo 'Operation successfully executed';
exit;
}
}
echo 'Write something to post.';
?>

Related

Json decode from Javascript to php to Javascript

I am trying to get the value from json.stringfy sent to PHP file, for some reason php file is not receiving the key. If I manually add the key it is working fine. What could be wrong here:
My php file:
$request = json_decode(file_get_contents('php://input'), true);
$getID = $request['docid'];
$query = mysqli_query($con, "SELECT * FROM user_details WHERE id = $getID'");
if(mysqli_num_rows($query) > 0)
{
$response["details"] = array();
while ($row = mysqli_fetch_array ($query))
{
// temp user array
$detail = array();
$detail["docname"] = $row["docname"];
$detail["textresults"] = $row["textresults"];
array_push($response["details"], $detail);
}
echo json_encode($response);
$response["success"] = 1;
}
else
{
$response["success"] = 0;
echo json_encode($response);
}
This is my javascript file:
function loadData() {
var docid = window.localStorage.getItem('myKey');
console.log("Docid " + docid);
var xhr = new XMLHttpRequest();
var url = "./api/getData.php";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json);
}
};
var data = JSON.stringify({'docid': docid});
xhr.send(data);
}

XMLHttpRequest().send(value) sending blank values

XMLTHttpRequest.send() is sending blank values to PHP file. I been trying to debug this but had no luck.
What could be going wrong?
I done a php echo testing below, and im always getting value test2 with nothing else.
AJAX
function subCatActivation(i) {
// var selectedBox = document.getElementById("Cat" + i);
var val = "test";
var hr = new XMLHttpRequest();
var url = "parse_receive_select.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlendcoded");
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
//document.getElementById("sub_cat").innerHTML = return_data;
alert(return_data);
}
}
hr.send("v="+val);
}
PHP
if(isset($_POST['v'])){
echo ($_POST['v']. " test1");
}else if($_POST['v'] == ''){
echo ($_POST['v'] . " test2");
}else{
echo ($_POST['v'] . " test3");
}
You have a simple typo:
hr.setRequestHeader("Content-type", "application/x-www-form-urlendcoded");
urlendcoded should be urlencoded.

Value not found in php

For login i'm passing mail id and password from javascript file and i've checked through console.log that the values are printed. But when i echo both values in php only password is showed not the mail. But i can't find any error.Here i'm pasting the php file.
<?php
require_once('DBconnection.php');
ini_set('display_errors', 1);
ini_set('log_errors', 1);
$datamail = $_GET["mailID"];
$datapass = $_GET["psw"];
//$datamail = isset($_GET["mailID"]) ? $_GET["mailID"] : '';
echo $datamail;
echo $datapass;
$login_query = "SELECT * FROM student_table where mail_id = '$datamail' AND password='$datapass'";
//echo $login_query;
$login_res = $db->query($login_query);
if( $login_res->num_rows == 1 ){
//if( $login_res == true ){
echo "success";
}
else {
//echo $login_res;
echo mysqli_error($db);
exit;
}
$db->close();
?>
Javascrit file Here
function globalLogin() {
checkLogInMail();
//pageEntry();
}
function checkLogInMail() {
var mailET = document.getElementById("mailID");
var mailIdError = document.getElementById("mailIdErr");
mailID = mailET.value;
var regex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
if (!regex.test(mailID)) {
mailIdError.innerHTML = "Enter a valid Email id";
//loginFlag = 1;
}
else{
checkmailPass();
}
}
function checkmailPass() {
var passET = document.getElementById("psw");
var passError = document.getElementById("pswErr");
psw = passET.value;
console.log(mailID);
console.log(psw);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
console.log(this.readyState);
if(this.readyState == 4 && this.status == 200)
{
console.log(this.status);
var response = xhttp.responseText;
alert(response);
if(!response.localeCompare( "success" )){
document.getElementById("loginErr").innerHTML = "Mail or Password is correct";
//alert("Successfully logged in :)");
//window.location.href = "index.html";
}
else{
document.getElementById("loginErr").innerHTML = response;
}
}
}
xhttp.open("GET", "passwordChecker.php?psw="+psw+"&mailID"+mailID, true);
xhttp.send();
}
you miss = in your get request in mailID
xhttp.open("GET", "passwordChecker.php?psw="+psw+"&mailID="+mailID, true);
You missed an equal sign '=' in your javascript at your mailid parameter.

Run Javascript script from ajax response

I want to call a JS Script in Ajax response. What it does is pass the document.getElementById script to the Ajax responseText.
The current code returns me this error: Uncaught TypeError: Cannot set property 'innerHTML' of null
This is done with Visual Studio Cordova..
Ajax:
$("#loginBtn").click(function() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.write(this.responseText);
}
}
xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);
});
PHP:
if($count == 1){
echo "document.getElementById('alertBox').innerHTML = 'Login Success!';
document.getElementById('alertBox').className = 'alert alert-success';
document.getElementById('alertBox').style.display = 'block';
setTimeout(function () {
window.location.href = '../html/dashboard.html';
}, 1000);
";
}else{
echo "document.getElementById('alertBox').innerHTML = 'Invalid login details';
document.getElementById('alertBox').className = 'alert alert-danger';
document.getElementById('alertBox').style.display = 'block';
";
}
You can solve it by a small change, you just have to write JS code in the AJAX success that you wrote in your PHP page. In the PHP page, there is no alertBox element, that's why the error occurred.
Your JS code will be like this:
$("#loginBtn").click(function() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
if(this.responseText=="success"){
document.getElementById('alertBox').innerHTML = 'Login Success!';
document.getElementById('alertBox').className = 'alert alert-success';
document.getElementById('alertBox').style.display = 'block';
setTimeout(function () {
window.location.href = '../html/dashboard.html';
}, 1000);
}elseif(this.responseText=="error"){
document.getElementById('alertBox').innerHTML = 'Invalid login details';
document.getElementById('alertBox').className = 'alert alert-danger';
document.getElementById('alertBox').style.display = 'block'
}
}
}
xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);
});
And PHP code like:
if($count == 1){
echo "success";
}else{
echo "error";
}
Basically you get that error because the thing you're trying to change is not on the page when you look for it.
What you need to do is, do not write javascript with PHP. You return something like an int from php and then use that to decide what the javascript does.
You have the html on the page and just change the content inside it.
$("#loginBtn").click(function() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var str = this.responseText; //you may need to trim whitespace
var alert = document.getElementById('alertBox');
if (str.trim() == 1) {
alert.innerHTML = 'Login Success!';
alert.className = 'alert alert-success';
alert.style.display = 'block';
setTimeout(function() {
window.location.href = '../html/dashboard.html';
}, 1000);
}
else {
alert.innerHTML = 'Invalid login details';
alert.className = 'alert alert-danger';
alert.style.display = 'block';
}
}
xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);
});
<div id="alertbox"></div>
PHP Code:
if($count == 1){
echo 1;
}
else{
echo 0;
}
Use eval like below
$("#loginBtn").click(function() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var fun = eval(this.responseText);
}
}
xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);
});

How to get data from PHP in JSON and AJAX?

Hey guys I am fetching some data with PHP with is listing the folders and Inside the folders I have some images. But I am willing to know how can I get that data in JSON with AJAX to get the name of folders in a DropDown.
This is the code that I am using
JS
<html>
<head>
<script type="text/javascript">
function getXmlHttp(){
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function readDir(dirName) {
var req = getXmlHttp();
var list = document.getElementById('subDir');
req.onreadystatechange = function() {
if (req.readyState == 4) {
if(req.status == 200) {
list.innerHTML = req.responseText;
}
}
}
req.open('GET', 'getList.php?data=' + dirName, true);
req.send(null);
list.innerHTML = 'loading...';
}
</script>
</head>
<body onload="readDir('');">
<div id="subDir">
</div>
</body>
</html>
PHP
<?php
$dir = "./data/";
if (strlen($_GET['data']) > 0){$dir = $_GET['data'];}
getList($dir);
function getList($name) {
$path = realpath($name);
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CATCH_GET_CHILD);
foreach($objects as $name => $object){
if (filetype($name) == "dir") {
print "<br/><a href='javascript:void' onClick='readDir(\"" . $path . "/" . basename($name) . "\")'><b>" . basename($name) . "</b></a>";
} else {
print "<br/><a><b>" . basename($name) . "</b></a>";
}
}
}
?>
Here you can see the code how is working: http://tdhdemo.com/phpfetch/
I'm not sure I get your question right but you can add your list to an array in PHP and display it using json_encode.
When receiving data from the ajax call, use JSON.parse to make it easily readable.
You can also separate files and folders if you want to use them in the future.
<?php
$dir = "./data/";
if (strlen($_GET['data']) > 0){$dir = $_GET['data'];}
echo json_encode(getList($dir));
function getList($name) {
$path = realpath($name);
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CATCH_GET_CHILD);
$folderContent = array("directories" => array(), "files" => array());
foreach($objects as $name => $object){
if (filetype($name) == "dir") {
array_push($folderContent["directories"], basename($name));
} else {
array_push($folderContent["files"], basename($name));
}
}
return $folderContent;
}
?>
Javascript :
function readDir(dirName) {
var req = getXmlHttp();
var list = document.getElementById('subDir');
req.onreadystatechange = function() {
if (req.readyState == 4) {
if(req.status == 200) {
contentList = JSON.parse(req.responseText);
for(i in contentList["directories"]){
list.innerHTML = list.innerHTML + contentList["directories"][i];
}
}
}
}
req.open('GET', 'getList.php?data=' + dirName, true);
req.send(null);
list.innerHTML = 'loading...';
}

Categories

Resources