PHP receiving black instead of js variable sent? - javascript

I am making a simple web app, in one part of it, I have to send a js variable to PHP. I am sending the JS variable using AJAX but PHP is receiveing blank instead of the data.
Here is the JS function:
function sync(){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
console.log(xmlhttp.responseText);
}
}
xmlhttp.open("POST","sync.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var data = "data=thisisdata";
console.log(data);
xmlhttp.send(data);
}
This is the PHP code:
<?php
return $_POST["data"];
?>
The output that I get at the console is:
data=thisisdata goal.js:23
goal.js:16
i.e., I am getting a blank instead of the responseText. I am NOT getting any errors.
What's wrong? What should I do?

change
<?php
return $_POST["data"];
?>
to
<?php
echo $_POST["data"];
?>
or to see all posted variables
<?php
echo "<pre>"; print_r($_POST);
?>

You need to echo the response on the PHP side :
<?php
echo $_POST["data"];
?>

Related

Post data from javascript to php

I have two dropdowns in my web-page where I select manager and project.
If I choose any manager then I want to get the project which are assigned to particular manager.
I think I can't do this without the help of javascript and ajax.
So I have passed the selected value of manager to javascript file and again I have posted the value using ajax. But it seems the code is not working.
Here is my php code.
<form method="post" action="<?php $_PHP_SELF ?>">
Select Manager <select id='managed' name="managed" onchange="getManager()">
<option value="">---select---</option>
<?php
$conn=mysqli_connect('localhost','root','root','projmanagement');
$result=mysqli_query($conn,'SELECT manager_id,manager_name FROM manager');
while($row=mysqli_fetch_assoc($result)) {
echo "<option value='$row[manager_id]'>$row[manager_name]</option>";
}
?>
</select>
Select Project <select name="projectsd">
<option value="">---select---</option>
<?php
$temp = $_POST['managed'];
var_dump($temp);
die();
$result1=mysqli_query($conn,'SELECT project_id,project_name FROM project inner join manager on project.m_id=$temp');
while($row1=mysqli_fetch_assoc($result1)) {
echo "<option value='$row1[project_id]'>$row1[project_name]</option>";
}
?>
This is my javascript code.
function getManager() {
var myvar=document.getElementById('managed').value;
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("managed").innerHTML = xhr.responseText;
}
}
xmlhttp.open("POST","TaskMaster.php",true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("managed=" + myvar);
}
I'am a beginner to php and javascript.
Please give me an idea to solve my problem.
Try This :
<form method="post" action="<?php $_PHP_SELF ?>">
Select Manager <select id='managed' name="managed" onchange="getManager()">
<option value="">---select---</option>
<?php
$conn=mysqli_connect('localhost','root','root','projmanagement');
$result=mysqli_query($conn,'SELECT manager_id,manager_name FROM manager');
while($row=mysqli_fetch_assoc($result)) {
echo "<option value='$row[manager_id]'>$row[manager_name]</option>";
}
?> </select>
Select Project <div id="project_container"><select name="projectsd"></div>
JS :
function getManager()
{
var myvar=document.getElementById('managed').value;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("project_container").innerHTML = xhr.responseText;
}
}
xmlhttp.open("POST","TaskMaster.php",true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("managed=" + myvar);
}

Passing JavaScript variable to PHP through AJAX

I am following the guide from http://www.w3schools.com/php/php_ajax_database.asp, and I get the basic concept of how this works.
My code:
PHP:
<?php
include('./db.php');
$PM = mysqli_query($con, "SELECT DISTINCT PMName FROM report WHERE PMname <> '' ORDER BY PMName ASC");
?>
<select class="navbar-inverse" placeholder="PM Name" name="PMName"onchange="showUser(this.value)">
<?php
while ($row = mysqli_fetch_row($PM)) {
$selected = array_key_exists('PMName', $_POST) && $_POST['PMName'] == $row[0] ? ' selected' : '';
printf(" <option value='%s' %s>%s</option>\n", $row[0], $selected, $row[0]);
}
?>
</select>
<div id="txtHint"><b></b></div>
JavaScript:
<script>
function showUser(str) {
if (str !==".PM") {
alert(str);
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
and the getuser.php page:
<?php
$q = intval($_GET['q']);
include('./db.php');
$sqlPM= "SELECT * FROM report WHERE PMName = '".$q."'";
$result = mysqli_query($con, $sqlPM);
?>
<table>
<?php
echo $q ;
?>
</table>
I have read through about 12 posts here and tried to make sense of the fact that most of these use some form of $.post('getuser.php'to send the variable over to the new PHP page, but the example from w3schools does not do this. On the initial page, my dropdown is populating fine from my database, and the value I select is being passed into the JavaScript function. I check this with alert(str);, but from there, it doesn't ever seem to get to the second PHP page. I tried testing that it came over using echo $q ;, but that comes up as empty.
What am I doing wrong that is causing the variable that the JavaScript function captures to not be passed over to the second PHP page?
From what I can see, I am following the instructions on the tutorial just fine.
$.post('getuser.php' This syntax is exclusive to a javascript library called jQuery. Furthermore, $q is not an integer it is a string considering the DB query you perform initially, so why are you wrapping $_GET['q'] with intval()?

javascript is not executing inserted in inner HTML

I am trying to get the response from another page for example its name is ajaxresponse.php through ajax request and I also want to perform some actions done by java script on that ajaxresponse.php page but the js code is not working. I am getting the response from that page but the js code for that page is not working. I want to only know why ajax code on mie second page is not working?
function ajaxinput(tinnerid)
{
var xmllhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("articledive").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajaxresponse.php?q="+tinnerid,true);
xmlhttp.send();
}
Here is the php code for first page
<?php
$con1=mysqli_connect("127.0.0.1","root","root","databasetry");
$result=mysqli_query($con1,"select title,articleid from article");
$tinnerid=0;
$articledivid=0;
while($row = mysqli_fetch_array($result))
{
$tinnerid=$row['articleid'];
echo "<div class='tinner' id='$tinnerid' onclick='ajaxinput($tinnerid)' style='cursor:pointer;'>";
echo"<span class='fontdiv'>";
echo $row['title']."<br>";
echo "</span>";
echo"</div>";
$tinnerid++;
$articledivid++;
}
mysqli_close($con1);
?>
Here is the js code for second page
function run()
{
alert("example");
}
Here is the php code of second page
<?php
$id=$_GET['q'];
$result=mysqli_query($con1,"select user.username,article.articleid,article.title,article.artiletext from article inner join user on article.user_id=user.user_id where article.articleid=$id");
$divid=0;
while($row = mysqli_fetch_array($result))
{
$id=0;
echo"<div class='inner' id=$divid >";
$id=$row['articleid'];
echo "<font class='ftitle'>"."Title : "."<a href='#'onclick='ajaxinput($id)'>".$row['title']."</a>"."</font>"."<br>"."<font class='ftext'>".$row['artiletext']."</font>"."<br>"."<font class='flast'>"."Posted By : ".$row['username']."</br>"."</font>"."<br>"."<br>";
echo "<button type='button' onclick='con($id)' class='button'><font size='1'>Delete</font></button>";
echo"</div>";
$divid++;
echo"<script>run()</script>";
}
mysqli_close($con1);
?>
Javascript inserted as innerHTML at runtime won't be executed. A possible solution is to remove the script tag from the second page return, and call the method run() on the first page, after the ajax callback. Like this:
function ajaxinput(tinnerid)
{
var xmllhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("articledive").innerHTML=xmlhttp.responseText;
/* CALL IT HERE AFTER INSERT */
run();
}
}
xmlhttp.open("GET","ajaxresponse.php?q="+tinnerid,true);
xmlhttp.send();

Javascript pass title attribute through function

I have a function that gets the value of a select menu and this work great. But i am trying to add another value to the function. So I thought I would use the title attribute for option (please see code below). The problem is the username parameter in my JavaScript function is undefined.
Does anybody have any ideas of what im doing wrong?
FORM
<form action="">
<select id="acyear" name="acyear" onchange="showyearlogdays(this.value, this.title)">
<option value="" label="">- Year -</option>
<?php
$is_business_result = mysql_query('SELECT DISTINCT(academic_year)FROM holiday_entitlement_business_manual WHERE employee = \'' . $username . '\'');
while($acyear_filter = mysql_fetch_array($is_business_result)) {
echo '<option value="'.$acyear_filter['academic_year'].'" title="'.$username.'"';
$datestr = $acyear_filter['academic_year'];
$currentyear = substr($datestr, 0, 4);
if(intval(substr($datestr,4,2)) < 8){$ayear = ($currentyear - 1).'/'.$currentyear;}
else{$ayear = ($currentyear).'/'.($currentyear + 1);}
echo '>';
echo $ayear;
echo '</option>';
}
?>
</select>
</form>
Javascript
function showyearlogdays(str, username)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","days_yearlog.php?username="+username+"&q="+str,true);
xmlhttp.send();
}
You need to get the title attribute of the selected option. Your code is pointing to the title attribute of the select tag. Make the change below:
showyearlogdays(this.value, this.options[this.selectedIndex].title)
You should also address the security concern mentioned in the comments. The way your query is setup would make for a really simple SQL Injection attack. If you don't want to rearchitect it the way the commenter suggested, I would at least escape $username so that SQL can't be injected.

window.XMLHttpRequest combine with script .change

I have a problem with combinning two scripts.
Fisrt script is working perfectly and taking stuf from mysql:
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open('GET','includes/test-search.php?q='+str,true);
xmlhttp.send();
}
</script>
The second one is working perfectly and it's simple script for inserting data after change:
<script type="text/javascript">
$("document").ready(function(){
$("#selection").change(function () {
$("#someDivName").html( $("#selection option:selected").val() );
});
});
</script>
now the hole point is to combine them.
It's look like, when I load the site it don't have id selection and second script stops but after taking data from php and mysql file test-search.php the missing id selection is on site but the first script is not checking if id selection apear and don't work.
The php code:
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("table", $con);
$sql="SELECT * FROM prod_models WHERE prod_main_group_id = '".$q."'";
$result = mysql_query($sql);
echo '
<select id="selection" name="prod_main_group_id" onchange="change_val()">
<option value="">Wybierz produkt</option>
';
while($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['id'].'">';
echo $row['product_name'] . "</option>";
}
echo "</select>
";
mysql_close($con);
?>
Code to display changed script:
<input type="text" id="someDivName" value="" />
if any one can help with solving the problem will be realy nice.
Thx i'm waiting for it now and trying to solve this for my self but now I don't have other ideas for it.

Categories

Resources