Javascript code not working on PHP include - javascript

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.

Related

Javascript and PHP in one file (form handling and XMLHTTPRequest)

I am confused about my homework requirements: we need to put JS, HTML and PHP code in the same file xxx.php.
There is a form in the HTML, and once I submit the form, I need to send a request (XMLHTTPRequest) to myPHP.php with the form inputs (using POST to transfer the form data PHP). The PHP file will retrieve the form inputs, reformat it to the syntax of the API and send it to the Google API to get JSON object.
I am a beginner of PHP and JS, and I don't know how to combine them in the same file and do the homework based on the requirements. Like, how to send the JSON object obtained in PHP to Javascript.
Here is framework of my code (myPHP.php):
<html>
<head>
<script type="text/javascript">
// show the result
function show() {
var xmlhttpreq = new XMLHttpRequest();
var keyword = document.getElementById("keyword").value;
var post_data = "keyword=" + keyword;
xmlhttpreq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonObj = JSON.parse(this.responseText);
createTable(jsonObj);
}
};
xmlhttpreq.open("POST", "myPHP.php", true);
xmlhttpreq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttpreq.send(post_data);
}
function createTable(object) {
var out = "xxx";
document.getElementById("display").innerHTML = out;
}
</script>
</head>
<body>
<div id="display"></div>
<form action="myPHP.php" name="myForm" method="POST">
<b>Keyword </b><input type="text" id="keyword" name="keyword">
<br>
<button type="submit" onclick="show()" name="search">Search</button>
</form>
<?php
if (isset($_POST["search"])) {
// extract the form data
$keyword = $_POST["keyword"];
// geocode the address
$location = urlencode($location);
// google map geocode api url
$url = "xxxxxxxx";
$res_json = file_get_contents($url);
echo $res_json;
}
?>
</body>
</html>
You can try something like this:
<?php
if (isset($_POST["search"])) {
// extract the form data
$keyword = $_POST["keyword"];
// geocode the address
$location = urlencode($location);
// google map geocode api url
$url = "xxxxxxxx";
echo file_get_contents($url);
} else {
echo '<html>
<head>
<script type="text/javascript">
// show the result
function show() {
var xmlhttpreq = new XMLHttpRequest();
var keyword = document.getElementById("keyword").value;
var post_data = "keyword=" + keyword;
xmlhttpreq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonObj = JSON.parse(this.responseText);
createTable(jsonObj);
}
};
xmlhttpreq.open("POST", "myPHP.php", true);
xmlhttpreq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttpreq.send(post_data);
}
function createTable(object) {
var out = "xxx";
document.getElementById("display").innerHTML = out;
}
</script>
</head>
<body>
<div id="display">
<?php echo $result; ?>
</div>
<form action="myPHP.php" name="myForm" method="POST">
<b>Keyword </b><input type="text" id="keyword" name="keyword">
<br>
<button type="submit" onclick="show()" name="search">Search</button>
</form>
</body>
</html>';
}
?>
You first have to test in myPHP.php if there is some data send. If so, the form already has been display and the browser is sending the form data back. If not, it is the first time the php-page is loaded and you can display the html and javascript.
So:
<?php
//test if there is data from the form
if( isset( $_POST['some-form-variable'] ) ){
// YES
// process data an display something
}
else{
// NO DATA
// display form and javascript
}

how to write php inside javascript

I write php inside JavaScript in the following way. even though the delete function is working that alert doesn't come.
Here is my code:
Delete.php
<script type="text/javascript">
function delete_id(id) {
if (confirm('Are you sure To Remove This Record ?')) {
<?php
include('database_connect.php');
if (isset($_GET['variable'])) {
$sql_query = "DELETE FROM register WHERE id=".$_GET['variable'];
mysqli_query($con, $sql_query);
header("Location: newusers.php");
}
mysqli_close($con);
?>
}
}
</script>
You can't do it like this. The correct way would be to make an ajax request to backend, and then have php delete the row.
Edit
here is some sample code for you
<script>
function delete_id() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert("deleted");
}
};
xhttp.open("GET", "/delete.php", true);
xhttp.send();
}
</script>
and the delete.php goes like
<?php
//write code for delete here
?>
Another point is that header("Location...") would redirect but in ajax, hence it is better to not use php redirect, but check in javascript and then use document.location for the redirect.

Ajax. Sending data to php file

Good day, I'm trying to use Ajax in my web application. But I have a little problem with it. I try to control a form if some username has already been registered or not. But my JavaScript seem does not send $_POST value to PHP. And responses that user in not defined on the line where I have $_POST['user'].
Here what I have.
PHP:
<?php
$opt = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$dsn ='mysql:dbname=someone;host=127.0.0.1;charset=utf8';
$user='someone';
$pswd='aaa';
$dbh = new PDO($dsn, $user, $pswd, $opt);
$query="SELECT 1 FROM users WHERE username = :username";
$query_p=array(':username' => $_POST['user']);
try
{
$statment = $dbh->prepare($query);
$result = $statment->execute($query_p);
}catch(PDOException $e)
{
echo "Can't run query: " . $e->getMessage();
}
$row = $statment->fetch();
if($row){
return 0;
}else {
return 1;
}
?>
So it opens a connection to database and runs a query
JavaScript:
function checkUser(e){
var state1 = document.getElementById("alert_text");
var u = document.getElementById("user").value;
if(u != ""){
state1.innerHTML = 'processing...';
var request = new XMLHttpRequest();
request.open("POST", "validation.php", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var result=request.responseText;
alert(result);
if(result==1){
state1.innerHTML="OK";
}else{
state1.innerHTML="Alredy exists!";
}
}
};
request.send(u);
var slova = request.responseText;
}
}
document.getElementById("user").addEventListener("blur",checkUser,false );
So technically it is ajax.
HTML:
<form id="check" name="signUp" method="post">
<p class="alert_text"></p>
<label for="user">Username:</label><br />
<input id="user" name="user" type="text" ><br />
</form>
I don't really see what's the problem...
You're not passing the username into the PHP script. Your PHP is looking for a POST variable, $_POST['user'] – in your JavaScript you make a GET request, so the PHP script has nothing to look up.
Based on the edited question: You are not sending any key-value pairs to the server, just a single value.
You need to change:
var u = document.getElementById("user").value;
to:
var u = 'user=' + encodeURIComponent(document.getElementById("user").value);
And then later on the pair will be sent correctly:
request.send(u); // sends a single key-value pair
Note that I have just added the encodeURIComponent function to make sure the value gets encoded correctly.

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

Need Javascript to locate individual divs looped by PHP

I managed to create a PHP loop that takes an array and create multiple copies of the same button while the buttons each have their own idenfication ("adiv_1" , "adiv_2", "adiv_3", etc). I have a javascript function that is able to take a single button "before it was called just 'adiv'" and change the text of the button if one clicks on it.
However due to the PHP loop which named it "adiv_1 or adiv_2 or adiv_3", I don't know how to create a javascript function that can take one of the buttons looped with a different identification div tag and get javascript to identify each one if one click on a certain button in that group. Can anyone help?
PHP loop that create the group of buttons
<?php
$array_query = mysql_query("SELECT * FROM person_finder_info");
$i = 0;
while($search_row = mysql_fetch_array($array_query)){
?>
<p><button type="button" onclick='load()'><div id='adiv_<?php echo $i?>'>Add this person</div></button></p>
<?php
$i++;
}
?>
Javascipt / AJAX function that changes button text (by getting echoed information in PHP file)
//Changes button text to "You added him!"
function load(){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("adiv_1").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET','include.inc.php', true);
xmlhttp.send();
This is rudimentary, but I think you're trying to do something like this, just loop inside of the onreadystatechange function like you did in the other one to display what you want in there to handle all of the buttons.:
<?php
for($i = 0; $i < count($array); $i++)
{
?>
<p><button type="button" onclick='load()'><div id='adiv_<?php echo $i;?>'>Add this person</div></button></p>
<?php
}
?>
<script>
//Changes button text to "You added him!"
function load(){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
<?php
echo "var divArray = {";
for($i = 0; $i < count($array); $i++)
{
echo "'adiv_".$i."'".($i < $count-1 ? "," : "");
}
echo "};" /// after the loop this will output like var divArray = {'adiv_1','adiv_2', ... };
?>
for (var i = 0; i < divArray.length; i++) {
document.getElementById(divArray[i]).innerHtml(dataFromResponse[i]); // assuming you've processed the response from AJAX into an array
}
}
}
xmlhttp.open('GET','include.inc.php', true);
xmlhttp.send();
</script>
I can't help you with setting up all of the button innerHTML though since I don't know what kind of response you're getting from AJAX. This is just to lead you in the right direction.

Categories