passing multiple values using xmlhttp.send - javascript

I am trying to pass two different values into an XMLHttpRequestObject.send but cannot seem to get the php script to read them both, it will only read the first value passed. How can I get the PHP to read both the values, here is the sample code:
HTML
<select id="mes" onchange="callCourseYards(this);">
<option>-</option>
</select>
Javascript
var XMLHttpRequestObject = false;
if(window.XMLHttpRequest){
XMLHttpRequestObject = new XMLHttpRequest();
}else if(window.ActiveXObject){
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function callCourseYards(selectObject){
if(XMLHttpRequestObject){
XMLHttpRequestObject.open("POST", "php/CourseChoiceTeeOff.php");
XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function(){
if(XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200){
var returnData = XMLHttpRequestObject.responseText;
var messageDiv = document.getElementById('tee');
messageDiv.innerHTML = returnData;
}
}
var data = selectObject.value;
var course = selectObject.value;
XMLHttpRequestObject.send("data=" + data + "course=" + course);
}
return false;
}
PHP
<?php
$pdo_dsn='localhost';
$dbname ='XXX';
$mysql_user='XXX';
$mysql_pass='XXX';
$db = mysqli_connect($pdo_dsn, $mysql_user, $mysql_pass, $dbname);
if(!$db){
print "Unable to connect to MySQL";
}
$myData = $_POST['data'];
$myData1 = $_POST['course'];
$sql_state = "SELECT * FROM ".$myData1." WHERE CourseCode = '".$myData."' ORDER BY CourseCode";
$result = mysqli_query($db, $sql_state);
$out = "";
$myrowcount = 0;
if(!$result){
$out = "Error";
}else{
$out = "<option>Selecciona un campo</option><br/ >";
$numresults = mysqli_num_rows($result);
for ($i = 0; $i < $numresults; $i++){
$row = mysqli_fetch_array($result);
$teeOff = $row['TeeOff'];
$out .= "<option id='".$myData."' value='".$teeOff."'> ".$teeOff."</option>";
}
$out .= "<br/ >";
}
print $out;
?>
I cannot seem to get the values through the XMLHttpRequestObject to go through into the PHP. I am not sure if its the syntax or how they should get past into the PHP.
I have tried using the & and the + symbols to concatenate both values, but I am not sure if this is possible. Does anyone know how I can fix this problem? I need both values to be able to do the mySQL search in the database.
Any help would be greatly appreciated. Thanks

Related

Why do I always get undefined response with this ajax post to php?

I am using mouseover event on span element to initiate an ajax post call to php page, but I always get undefined, first for responseText when I used a simple echo to get response and now when I use responseXML. Can somebody please explain me why.
Here is ajax code:
var span = document.getElementsByTagName('span');
for (var i = 0; i < span.length; i++) {
span[i].addEventListener("mouseover", showInformation, false);
}
function showInformation(event) {
var xhr = new XMLHttpRequest();
xhr.open("POST", "../includes/ajax_response.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
content(xhr, event);
}
};
xhr.send("uname=" + event.target.firstChild.textContent);
}
function content(xhr, event) {
var info = document.getElementById('displayInformation');
var xmlResponse = xhr.resopnseXML;
var xmlDocumentElement = xmlResponse.documentElement;
var message = xmlDocumentElement.firstChild.data;
info.innerHTML = message;
info.style.visibility = "visible";
event.target.addEventListener("mouseout", function() {
document.getElementById('displayInformation').style.visibility = "hidden";
}, false);
}
And this is php code:
$username = $_POST['uname'];
$query = "SELECT id, joined FROM users WHERE username = '{$username}' LIMIT 1";
$first_result = Database::getInstance()->query($query);
if ($first_result->num_rows == 1) {
foreach ($first_result as $first) {
$id = $first['id'];
$joined = $first['joined'];
}
}
$first_result->free();
$query = "SELECT COUNT(message) AS count FROM blogs WHERE user_id = '{$id}'";
$results = Database::getInstance()->query($query);
if ($results) {
foreach ($results as $result) {
$number = $result['count'];
}
}
header("Content-Type: text/xml");
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
echo "joined: {$joined}";
echo "number of posts: {$number}";
echo '</response>';
This is version of php with xml, I tired simpler versions with just
$username = $_POST['uname'] and then echo $username, but always response is
undefined.
I read your code once and there does not seem to be any major error. However, I found out this minor bug:
var xmlResponse = xhr.resopnseXML;
spelling of responseXML is incorrect .. maybe that's what's causing the xmlResponse to be undefined?

Variable is not defined even though it is?

Hi I'm trying to call a php function when a button is pressed but I keep getting the error in the title.
I'm calling the function like so:
echo("<th><input type='button' name = 'Attack_Btn' onclick = 'FightPlayer(".$row['username'].")' value ='Attack'></th>");
just say the username that it gets from $row['user... is James the error will display
index.php:1 Uncaught ReferenceError: casualjames is not defined
This is the code that it calls next
function FightPlayer(enemyName){
var xhttpe;
if (window.XMLHttpRequest) {
xhttpe = new XMLHttpRequest();
} else {
xhttpe = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttpe.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
BattlePlayers();
}
};
xhttpe.open("GET", "FightPlayer.php?enemyname="+enemyName, true);
xhttpe.send();
}
and then it calls my php script passing in the variable enemyname for it to use
<?php
session_start();
include 'Training.php';
$link = mysqli_connect("","","","");
if (isset($_SESSION['username'])) {
$enemyname = $_REQUEST["enemyname"];
echo $enemyname;
$energyRemove = 1;
$ExperienceGain = 1;
$sql = "SELECT * FROM userstats WHERE username = '$enemyname'";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_assoc($result);
$Defence = $row["Defence"];
$winChance = CalculateWinChance($link,$Defence);
$sql = "SELECT Energy FROM userstats WHERE username = '".$_SESSION['username']."'";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_assoc($result);
$rand = rand ( 1 , 100 );
if($row["Energy"] < 1 ){
echo "<script type='text/javascript'>alert('Not enough energy to fight. please restore in character page');</script>";
}else{
if($rand < $winChance){
$_SESSION['Battlemessage'] = "you won against ".$enemyname;
$sql = "UPDATE userstats SET `Energy` = `Energy` - '$energyRemove' WHERE username = '".$_SESSION['username']."'";
mysqli_query($link,$sql);
$sql = "UPDATE userstats SET `Experience` = `Experience` + '$ExperienceGain' WHERE username = '".$_SESSION['username']."'";
mysqli_query($link,$sql);
$sql = "UPDATE userstats SET `Satoshi` = `Satoshi` + 2 WHERE username = '".$_SESSION['username']."'";
mysqli_query($link,$sql);
}else{
$_SESSION['Battlemessage'] = "you lost against ".$enemyname;
$sql = "UPDATE userstats SET `Energy` = `Energy` - '$energyRemove' WHERE username = '".$_SESSION['username']."'";
mysqli_query($link,$sql);
$sql = "UPDATE userstats SET `Satoshi` = `Satoshi` + 1 WHERE username = '".$enemyname."'";
mysqli_query($link,$sql);
}
echo "";
}
calculateLevel($link);
}
?>
I'm not sure where the error is actually happening I've put my scripts through online code checkers and it all returns normal. Where am I going wrong here?
The string you're passing into your javascript function needs to be quoted, or else it thinks that it's a variable:
echo("<th><input type='button' name = 'Attack_Btn' onclick = 'FightPlayer(\"".$row['username']."\")' value ='Attack'></th>");
Your error is most likely with the onclick...you need to escape quotes in the function argument here:
echo("<th><input type='button' name = 'Attack_Btn' onclick = 'FightPlayer(\"".$row['username']."\")' value ='Attack'></th>");

Why am I not able to fetch property of the object that I get from PHP?

I am trying to receive data from database based on the name entered by user, everything works fine I do see the value on screen and no error Here is the php code :
<?php
$dbhost = "localhost";
$username = "root";
$password = "";
mysql_connect($dbhost,$username,$password);
#mysql_select_db("trynew") or die(mysql_error());
$user ="mon";
$query = "SELECT * FROM trynewtable where name = '$user' ";
$all_result = array();
$result = mysql_query($query);
if($result==FALSE)
{
die(mysql_error());
}
while($row = mysql_fetch_assoc($result))
{
$all_result[] = $row;
}
header('Content-Type: application/json');
$jsondata = json_encode($all_result);echo $jsondata;
mysql_close();
?>
JavaScript code :
var loadingFunc=function()
{
var xhr;
if(window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else
{
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
var jsonData= "";
xhr.onreadystatechange =function()
{
if(xhr.readyState==4)
{
if(xhr.success =200)
{
jsonData = xhr.responseText;
document.getElementById("dvID").innerHTML = jsonData;
//var parsejson = JSON.parse(jsonData);
//document.getElementById("dvIDO").innerHTML = parsejson.age;
document.getElementById("dvIDO").innerHTML = jsonData[0].age;
}
else
{
document.getElementIdById("dvID").innerHTML = "it's not success ";
}
}
else
{
console.log("error is here");
console.log(xhr.readyState);
}
}
var element1 = document.getElementById("dvID") ;
xhr.open("POST","index.php");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var sendD = document.getElementById("data_found").value;
var data = "data_found=" + sendD;
var element = document.getElementById("btn") ;
if(element)
{
element.addEventListener('click',function(){
console.log("just clicked")
xhr.send(data);
})
}
};
window.onload = loadingFunc();
but the output that I see on the html div is :
[{"id":"1","Name":"mon","Age":"26","Gender":"F"}]
undefined
I am getting the whole object but whenever I am trying to fetch any property of the object like age here (parsejson.age or jsonData[0].age) it's showing undefined , Could anyone help me how do I fetch any property of the object?
Kindly let me know what am I doing wrong ?
First transform the cleartext response into a javascript object. You have the line already there but commented out it seems, after that:
alert(jsonData["Age"]); //Age
alert(jsonData.Age); //Age

php returns empty JSON array

I created an array for town name, "Auckland" and "Hamilton", but the response from php is always empty, any idea?
UPDATE:
after debugging, I found that the problem is in php query
" where town = '$town' ", once i deleted this line, the rest works perfectly.
But I still can't figure out why :<
javascript:
var _addNewTowntoList = function(){
if (_request.readyState == 4) {
if (_request.status == 200) {
var data = JSON.parse(_request.responseText);
if(data.length == 0){
alert("No such town");
return;
}
var t = data[0].town;
var o = data[0].outlook;
var min = data[0].min_temp;
var max = data[0].max_temp;
var witem = new WLine(t,o,min,max);
console.log(t+" "+o+" "+min+" "+max);
_list.push(witem);
}
}
}
here is the php
$town = $POST_['town'];
$query = "Select * From weather WHERE town = '$town'";
$result = mysqli_query($conn, $query);
//create array for data
$data = array();
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row;
}
echo json_encode($data);
change this
$town = $POST_['town'];
> $query = "Select * From weather WHERE town = '$town'";
to
$town = $_POST['town'];
$query = "Select * From weather WHERE town = '".$town."'";
Remember to properly escape the query string
$town = mysqli_real_escape_strin($conn, $_POST['town']);
Because else your script is opened to SQL Injection attack
The other thing to mention here other than correct name for the $_POST is that you can use mysqli_fetch_all function to fetch all results at once and avoid the loop. For example
echo json_encode(mysqli_fetch_all($result, MYSQLI_ASSOC));

Turning PHP into JSON array when parsed in Javascript

So, in order to create a page that has dynamic HTML, the following Javscript code was used:
function add0(Text, Value){
var x = document.getElementById("thingy");
var option = document.createElement("option");
option.text = Text;
option.value = Value;
x.add(option);}
function add(Text, Value){
var x = document.getElementById("stuff");
var option = document.createElement("option");
option.text = Text;
option.value = Value;
x.add(option);}
var c = 0;
var value =<?php echo json_encode($ToAndFromR); ?>;
var formula = <?php echo json_encode($FormulaR); ?>;
while(c < <?php echo $countr ?>){
add0(value[c], formula[c]);
add(value[c], formula[c]);
c++;
}
This was done after recieving $ToAndFromR and $Formula from a SQL Query, in which the code is :
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//declare variables
$countr = null;
$sql = "SELECT * FROM `convert`";
$drippage = mysqli_query($conn, $sql);
//this counts the number of rows
if (mysqli_num_rows($drippage)) {
$countr = mysqli_num_rows($drippage);
}
$ToAndFrom = mysqli_query($conn, "SELECT ToAndFrom FROM `convert`");
$ToAndFromR = null;
$ToAndFromR = mysqli_fetch_all($ToAndFrom, MYSQLI_BOTH);
$FormulaR = null;
$Formula = mysqli_query($conn, "SELECT Formula FROM `convert`");
$FormulaR = mysqli_fetch_all($Formula, MYSQLI_BOTH);
However, the HTML gets shown as [object Object] in the dropdown list, as opposed to their actual values when a regular PHP array is used. Is there a way to fix this?
Each Text and Value passed to your JavaScript functions will be an object with two properties (because you're using MYSQLI_BOTH fetch mode), eg
{"0": "some value", "ToAndFrom": "some value"}
You're attempting to assign this to the option's text and value properties.
You also appear to be running three queries when you should be running one.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset('utf8');
$result = $conn->query('SELECT `ToAndFrom` AS `text`, `Formula` AS `value` FROM `convert`');
$options = $result->fetch_all(MYSQLI_ASSOC);
and in your JavaScript
var options = <?= json_encode($options) ?>;
for (var i = 0, l = options.length; i < l; i++) {
add0(options[i].text, options[i].value);
add(options[i].text, options[i].value);
}
Also, you could cut down on the almost identical JavaScript functions add0 and add by simply passing the <select> ID, eg
function add(selectId, text, value) {
var x = document.getElementById(selectId);
// and so on
}
with
add('thingy', options[i].text, options[i].value);
add('stuff', options[i].text, options[i].value);
I think you should write a separate PHP script which echo the JSON.
Then in the javascript, you should call this PHP and parse the JSON. A simple code:
var xhr = new XMLHttpRequest();
xhr.open("GET", "sql.php", true);
var htmltext= '';
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var jsoninfo = xhr.responseText;
var obj = JSON.parse(jsoninfo);
// text = obj.attribute;
// add0(text,formula[c])
}
}
}

Categories

Resources