XMLHttpRequest().send(value) sending blank values - javascript

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.

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

How can Variable and that value move freely in the cycle of PHP->HTML->JS->PHP

I am adding the comments input box of every XML-RSS article.
When I select a RSS url, that results are commonly as below
PHP code
for ($i=0; $i<=19; $i++) {
$item_title=$x->item($i)->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$item_link=$x->item($i)->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$item_desc=$x->item($i)->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
$item_date=$x->item($i)->getElementsByTagName('pubDate')
->item(0)->childNodes->item(0)->nodeValue;
echo ("<p><a href='" . $item_link
. "' target=\'_blank\'>" . $item_title . "</a>");
echo ("<br>");
echo ($item_desc . "<br>".$item_date."</p>");
$item_link1 = str_replace('http://','',$item_link);
$item_link2 = str_replace('https://','',$item_link1);
$item_link3 = str_replace('/','-',$item_link2);
$item_link4 = str_replace('?','-',$item_link3);
$content = $item_title."--". $item_link."--".$item_desc."--".$item_date;
file_put_contents("./comments/".$item_link4.".txt",$content);
//Next line is something wrong or not??
echo "<option id=".$item_link4." onclick=\"showComment(this.value)\" value=".$item_link4."> Show Comments </option> <div id=\"".$item_link."\"></div>";
Next, I can see the results as a below picture.
And I am coding JS which has the showComment function as below.
function showComment(str) {
if (str.length == 0) {
document.getElementById(""+item_link4+"").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(""+item_link4+"").innerHTML = this.responseText;
}
};
var q = document.getElementById(""+item_link4+"").value;
xmlhttp.open("GET", "showComment.php?q=" + q, true);
xmlhttp.send();
}
}
And Next, I am coding the showComment.php as below to see the 'q' value.
But,
Notice: Undefined index: q in E:\xampp\htdocs\code\v1\showComment.php on line 5.
The first part is like next.
// line 5 is $q = html...
$q = htmlspecialchars($_GET['q']);
global $result;
echo $q;
Eventually, I got something wrong in JS code which received item_link4
How do I change the JS variable originated from php-HTML code?
Please your Kindness.
I have tried so many times. At last I got the good result for going to the better.
PHP code is
echo " <option id=".$i." onclick=\"showComment".$i."(this.value)\" value=".$item_link4."> Show Comments </option>";
And I changed JS code as below.
<script>
function showComment0(str) {
if (str.length == 0) {
document.getElementById("0").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("0").innerHTML = this.responseText;
}
};
var q = document.getElementById("0").value;
xmlhttp.open("GET", "showComment.php?q=" +q, true);
xmlhttp.send();
}
}
</script>
....
<script>
function showComment22(str) {
if (str.length == 0) {
document.getElementById("22").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("22").innerHTML = this.responseText;
}
};
var q = document.getElementById("22").value;
xmlhttp.open("GET", "showComment.php?q=" +q, true);
xmlhttp.send();
}
}
</script>
<script>
function showComment23(str) {
if (str.length == 0) {
document.getElementById("23").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("23").innerHTML = this.responseText;
}
};
var q = document.getElementById("23").value;
xmlhttp.open("GET", "showComment.php?q=" +q, true);
xmlhttp.send();
}
}
</script>
So I made Id 0 to 18 script. That is, 19 scripts are necessary.
I am waiting for better answer.

Using Ajax/XMLhttprequest to send data to a php file with mail function

I have been following this tutorial (https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started) but I had no luck. I am trying to communicate with a php file with a javascript file using XMLhttpRequest. This is the code bellow. I still dont understand how to fully transfer the data across.
HTML
form id="uDF" method="post" onsubmit="submitValidation()">
JavaScript
function submitValidation(){
var data = [document.forms ["uDF"] ["uDFName"].value, document.forms ["uDF"] ["uDFNumber"].value,
document.forms ["uDF"] ["uDFEmail"].value, document.forms ["uDF"] ["uDFSubject"].value,
document.forms ["uDF"] ["uDFMessage"].value,]
console.log(data);
var char = ''; // variable used to check whether email has #
var x;
var isEmail = false;
var isNotEmpty = false;
//for loop checks email for # char
for(x = 0; x<data[2].length;x++)
{
char = data[2].charAt(x);
if(char === "#"){
isEmail = true;
break;
}
}
var i;
//for loop check if data is collected
for(i=0;i < 5;i++){
if(data[i] === ""){
isNotEmpty = false;
}else{
isNotEmpty = true;
}
}
if(isEmail === true && isNotEmpty === true)
{
var httpRequest;
httpRequest = new XMLHttpRequest();
if(!httpRequest){
return false;
}
httpRequest.onreadystatechange = function(){
if(httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200)
{
var response = JSON.parse(httpRequest.responseText);
}
httpRequest.open('POST', '../userData.mail.php')
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send('uDFName=' + encodeURIComponent(data[0]) + 'uDFNumber=' + encodeURIComponent(data[1]) + 'uDFNumber=' + encodeURIComponent(data[3])
+ 'uDFNumber=' + encodeURIComponent(data[4]))
}
}else if (!isNotEmpty){
alert("empty fields");
}else if(!isEmail){
alert("Please enter valid email!");
}
}
PHP
$uDFName = (isset($_POST['uDFName'])) ? $_POST['uDFName'] : '';
$uDFNumber = (isset($_POST['uDFNumber'])) ? $_POST['uDFNumber'] : '';
$uDFEmail = "my#email";
$uDFSubject = (isset($_POST['uDFSubject'])) ? $_POST['uDFSubject'] : '';
$uDFMessage = $uDFName . "\r\n" . $uDFNumber . "\r\n" . "just testing";
$message = wordwrap($message, 70, "\r\n");
mail($uDFEmail, $uDFSubject, $uDFMessage);
You have to open and send the request outside of the event handler function. The onreadystatechange handler only executes when the ready state of your request changes.
If you don't open and send the request, the handler function is not executed, and you won't see any results.
This solution should work:
var httpRequest = new XMLHttpRequest();
// this function executes whenever the ready state of the request changes
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
}
}
// open the request ...
httpRequest.open('POST', '../userData.mail.php')
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// ... and send it
httpRequest.send('uDFName=' + encodeURIComponent(data[0]) + 'uDFNumber=' + encodeURIComponent(data[1]) + 'uDFNumber=' + encodeURIComponent(data[3])
+ 'uDFNumber=' + encodeURIComponent(data[4]));

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

Unable to pass value to php POST via 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.';
?>

Categories

Resources