AJAX call to php not working - javascript

I'm working on AJAX programming in which I have a little problem. In the below code, I think my php script is not echoing back success. I'm trying to insert values into my database table. Accordingly, the values are getting inserted into the table. I have a span element on my page which by default shows nothing. But if the php script is echoing back success, it must show "AJAX worked". If my PHP script is not echoing back "success", it must show "AJAX didn't work". But it is showing "AJAX didn't work" though the values are getting inserted. If I didn't include the database code, then my script is echoing back success and the span element is showing "AJAX worked". But if I include database code, I think it is not echoing back success and the span elemnt is showing "AJAX didn't work". Below is my code:
<head>
<meta charset="UTF-8">
<title></title>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function insert(){
var elem = _("myTextArea").value;
var result = _("result");
result.innerHTML += elem + "<br>";
elem.value = "";
var ajax = ajaxObj("POST", "dynamicdiv_parser.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "success"){
_("status").innerHTML == "AJAX worked";
}
else{
_("status").innerHTML == "AJAX didn't work";
}
}
}
ajax.send("post="+elem+"&type=a");
}
</script>
</head>
<body>
<form name="dynamicdivform" id="dynamicdivform" onsubmit="return false;">
<p id="result"></p>
<textarea name="myTextArea" id="myTextArea" cols="100" rows="14"></textarea><br>
<input type="button" id="postBtn" value="POST" onClick="insert()">
<span id="status"></span>
</form>
</body>
I have included two JavaScript files in my program which are main.js and ajax.js. Below is their code.
This is main.js:
function _(x){
return document.getElementById(x);
}
This is ajax.js:
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
This is my PHP script which is echoing back success
<?php
if(isset($_POST["post"])){
include_once("php_includes/dbconsampledb.php");
$data = $_POST['post'];
$type = $_POST['type'];
$sql = "INSERT INTO posts(data, type)
VALUES('$data','$type')";
$query = mysqli_query($db_conx, $sql);
echo "success";
}
?>
Before posting this question, I have tried the works but I didn't find any solution. This is very important to me. So please can anyone debug it and tell me what the problem is... Thanks in advance!!

_("status").innerHTML == "AJAX worked";
should be
_("status").innerHTML = "AJAX worked";
with one = only

My suggestion is to use a console.log() for debuging your ajax response.
if(ajaxReturn(ajax) == true) {
console.log('Response: ', ajax.responseText);
if(ajax.responseText == "success"){
Probably there is some errors with DB functionality.

Related

Javascript code not working on PHP include

So I have a main page which have buttons, each buttons contain names, when I click that button I want to pop up div which shows information of that person, I used ajax to retrieve info from php,
var strURL="searchSender.php?ID="+ID;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
outMsg=req.responseText;
var prevWin = document.getElementById("senderInfo");
prevWin.innerHTML = outMsg;
prevWin.style.top = 50+"px";
prevWin.style.right = 80+"px";
prevWin.style.visibility = "visible";
} else {
alert("Problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
searchSender.php basically redeem info of that specific person from the database, that returns these codes (i didn't include here the code that retrieves data from database)
<label>Name: <?php echo $row['Name'];?> </label></br>
<label>Address: <?php echo $row['Address'];?></label></br>
<label>Contact: <?php echo $row['ContactNumber'];?></label></br>
<div id="divSenderMap">
<?php
$url = "mapSender.html";
$_SESSION['SenderID'] = $row['ID'];
include $url ?>
</div>
<input type="button" id="btnSendReply" value="SEND"/>
<input type="button" id="btnCloseDiv" value="X" onclick="closeDiv()"/>
mapSender.html is supposed to return a map where the person is, the code is working on any other file/page, but it does not do it here. It is returning php and html codes but not javascript codes. What could be wrong?
As #MichaelLonghurst told it seems your file is named mapSender.html. So the server does not call PHP before return the HTML.
You should rename mapSender.html into mapSender.php.

Error when trying to call javascript function

I'm trying to add a listener into the 'Yes' button which is shown in the code below.I want this function to save this boolean value into approval field in my database like:$query_row['approval']==1; and a message to display on it.But when executing the code nothing happens after clicking on the'Yes button'.
Can someone please show me how to fix this code if there is an error on it?
Thanks in advance!
This is my code:
<html >
<head>
<title></title>
</head>
<body>
<?php
if( !($database=mysql_connect("localhost","root",""))||!(mysql_select_db("st_login",$database)) )
print("Could not connect");
$result = mysql_query("SELECT * FROM `login` WHERE `admin` = 0 AND `approval`=0");
// if($_POST['admin']==0) {//perjashton administratorin
if(mysql_num_rows($result) == 0) {//esht aprovuar llogaria
if(!($result=mysql_query($query,$database)))
{
print("Could not execute query");
die (mysql_error());//ose error
}
//nese esht aprovuar logini i st.
echo "You are approved";
}
else //approval=0
echo"YOU HAVE NEW REQUESTS WAITING FOR APPROVAL IN YOUR WEBSITE!!!<br />";
while($query_row=mysql_fetch_assoc($result)){
$firstname=$query_row['firstname'];
$lastname=$query_row['lastname'];
$username=$query_row['username'];
$password=$query_row['password'];
$email=$query_row['email'];
$cv=$query_row['cv'];
echo $firstname.' '.$lastname.' has this cv:'.$cv.'<br /> Do you want to approve his account?
<button id="but">Yes</button><button>No</button><br />
<p id="demo"></p>';
?>
<script>
document.getElementById("but").addEventListener("click", MyFunction());
function MyFunction() {
$query_row['approval']==1;
document.getElementById("demo").innerHTML = "This account is approved";}
</script>
<?php
}mysql_close($database);
?>
</body>
</html>
And this is my database with the approval field which boolean value I'm trying to change:
Change document...addEventListener("click", MyFunction()); to document...addEventListener("click", MyFunction); otherwise your function executes immediately and only once.
You can't modify a value in the database only with changing value of the output array. You have to create a new php file and call it asynchronuslly. Read more about updating values in the database here and about calling files asynchronuslly here.
First, I will edit your main file because it's a mess (sorry to say that, but don't worry, it was same with me):
<html>
<head>
<title></title>
<script>
function MyFunction(id) {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
if(xhttp.responseText.indexOf("UPDATE WENT OK")!=-1)
document.getElementById(id).nextSibling.innerHTML = "This account is approved";
}
else {
document.getElementById(id).nextSibling.innerHTML = "An error occured while approving this account";
}
}
xhttp.open("GET", "ajax_file.php?id="+id, true);
xhttp.send();
}
</script>
</head>
<body>
<?php
if(!($database = mysql_connect("localhost","root","")) || !(mysql_select_db("st_login",$database)))
print("Could not connect");
else {
$result = mysql_query($database,"SELECT * FROM `login` WHERE `admin` = 0 AND `approval`=0");
if(!$result){
print("Could not execute query");
die (mysql_error());//ose error
}
else{
if(mysql_num_rows($result) == 0) {//esht aprovuar llogaria
//nese esht aprovuar logini i st.
echo "You are approved";
}
else { //approval=0
echo"YOU HAVE NEW REQUESTS WAITING FOR APPROVAL IN YOUR WEBSITE!!!<br/>";
while($query_row=mysql_fetch_assoc($result)){
$firstname=$query_row['firstname'];
$lastname=$query_row['lastname'];
$username=$query_row['username'];
$password=$query_row['password'];
$email=$query_row['email'];
$cv=$query_row['cv'];
echo $firstname.' '.$lastname.' has this cv:'.$cv.'<br /> Do you want to approve his account?';
?><div class="container"><button id="<?php echo $query_row['id'];?>" onclick="MyFunction(this.id)">Yes</button><button>No</button><br />
<p class="demo"></p></div><?php
}
}
}
}
mysql_close($database);
?>
</body>
</html>
Now, create a php file named ajax_file.php (in the same folder):
<?php
if(!($database = mysql_connect("localhost","root","")) || !(mysql_select_db("st_login",$database)))
die("Could not connect");
else {
$id = intval($_GET['id']);
$result = mysql_query($database,"UPDATE table `login` SET approval = 1 WHERE `id` = '".$id."'");
if(!$result){
print("Could not execute query");
die (mysql_error());//ose error
}
else{
echo "UPDATE WENT OK";
}
Do not hesitate to ask me about any detail how this works. Also, this might not be correct because i don't exactly know what you are doing or want to do with the file you provided. But, if you'll give me the details, I will edit it so it will work.

Call PHP function on click of a html button

I would like to call a php function after clicking a button.
I already found a way to do this (kind of).
This is my code:
info.html
<html>
<head>
</head>
<body>
<input type=button value="test" onClick="self.location='http://127.0.0.1/info.php?runFunction=main'">
</body>
</html>
info.php
<?php
if(isset($_GET['runFunction']) && function_exists($_GET['runFunction']))
call_user_func($_GET['runFunction']);
else
echo "Function not found or wrong input";
function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle ,1024,";");
}
fclose($file_handle);
return $line_of_text;
}
function main($csvFile){
//Set path to CSV File
$csv = readCSV($csvFile);
echo '<pre>';
print_r($csv);
echo '</pre>';
}
?>
My button is able to call the main function, but I do not know how to pass on a variable with a button click, could anybody help me with this?
You could pass the argument as another URL parameter:
<input type=button value="test" onClick="self.location='http://127.0.0.1/info.php?runFunction=main&arguments[]=File.csv'">
Then the PHP would be:
if(isset($_GET['runFunction']) && function_exists($_GET['runFunction'])) {
if (isset($_GET['arguments'])) {
$args = $_GET['arguments'];
} else {
$args = array();
}
call_user_func_array($_GET['runFunction'], args);
} else {
echo "Function not found or wrong input";
}
Putting [] after the parameter name in the URL tells PHP to collect all the parameters with this same name into an array.
However, this is extremely dangerous, since it allows someone to execute any PHP function. Someone could connect to a URL like info.php?runFunction=unlink&arguments[]=.htaccess.
You should check the function name against a list of allowed functions to call.
You have to make a AJAX call. You can pass any arguments in that via GET or POST method. AJAX is simplest way to do this.
Change
<input type=button value="test" onClick="self.location='http://127.0.0.1/info.php?runFunction=main'"
to
<input type=button value="test">
You should use Ajax to send data to the server
<script>
function sendData(){
var data1 = "Hello";
var data2 = "World";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
alert(xmlhttp.responseText);
}
xmlhttp.open("GET", "ajax.php?data1=" + data1 + "&data2=" + data2, true);
xmlhttp.send();
}
</script>
You call the sendData function, when the button is clicked:
<input type=button value="test" onClick="sendData()">
The server reads the GET-Parameter
if(isset($_GET['data1']) && isset($_GET["data2"])){
$data1 = $_GET["data1"];
$data2 = $_GET["data2"];
return $data1 . " " . $data2 . " was sent to the server";
}

Trying to write JSON data to a txt file using Ajax and PHP

My project is to take input from the user and write it to the end of a text file in JSON format using ajax and php. Problem is that the php only writes the time and date to the end of the file and nothing else. I took the example from a previous post and modified it here for my purposes. Here's the html
movie.html:
<html lang="en">
<head>
<meta charset="utf-8"/>
<script src="movie.js" type="text/javascript"></script>
</head>
<body>
<h1>
<center>
<input id="box" type="textbox"name="box" value="Enter Movie:"/>
<input id="add" type="button" value="Submit" onClick="addStuff();" /></center>
</h1>
<div id="status" ></div>
<h2>MOVIE NAME:</h2>
<ul id="list" name="list">
</ul>
<div id="status"></div>
</body>
</html>
Here's the movie.js file which sends the data via Ajax:
function addStuff(){
var movie_name_entered = document.getElementById("box").value;
var movieList = document.getElementById("list");
var hr= new XMLHttpRequest();
var url= "movie.php";
hr.open("POST",url,true);
hr.setRequestHeader("Context-type","application/x-www-form-urlencoded");
var param = "film=" + movie_name_entered;
hr.setRequestHeader("Content-length", param.length);
hr.setRequestHeader("Connection", "close");
hr.onreadystatechange= function(){
if(hr.readyState==4 && hr.status==200){
var return_data=hr.responseText;
console.log(hr.responseText);
document.getElementById("status").innerHTML=return_data;
}
}
hr.send(param);
document.getElementById("status").innerHTML = "processing...";
}
Here's the php (btw, I console.logged the data being sent to the php and it is correct):
<?php
if($_POST){
$data = $_POST["film"];
$file ='movie.txt';
$fp = fopen($file, "a");
$encoded = json_encode($data);
fwrite($fp, $encoded);
fclose($fp);
return $encoded;}
?>
As mentioned above, the code only writes the time and date to the text file and nothing more no matter what I do. I tested the data being sent and it's valid $_POST data. I'm not sure how else to proceed. Any helop would be appreciated. Thx!
try this code in movie.js
function addStuff() {
var movie_name_entered = document.getElementById("box").value;
var movieList = document.getElementById("list");
var hr = new XMLHttpRequest();
var url = "movie.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var param = "film=" + movie_name_entered;
hr.setRequestHeader("Content-length", param.length);
hr.setRequestHeader("Connection", "close");
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
console.log(hr.responseText);
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(param);
document.getElementById("status").innerHTML = "processing...";
}
Please change your php code to below
if ($_POST) {
$data = $_POST["film"];
$file = 'movie.txt';
$fp = fopen($file, "a+");
$encoded = json_encode($data);
fwrite($fp, $encoded);
fclose($fp);
exit();
}
you are getting a empty $_POST variable so your php code is never gets executed. you have a mistake in your code :
hr.setRequestHeader("Context-type","application/x-www-form-urlencoded");
it should be Content-type , replace x with c :D

JS bug: input field repeated with xmlhttp response text

This is a follow up of another question I asked last night. My problem now is not that the script doesn't works, but that I'm getting some very strange repeat of an HTML input element when my xmlhttprequest object returns the response text. Here's the code:
<!DOCTYPE HTML>
<?php
if(!empty($_GET['uName']))
{
$r = mysql_connect("localhost", "root", "pass") or die("Couldn't connect to db");
mysql_select_db("db", $r) or die ("Couldn't select db");
$q = mysql_query("select * from users where uName = '{$_GET['uName']}'") or die("Couldn't query table");
$data = mysql_fetch_assoc($q);
mysql_close($r);
}
?>
<html>
<head>
</head>
<body>
<form>
<input type="text" name="fUName" onchange="ShowUser(fUName.value);" value="name" style="width:125px;">
</form>
<div id="display"><?php print "ID = {$data['id']}"; ?></div>
</body>
</html>
<script type='text/javascript'>
function ShowUser(name)
{
if(name.length == 0)
{
document.getElementById("display").innerHTML = "Please enter a username to check";
return;
}
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("display").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "index.php?uName=" + name, true);
xmlhttp.send();
}
</script>
Here's the strange problem:
There should only be one input field, and is orginally, however when I enter text into it and it loses focus, the JS is triggered and also prints out another input field.
Please ignore the bad practice of PHP, JS and HTML/CSS in one script, this was supposed to be a quick test that has turned for the worse :)
I'm baffled!
Thanks for any help.
The problem lies in the fact that all of your code is in one page. Consider this: you load up index.php. After it's all displaying then you call this same page again (for your AJAX request) so you're essentially saying "Hey, I want you to try and load this page again," hence why you're ending up with duplicate fields.
Try separating out your files in to something like index.php and getuser.php or something of the sort.

Categories