I want to retrieve data from a database which is locally installed.
But the website is written and controlled with js, so I have to send an ajax request to a php-file, which then connects to the database, sends the query and later the result back to js.
I have a couple of files, because i followed this tutorial from 2012: https://www.youtube.com/watch?v=Yb3c-HljFro
The structure:
|-ajax (Folder)
| |-pkmn.php
|-db (Folder)
| |-connect.php
|-js (Folder)
| |-global.js
|-index.php
The files:
index.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"></meta>
</head>
<body>
Type: <input type="text" id="type"></input>
Tier: <input type="text" id="tier"></input>
<input type="submit" id="submit" value="Suchen"></input>
<div id="pkmn-data"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="js/global.js"></script>
</body>
</html>
global.js:
$("#submit").click(function () {
var type = $("type").val();
$.ajax("ajax/pkmn.php", {type: type}, function(data) {
alert(data);
});
});
connect.php
<?php
mysql_connect('localhost','root', '123456');
mysql_select_db('database');
pkmn.php:
<?php
echo 'Hello';
The user should enter something into the text-inputs, then click submit and the global.js-file sends that text to the file pkmn.php via an ajax request.
But when I click the submit-button, I receive an error:
XML-Verarbeitungsfehler: Ungeschlossenes Token
Adresse: file:///C:/Users/Jonathan%20Frakes/Documents/testDB/ajax/pkmn.php
Zeile Nr. 1, Spalte 1: pkmn.php:1:1
XML-Verarbeitungsfehler: Ungeschlossenes Token
Adresse: file:///C:/Users/Jonathan%20Frakes/Documents/testDB/index.php
Zeile Nr. 1, Spalte 1: index.php:1:1
Which says something like:
XML-Parseerror: unclosed token
at: file:///C:/Users/Jonathan%20Frakes/Documents/testDB/ajax/pkmn.php
Row 1, Column 1: pkmn.php
XML-Parseerror: unclosed token
at: file:///C:/Users/Jonathan%20Frakes/Documents/testDB/ajax/index.php
Row 1, Column 1: index.php
I have absolutely no idea, what could cause this error.
Furthermore: When I close the php-tag in pkmn.php the console says BOTH errors moved to Row 3 Column 3 and when I close the php-tag one line later (by adding another newline) the error again moves in both files one down. I can also add spaces in front of the closing tag, moving the errors horizontally.
I have never seen something like this before, so please help me to fix that.
Best regards,
PanCave
EDIT:
changing the global.js according to this tutorial (https://www.w3schools.com/php/php_ajax_database.asp) now produces an "no root element found" error :/
$("#submit").click(function () {
var type = $("#type").val();
var tier = $("#tier").val();
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
document.getElementById("pkmn-data").innerHTML = this.responseText;
}
};
xmlhttp.open("Get", "pkmn.php?type="+type+"&tier="+tier);
xmlhttp.send();
});
Related
want to create a fully dynamic chat UI for my website, But it reloads the whole page if a person submits the button page should not reload like many chat website.
<form action="action.php" method="post" id="formpost">
<input type="text" id="input" value="php echo">
<input type="submit" value="send">
</form>
I want to submit this form through ajax and show the last xml <message> containing <message>talk 123<message>
<messages category="short">
<person1>
<time>
r
<message>Djssjs</message>
</time>
</person1>
<person2>
<time>
r
<message>1234fdg</message>
</time>
</person2>
<person1>
<time>
r
<message> talk 123</message>
</time>
</person1>
</messages>
i want to show that talk 123 in the html document bit confused how to do that
//for form submit
$("#formpost").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: action.php,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
//for xml
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "name.xml", true);
xhttp.send();
}
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var msg = "";
//how to select the last person's of the <messages> child
msg = getElementsByTagName("messages").lastChild.childNodes[1].nodeValue ;
document.getElementById("demo").innerHTML = msg;
}
$("#formpost").on('submit', function(event){
event.preventDefault();
// rest of your ajax code here...
});
Points to note
1. Make sure you have also added JQuery script source on the head tag of your chat page.
2. Make sure to put preventDefault() immediately before any other code is executed.
You can use reverse ajax method pulling data from the server.
In reverse ajax a request is auto-generated at a certain time interval or hold the request for fetching new message.
There are three technologies for reverse ajax:-
Piggyback
Polling
Comet
I have a server which I am storing standard text inputs once a submit button has been clicked, I have done this successfully and now need to recall all the inputs on a different button click. My lack of understanding of PHP starts to kick me as I have little to no idea how to retrieve this, I know that data within PHP files once ran is deleted so I need to create some sort of "storage" ( I found the use of $_SESSION to be the go to thing for this).
I then need to use my JS file to somehow recall the data that is temporarily stored but again have no idea how I can get an array that is stored on a PHP file across to a JS file.
Any brief explanation oh how this is done would be greatly appreciated as I am extremely new to PHP!
For reference I currently have:
JS:
function writeDoc() {
var xhttp = new XMLHttpRequest();
var url = "gethint.php";
var input = document.getElementById("text").value;
var clicker = document.getElementById("submit");
xhttp.open("POST", "gethint.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
alert("Form Was Submitted");
// var returnData = xhttp.responseText;
}
}
xhttp.send("input= " + input);
}
function readDoc() {
var xxhttp = new XMLHttpRequest();
xxhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
alert("Data retrieved")
// var returnData = xhttp.responseText;
}
}
xxhttp.open("GET", "gethint.php", true);
xxhttp.send();
}
HTML:
<body>
<label>Text Input To Save: </label>
<br></br>
<textarea rows="6" cols="20" id="text" name="textInput"></textarea>
<input type="submit" id="submit" onclick="writeDoc()">
<br></br>
<label>Retrieve Text :</label> <input type="button" id="getText"
onclick="readDoc()">
</body>
PHP:
<?
session_start();
echo $_SESSION["input_data"] = $_POST;
print_r($_POST);
echo "Text Submitted". $_POST["input"];
print_r($_REQUEST);
echo "Text Retrieved" . $_REQUEST["input"];
?>
In your php you can encode the post data as json like so:
$_SESSION['input_data'] = json_encode($_POST);
And in your js you can the get the data by decoding it like so:
var data = JSON.parse('<?php echo $_SESSION["input_data"]; ?>');
This will give you a js object that you can access using the name you gave your input tags in your html.
ex: data.textInput would get that value of the textarea.
To easily access the php data in js , you can store the data in session.also use json format to throw data to js and access it in js via jeson array key value format if you have multiple form field to store and access.
Use json_encode() to throw from php to js.
Also you can save this data in cookie. Session and cookie are temporary way to store data. For permanent storage use a database like mysql and call this from js with json.
I'm trying to make a client-server application where from the client I send a request through a JSON object to the server to register. The thing is I should get another JSON with an "OK" field (which is actually being sent) but for some reason the client keeps going to the .fail function instead of the .done one (sorry if some of used terms are not very accurate, I'm new to this).
So I'll this is my code incase you can check if there's anything wrong causing this:
Client JS:
define(['ojs/ojcore', 'knockout', 'jquery', 'appController', 'jquery', 'ojs/ojknockout', 'ojs/ojinputtext'],
function(oj, ko, $, app) {
function RegistrarseViewModel() {
var self = this;
this.email = ko.observable();
this.pwd1 = ko.observable();
this.pwd2 = ko.observable();
this.registrar = function(){
alert("Se ha mandado el registro");
var p = {tipo:"Registrarse",email: this.email(), pwd1:this.pwd1(), pwd2:this.pwd2()};
$.ajax({
type:"POST",
url:"http://localhost:8080/ServidorWeb/Registrarse.jsp",
data: "p=" + JSON.stringify(p)
}).done(function(data, textStatus, jqXHR){
alert("Comprobando tipo");
if (data.tipo == "OK"){
//window.location="index.html?root=juegos"
sessionStorage.jugador=self.email();
app.router.go("login");
alert("Registro correcto");
}else
alert(respuesta.texto)
}).fail(function() {
alert("Sorry. Server unavailable. lol ");
});
}
this.cancelar = function(){
app.router.go("login");
}
}
return new RegistrarseViewModel();
}
);
Server JSP:
<%# page language="java" contentType="application/json ; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import= "org.json.*,dominio.Manager"%>
<%
String p = request.getParameter("p");
JSONObject resultado=new JSONObject();
try{
JSONObject jso= new JSONObject(p);
if(!jso.getString("tipo").equals("Registrarse")){
resultado.put("tipo","NOK");
resultado.put("texto","Mensaje inesperado");
}else{
String email=jso.getString("email");
String pwd1=jso.getString("pwd1");
String pwd2=jso.getString("pwd2");
Manager.get().registrarse(email,pwd1,pwd2);
resultado.put("tipo","OK");
resultado.put("texto","Te has registrado con el email " + email);
}
}
catch(Exception e){
resultado.put("tipo","NOK");
resultado.put("texto","Mensaje Inesperadoo");
}
%>
<%=resultado.toString()%>
After executing Manager.get().registrarse(email,pwd1,pwd2); (which is the logic to register into a MongoDB) it just continues with the resultado.put("tipo","OK"); line which means the problem isn't in there.
Also if I send the request http://localhost:8080/ServidorWeb/Registrarse.jsp?p=%7Btipo:%22Registrarse%22,email:%2233%22,pwd1:%2220%22,pwd2:%2220%22%7D from a browser like Google Chrome it prints this: {"texto":"Te has registrado con el email 33","tipo":"OK"} but from the real client it just won't get into the .done function, idk why.
I really hope you can help me.
Thanks in advance.
EDIT 1: Added the server response from the browser console IMAGE
Okay I solved this finally.
I had to add this line at the beggining of the .jsp, this was an issu with TomCat which has something like 2 machines and without this line it doesn't allow communication among different machines because of security reasons it seems.
response.setHeader("Access-Control-Allow-Origin", "*");
if you use jquery the correct way is use serialize function from jquery
https://api.jquery.com/serialize/
first give a id for you form something like :
`
$("#myform form").submit(function(event){
event.preventDefault();
var sendData = $("#myform form").serialize();
$.post("your-PHP-handler.php", sendData);
});
<form id="myform" method="post" action="your-PHP-handler.php">
<input type="name" placeholder="name">
<input type="name" placeholder="age">
<input type="name" placeholder="address">
<button type="submit">send</button>
</form>
`
note when you submit your form via javascript the serialization jquery get all inputs in your post end send all together you cam handler the response php inside of $.post() you can make many things with this consulting jquery documentation.
anyway the basic is there , get everything inside my form and send to my php file
I copied the code from a YouTube tutorial, modified the database connection and SELECT items to connect to my existing DB, but I can't seem to get the JS to load the PHP file. In Chrome using the "inspect" tool, I can see that the JS file is loading, but when I click on GRAB on my HTML page, it doesn't do anything. Almost like the JS file is loading but not running.
Webserver folder structure:
ROOT FOLDER
test.html
-AJAX (folder)
name.php
-JS (folder)
global.js
-CONNECTIONS (folder)
dbase.php
HTML CODE
<!doctype html>
<html>
<head>
<title>AJAX Database</title>
</head>
<body>
Name: <input type="text" id="name">
<input type="submit" id=name-submit" value="Grab">
<div id="name-data"></div>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script src="js/global.js"></script>
</body>
</html>
Javascript File
$('input#name-submit').on('click', function() {
var name = $('input#name').val();
if ($trim(name) != '') {
$.post('ajax/name.php', {name: name}, function(data) {
$('div#name-data').text(data);
});
}
});
PHP File
First try to add a console.log('something') inside your javascript click function, right before the var name =... line, to see that your event is even firing. If not you need to register the event properly. Is the click function surrounded by
$(document).ready(function () {
$('input#name-submit').on('click', function() {
var name = $('input#name').val();
if ($trim(name) != '') {
$.post('ajax/name.php', {name: name}, function(data) {
$('div#name-data').text(data);
});
}
});
});
//try using submit event
$(document).ready(function () {
$('input#name-submit').on('submit', function(e) {
e.preventDefault();
var name = $('input#name').val();
if ($trim(name) != '') {
$.post('ajax/name.php', {name: name}, function(data) {
$('div#name-data').text(data);
});
}
});
});
I'm not sure why my PHP code was edited and removed from here, but I've ended up re-writing the whole PHP page. I added or die(mysql_error()); to my SELECT statement and found that it needed me to specify my database in the FROM. I have multiple databases on my server and even though the DB is specified in the connection string it needed it again in the SQL Statement. The next problem I resolved was removing the mysql_num_rows as this was just not working like the demo did.
ORIGINAL PHP
<?PHP
if (isset($_POST['name']) === true && empty ($POST['name']) === false) {
require '../db/connect.php';
$query =mysql_query("
SELECT 'names'.'location'
FROM 'names'
WHERE 'names'.'name' = '" . mysql_real-escape_string(trim($_POST['name'])) . "'
");
echo (mysql_num_rows($query) !== 0) ? mysql_result($query, 0, 'location') : 'Name not found';
}
?>
The original was far too complicated for what I wanted and also for me to problem solve it so I re-wrote it:
NEW PHP FILE
<?PHP
//I've intentionally left out the connection data..
$sql_select = mysql_query("
SELECT names.location
FROM database_name.names
WHERE names.name = '" . $_POST['name'] . "'
")
or die(mysql_error());
$sql_fetch = mysql_fetch_assoc($sql_select);
echo $sql_fetch['name'];
?>
Thanks to those that assisted. Appreciated...
I am aware of the deprecated tags in the PHP file, but when I was copying from a demo so I wanted to get it working before updating it with new tags.
I have struggled with this task for so long that I am hoping for a reprieve.
We have a web service called Validate on a separate server/domain.
Due to same domain restrictions, I came up with proxy server (code) to work around it.
The code below called Validate.asp, points to the webservice:
Set http = Server.CreateObject("msxml2.ServerXMLHTTP")
http.Open "POST", "http://servername1/folder1/folder2/folder3/Validation/Validate", False
http.setRequestHeader "Content-type","application/x-www-form-urlencoded"
http.Send Request.Form
Response.Write http.ResponseText
Response.End
%>
Then the code markup below invokes Validate.asp.
<!DOCTYPE html>
<html>
<body>
<form>
Enter name: <input id="user" /><br/>
Enter Pass: <input id="pass" /><br/>
<input type="button" value="Get web response via AJAX" onclick="ajaxViaProxy()" />
</form>
<hr/>
Ressponse: <div id="result"></div>
<script type="text/javascript">
function ajaxViaProxy( )
{
var uname = document.getElementById("user").value;
var upass = document.getElementById("pass").value;
var http = new XMLHttpRequest();
http.open("POST", "Validate.asp", true );
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
http.onreadystatechange=function()
{
if (http.readyState==4 && http.status==200)
{
document.getElementById("result").innerHTML =
"Response from web server was '" + http.responseText + "'";
}
}
http.send("username=" + encodeURIComponent(uname)
+ "&password=" + encodeURIComponent(upass));
}
</script>
</body>
</html>
If everything goes well, we should get response similar to this one below:
{"Value":{"TokenId":35,"LoginName":"validUser","Created":"2013-12-03T09:53:35","Expires":"2013-12-24T09:53:35","LastUsed":"2013-12-03T09:53:35"},"Status":0,"Message":null}
This is the exact response we get when I paste the code below into an address bar and hit the enter key:
http://servername/folder1/folder2/folder3/Validation/Validate?data={"User":"validUserName","Password":"validPassword"}
However, when I use the markup to invoke proxyValidate.asp, rather than get the response with token, I get the following:
{"Value":null,"Status":2,"Message":"Invalid username or password"}
Does anyone know what I need to change in the markup or in proxyValidate.asp so that when I run the code, I get a properly formatted URL string like this below?
http://servername/folder1/folder2/folder3/Validation/Validate?data={"User":"validUserName","Password":"validPassword"}
Thanks alot in advance