Run Javascript script from ajax response - javascript

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

Related

Undefined index error in ajax using javascript

I am sending data through ajax it is working properly using jquery but JavaScript code is giving undefined error
function send_message() {
var name = document.querySelector("#name").value;
var email = document.querySelector("#email").value;
var mobile = document.querySelector("#mobile").value;
var message = document.querySelector("#message").value;
if (name == "") {
alert('Please enter name');
} else if (email == "") {
alert('Please enter email');
}
else if (mobile == "") {
alert('Please enter mobile');
}
else if (message == "") {
alert('Please enter message');
} else {
var ajax = new XMLHttpRequest();
ajax.open("POST", "send_message.php", true);
ajax.setRequestHeader("Content-Type", "application/json");
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// Response
var response = this.responseText;
console.log(response);
alert(response);
}
};
var data = 'name='+name+'&email='+email+'&mobile='+mobile+'&message='+message;
ajax.send(JSON.stringify(data));
}
}
the error code is
<br />
<b>Notice</b>: Undefined index: name in <b>D:\xampp\htdocs\webmakeup\send_message.php</b> on line <b>4</b><br />
<br />
<b>Notice</b>: Undefined index: email in <b>D:\xampp\htdocs\webmakeup
send_message.php is the file I am sending data to.
This is my php code
require('connection.inc.php');
require('functions.inc.php');
$name=get_safe_value($con,$_POST['name']);
$email=get_safe_value($con,$_POST['email']);
$mobile=get_safe_value($con,$_POST['mobile']);
$comment=get_safe_value($con,$_POST['message']);
$added_on=date('Y-m-d h:i:s');
mysqli_query($con,"insert into contact_us(name,email,mobile,comment,added_on) values('$name','$email','$mobile','$comment','$added_on')");
echo "Thank you";
?>
Your PHP endpoint is expecting application/x-www-form-urlencoded data not JSON.
You can use a URLSearchParams object to send that type of data.
var ajax = new XMLHttpRequest();
ajax.open("POST", "send_message.php", true);
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// Response
var response = this.responseText;
console.log(response);
alert(response);
}
};
var data = new URLSearchParams ({name,email,mobile,message});
ajax.send(data);
Don't JSON.stringify what you send.
Wrap each variable in encodeUriComponent.
Don't add a space after the equals.
Try:
var data = 'name=' + encodeURIComponent(name)
+ '&email=' + encodeURIComponent(email)
+ '&mobile=' + encodeURIComponent(mobile)
+ '&message=' + encodeURIComponent(message);
ajax.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.

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.

onreadystatechange func. not working

i have written following ajax code but the onreadystatechange func. is not working within the chkPwd script func....only alert box with hiii 1 is shown on browser
function chkPwrd(){
var fname = document.getElementById("fname").value;
var lname= document.getElementById("lname").value;
var umail= document.getElementById("umail1").value;
var upass= document.getElementById("upass").value;
var xhr=new XMLHttpRequest();
if( flag === 1)
{
xhr.open("POST","conCheck?umail="+umail);
xhr.send(null);
alert("HIIII 1");
xhr.onreadystatechange=function()
{alert("HIIII 2");
if(xhr.readyState===4 & xhr.status===200)
{alert("HIIII 3");
var a=xhr.responseText;
if(a.indexOf('5')!==-1)
{alert("Emailid already Exists");
document.getElementById('umail1').style.color="red";
// document.getElementById('umail1').innerHTML="Emailid already Exists";
}
if(a.length===0)
{alert("Registering you..please click OK");
var char="register.jsp?fname="+fname+"&lname="+lname+"&umail="+umail+"&upass="+upass;
window.open(char,"_self");
}}
};}};
You called send before declaring onreadystatechange, that's why it doesn't work :
function chkPwrd() {
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var umail = document.getElementById("umail1").value;
var upass = document.getElementById("upass").value;
var xhr = new XMLHttpRequest();
if (flag === 1) {
xhr.open("POST", "conCheck?umail=" + umail);
alert("HIIII 1");
xhr.onreadystatechange = function() {
alert("HIIII 2");
if (xhr.readyState === 4 & xhr.status === 200) {
alert("HIIII 3");
var a = xhr.responseText;
if (a.indexOf('5') !== -1) {
alert("Emailid already Exists");
document.getElementById('umail1').style.color = "red";
// document.getElementById('umail1').innerHTML="Emailid already Exists";
}
if (a.length === 0) {
alert("Registering you..please click OK");
var char = "register.jsp?fname=" + fname + "&lname=" + lname + "&umail=" + umail + "&upass=" + upass;
window.open(char, "_self");
}
}
};
xhr.send(null);
}
};

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