Pass json var to php - javascript

Friends be patient with me. I'm not even a newbie. I'm developping a website that accesses MySQL database and I'm using this code:
File getdata.php
<?PHP
require_once("php/simfatic-RegistrationForm-dc288cf/source/include/membersite_config2.php");
$mycon = mysqli_connect("localhost", "dbuser", "ammr4024", "gadgetbid") or die("Erro! " . mysqli_error($mycon));
$myque = "SELECT * FROM leilaov WHERE numero12345 = 1";
$resul = $mycon->query($myque);
if(!$resul) {
die("Erro no query!" . $fgmembersite->UserId());
}
$myrow = mysqli_fetch_array($resul);
$variarr = array('0' => $myrow['fotodet'], '1' => $myrow['anoini'], '2' => $myrow['mesini'], '3' => $myrow['diaini'], '4' => $myrow['horaini'], '5' => $myrow['minutoini']);
echo json_encode($variarr);
?>
File getdatamain.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function reqListener () {
console.log(this.responseText);
}
function teste() {
var oReq = new XMLHttpRequest();
oReq.onload = function() {
var variarr = JSON.parse(this.responseText);
alert(variarr[0]+" em "+variarr[1]+"-"+variarr[2]+"-"+variarr[3]+" às "+variarr[4]+":"+variarr[5]);
};
oReq.open("GET", "getdata.php", true);
oReq.send();
}
</script>
</head>
<body>
Botanito
<input type="submit" name="botao" id="botao" value="Largar bosta" onclick="teste()" />
</body>
</html>
This works perfect! Clicking the button retrieves the information I want from MySQL table.
My question is:- Is it possible to pass a variable to getdata.php?
As you can see in this file I have
$myque = "SELECT * FROM leilaov WHERE numero12345 = 1";
Well, I want to pass a variable and use it in this "SELECT" (instead of "1")
Here's some of my trials that didn't work.
var indice = 1;
oReq.open("POST", "getdata.php", true);
oReq.send(indice);
var indice = {
object: { child:1 }
}
oReq.open("POST", "getdata.php", true);
oReq.send(indice);
When I print the $POST the result is always the same
Array
(
)
Can anybody help me?

Related

window.onload function is not getting called on the page

My code is as shown below:
xyz.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Status</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div style="width: 300px;padding: 10px;margin: 0 auto;background: #f2f2f2;">
<form name="Form">
<input type="hidden" name="Status" value="<?php echo $_POST['Status'] ?>" />
</form>
<script type="text/javascript">
alert(window.onload);
window.onload = function() {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://api.com');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200) {
var apiresponse = JSON.parse(xhr.response);
console.log(apiresponse);
if (apiresponse.status == "200") {
document.getElementById('response').innerHTML = apiresponse.message + '<br/> Press back button to continue in App.';
} else {
document.getElementById('response').innerHTML = JSON.stringify(apiresponse);
}
} else {
document.getElementById('response').innerHTML = JSON.stringify(xhr);
}
};
var elements = document.forms['Form'].elements;
let formBody = [];
for (var i = 0, element; element = elements[i++];) {
let encodedKey = encodeURIComponent(element.name);
let encodedValue = encodeURIComponent(element.value);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
document.getElementById('request').innerHTML = formBody;
xhr.send(formBody);
}
</script>
</body>
</html>
when I run the above code, in alert method I get null value and the function below it given with window.onload = function() is not getting called at all. So is there anything which needs to be included to get it done.
When you call alert(window.onload) it is null because you have not assigned a function to window.onload. Your alert proves nothing.
For a sanity check, add the code alert('hello world'); above the line var xhr = new XMLHttpRequest(); in the function you bind to window.onload. You will probably find that your function is being called but its behavior is not acting as you expect, so you think your function is NOT being called on window.onload but it actually is.

send parameter from js file to jsp file with ajax

Here is my js file where my goal is to send variable va to jsp file and output it. The problem I can't find the bug.
$(function(){
$("td").click(function(){
var date = $(this).html();
var message = prompt(year+"year "+month+"month "+ date+"day","null!");
this.append(message);
var variable = "mememem";
var sendData = new XMLHttpRequest();
sendData.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert("connected to server");
}
};
sendData.open('GET','dataFile.jsp?na='+variable,true);
sendData.send(null);
window.location = "dataFile.jsp";
})
});
///////////////////////////javascript file//////////////////////
<%# page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
String name = request.getParameter("na");
out.print(name);
%>
</body>
</html>
///////////////////jsp file
I think the problem is you're sending variable instead of va.
This line:
sendData.open('GET','dataFile.jsp?na='+variable,true);
Hope that is the root cause of your problem.

Having trouble passing data from JavaScript to PHP using POST method in ajax

I'm trying to implement the function of checking if the email is exists by using ajax, but my code works on my mac with MAMP while they don't work on my windows PC with XAMPP. Here is the register.php file:
<!doctype html>
<html lang="en" xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script type="text/javascript">
/**
* Created by PC2 on 15/12/2016.
*/
/** Create xmlHttpRequest Object */
function getXmlHttpObject() {
var xmlHttpRequest;
if(window.ActiveXObject){ //if the user's web browser is IE core
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}else{
xmlHttpRequest = new XMLHttpRequest();
}
return xmlHttpRequest;
}
var myXmlHttpRequest = "";
/** Check if the email address is exist or not */
function checkEmail() {
myXmlHttpRequest = getXmlHttpObject();
if(myXmlHttpRequest){
var url = "/Ajax-Check-Username-Clean-Code/Ajax/registerProcess.php";
var data = "email="+$('email').value;
myXmlHttpRequest.open("POST",url,true);
myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
myXmlHttpRequest.onreadystatechange = process; //process is a function
myXmlHttpRequest.send(data);
}else{
window.alert("Create Ajax Engine Fail!");
}
}
/** function to change the visibility of the div */
function process() {
if(myXmlHttpRequest.readyState == 4){
var mes = myXmlHttpRequest.responseText;
var mes_obj = eval("(" + mes + ")");
var mes_status = mes_obj.status;
}else{
window.alert("Error");
}
if(mes_status == "ok"){
$('message').textContent = "ok";
}else if(mes_status == "error"){
$('message').textContent = "Error";
}
}
function $(id) {
return document.getElementById(id);
}
</script>
<title>Check Username</title>
</head>
<body>
<section>
<form class="register-form">
<div class="register">
<h2>Email:</h2><input type="text" id="email" name="email-input" onkeyup="checkEmail();"><div class="text" id = "message"></div>
<h2>Password</h2><input type="password" class="password-input"><br/><br/>
<button class="submit">Sign Up</button>
</div>
</form>
</section>
</body>
</html>
And Here is the PHP file:
<?php
$email = $_POST['email'];
$mes = "";
if ($email == "songtao"){
$mes = '{"status":"error"}';
} else {
$mes = '{"status":"ok"}';
}
echo $mes;
?>
These code works well on my Mac, when I tried to run the code on windows, there is an error said "undefined index" in the php file ( $email = $_POST['email'] ), anyone has any ideas why this happened?

HTML file as the response to a POST request?

I have seen questions and answers regarding this issue. For example How to return a HTML file as the response to a POST request? but am having problems implementing the solutions. Here is a sample of some php code in a directory called websiteIssue that does not work, and I am not sure why.
index.php
<?php
if(isset($_POST['page']))
{
$page = $_POST['page'];
}
else
{
$page = "";
}
include 'case.php';
?>
case.php
<?php
$testLog = 'testLog.txt';
$fileHandle = fopen('testLog.txt', 'a');
fwrite($fileHandle, '$page = '.$page."\n";
switch($page)
{
case "screen2":
include 'screen2.php';
fwrite($fileHandle, 'including screen2.php'."\n");
break;
default:
include 'screen1.php';
fwrite($fileHandle, 'including screen1.php'."\n");
break;
}
fclose($fileHandle);
?>
screen1.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>screen1.php</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<button type="button" onClick=dataSubmit({page:"screen2"})> Screen 1 => Screen2</button>
<script>
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData= new FormData();
for(name in data)
{
formData.append(name, data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
</script>
</body>
</html>
screen2.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>screen2.php</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<button type="button" onClick=dataSubmit({page:"screen1"})> Screen 2 => Screen1</button>
<script>
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData= new FormData();
for(name in data)
{
formData.append(name, data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
</script>
</body>
</html>
On initial load it works as I expected, the html in screen1.php is shown in the browser, but when the button on the page is pressed the html remains the same, rather than changing to that in screen2.php
The output to testText.log is something like:
$page =
including screen1.php
$page = screen2
including screen2.php
As is might be obvious, I am a newbie to this, and hopefully there is some basic thing I have not done. The browser I am running it on is Firefox. Any help would be much appreciated.
Small note:I retyped the code by hand for this post, and have not run it (the machine running the webserver is not connected to the internet), hopefully there are no syntax errors, but I may have made a typo somewhere.
By including the php file you are responding to the javascript, but you arent actually using that response for anything. If redirecting to that page is what you want, you need to use location.assign on the response. To do that:
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData= new FormData();
// Redirects user to response when received.
xmlRequest.onreadystatechange=function{
if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
location.assign(xmlRequest.responseText);
}
};
for(name in data)
{
formData.append(name, data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
Based on the answer given by Felipe Souza I made the following modifications to allow the page to be dynamically modified rather than being a redirect. Thought I would share as it is another solution which some might be interested in.
index.php
<?php
if(isset($_POST['page']))
{
$page = $_POST['page'];
include 'case.php';
}
else
{
include 'base.php';
}
?>
case.php
<?php
switch($page)
{
case "screen2":
include('screen2.php');
break;
case "screen1":
include('screen1.php');
break;
default:
include('screen1.php');
break;
}
?>
base.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>base.php</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<div id="container" style="width:100%; height:100%">
<?php
if(!isset($_POST['page']))
{
$page = "";
include 'case.php';
}
?>
</div>
<script>
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData = new FormData();
xmlRequest.onreadystatechange=function()
{
if(xmlRequest.readyState==4 && xmlRequest.status==200)
{
document.getElementById("container").innerHTML = xmlRequest.responseText;
}
}
for(name in data)
{
formData.append(name, data[name]);
console.log(name + ":" + data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
</script>
</body>
</html>
screen1.php
<button type"button" onClick=dataSubmit({page:"screen2"})> Screen 1 => Screen 2</button>
screen2.php
<button type"button" onClick=dataSubmit({page:"screen1"})>Screen 2 => Screen 1</button>
There seem some potential advantages in that the amount of data sent for the new screens is smaller, and (not sure if it is useful) the structure of the website is more disguised. Anyway, it is based on the answer given by Felipe Souza and supplements it (shows a dynamic approach rather than a changing pages one). Just thought I would mention it, if that was what some were looking for.

Loop through XML attributes and elements with jQuery

I've searched most of the forums and can't find what I am looking for. I want to do the following:
XML file:
<vaardigheden>
<vaardigheid soort="techniek">HTML/CSS</vaardigheid>
<vaardigheid soort="techniek">PHP/MySQL</vaardigheid>
<vaardigheid soort="techniek">Javascript</vaardigheid>
<vaardigheid soort="Instrument">Drums</vaardigheid>
<vaardigheid soort="Instrument">Gitaar</vaardigheid>
</vaardigheden>
I would like to loop through the attributes and elements and get this result:
Techniek
HTML/CSS
PHP/MySQL
Javascript
Instrument
Drums
Guitar
Does anyone have an idea how to achieve this? Just need the basic understanding of looping through attributes and elements in this way with jQuery.
DEMO
Using parseXML and each - NOTE the script will work on either a string as here or an ajaxed file.
var xml = '<vaardigheden> <vaardigheid soort="techniek">HTML/CSS</vaardigheid> <vaardigheid soort="techniek">PHP/MySQL</vaardigheid><vaardigheid soort="techniek">Javascript</vaardigheid><vaardigheid soort="Instrument">Drums</vaardigheid><vaardigheid soort="Instrument">Gitaar</vaardigheid></vaardigheden>',
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$vaardigheden = $xml.find( "vaardigheid" );
var currentSoort = "", content = $("#content");
$.each($vaardigheden,function(i,item) {
var soort = $(this).attr('soort');
if (soort != currentSoort) {
content.append("<dt>"+soort+"</dt>");
currentSoort = soort;
}
content.append("<dd>"+$(this).text()+"</dd>");
});
Hope this helps :)
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>XML JQUERY Example</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function(){
function parseXml(xml)
{
var titles = [];
var newL ;
$(xml).find("vaardigheid").each(function()
{
if (jQuery.inArray($(this).attr("soort"), titles)==-1){//append new title
newL = '<label>'+$(this).attr("soort")+'</label><br/>';
var newList = '<ul id="' + $(this).attr("soort") + '" \><li>'+$(this).text()+'</li></ul>';
$("#output").append($(newL));
$("#output").append($(newList));
titles.push($(this).attr("soort"));
}
else{
var newItem = '<li>'+$(this).text()+'</li>';
$("#"+$(this).attr("soort")).append($(newItem));
}
});
}
$.ajax({
type: "GET",
url: "myFile.xml",
dataType: "xml",
success: parseXml
});
});
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>

Categories