I am trying to make -
an android WEB application
with phonegap
layout with JqueryMobile
What Im doing -
An html form that takes ID, name, and address as input
'Serialize's this data using ajax
makes a json object out of it
Should send it to a file called 'connection.php'
Where, this data is put into a database (MySql)
Other details -
My server is localhost, Im using xampp
I have already created a database and table using phpmyadmin
The problem -
My html file, where my json object is created, does not connect to the php file which is hosted by my localhost
Here is my COMPLETE html file:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<!-- Change this if you want to allow scaling -->
<meta name="viewport" content="width=default-width; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html;charset=utf-8">
<title>Trial app</title>
<link rel="stylesheet" href="thestylesheet.css" type="text/css">
<script type="text/javascript" charset="utf-8" src="javascript1.js"></script>
<script type="text/javascript" charset="utf-8" src="javascript2.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova-1.8.0.js"></script>
<script>
$(document).ready(function () {
$("#btn").click( function() {
alert('hello hello');
$.ajax({
url: "connection.php",
type: "POST",
data: {
id: $('#id').val(),
name: $('#name').val(),
Address: $('#Address').val()
},
datatype: "json",
success: function (status)
{
if (status.success == false)
{
alert("Failure!");
}
else
{
alert("Success!");
}
}
});
});
});
</script>
</head>
<body>
<div data-role="header">
<h1>Heading of the app</h1>
</div><!-- /header -->
<div data-role="content">
<form id="target" method="post">
<label for="id">
<input type="text" id="id" placeholder="ID">
</label>
<label for="name">
<input type="text" id="name" placeholder="Name">
</label>
<label for="Address">
<input type="text" id="Address" placeholder="Address">
</label>
<div id="btn" data-role="button" data-icon="star" data-theme="e">Add record</div>
<!--<input type="submit" value="Add record" data-icon="star" data-theme="e">
-->
</form>
</div>
</body>
</html>
And here is my 'connection.php' hosted by my localhost
<?php header('Content-type: application/json');
$server = "localhost";
$username = "root";
$password = "";
$database = "jqueryex";
$con = mysql_connect($server, $username, $password);
if($con) { echo "Connected to database!"; }
else { echo "Could not connect!"; }
//or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
/*
CREATE TABLE `sample` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
`Address` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
)
*/
$id= json_decode($_POST['id']);
$name = json_decode($_POST['name']);
$Address = json_decode($_POST['Address']);
$sql = "INSERT INTO sample (id, name, Address) ";
$sql .= "VALUES ($id, '$name', '$Address')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Comment added";
}
mysql_close($con);
?>
My doubts:
No entry is made in my table 'sample' when i view it in phpmyadmin
So obviously, i see no success messages either
I dont get any errors, not from ajax and neither from the php file.
Stuff Im suspecting:
Should i be using jsonp instead of json? Im new to this.
Is there a problem with my php file?
Perhaps I need to include some more javascript files in my html file?
I assume this is a very simple problem so please help me out! I think there is just some conceptual error, as i have only just started with jquery, ajax, and json.
Thank you.
A FEW EDITS:
I was getting the following syntax errors:
Connected to database!
Notice: Undefined index: id in C:\xampp\htdocs\connection.php on line 28
Notice: Undefined index: name in C:\xampp\htdocs\connection.php on line 31
Notice: Undefined index: Address in C:\xampp\htdocs\connection.php on line 34
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' '', '')' at line 1
So i changed my code to
if (isset($_POST['id']))
$id= json_decode($_POST['id']);
if (isset($_POST['name']))
$name = json_decode($_POST['name']);
if (isset($_POST['Address']))
$Address = json_decode($_POST['Address']);
Still getting the same errors
Please help!
As you're using android so direct connection.php won't work, here is the general method to get this done:
http://www.mobitechie.com/android-2/how-to-access-localhost-on-android-over-wifi/
After you setup things given in above link, the network address you'll get will be something like 10.0.0.2 then change your server to http://10.0.0.2/connection.php where connection.php is placed in htdocs directory.
Above step is necessary because android treats localhost as its own device localhost and doesn't pick the system's localhost directly.
Comment under this answer further to ask if you have more issues.
You can use JSONP for ajax request in Phonegap. But for that, you have to use Cross domain request to the server page using JSONP. Here you have to use callback method.
Just go through my post $.ajax() on phonegap.
And one more thing, dont make request from android to the localhost. Just put your file in webserver and try to make request.
Please change this script from :
$sql = "INSERT INTO sample (id, name, Address) ";
$sql .= "VALUES ($id, '$name', '$Address')";
To:
$sql = "INSERT INTO sample (id, name, Address) ";
$sql .= "VALUES ('$id', '$name', '$Address')";
Add the character ' around $id
Related
I created a google sign in using Google OAuth 2.0, I configure it using Xamp and php to build the database, I built it outside my project, now I want to include the google sign in button in my project but I kept getting errors. From my localhost, I want to add it to my file first and see how it would look in my page before uploading it. Below is my index.php file
<?php
require_once('config.php');
require_once('core/controller.Class.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="uft-8">
<meta name="viewport" content="width=device-width, inital-scale=1">
<title>Login with Google</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" >
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
</head>
<body>
<div class="container" style="margin-top: 100px">
<?php
if(isset($_COOKIE["id"]) && isset($_COOKIE["sess"])){
$Controller = new Controller;
if($Controller -> checkUserStatus($_COOKIE["id"], $_COOKIE["sess"])){
echo $Controller -> printData(intval($_COOKIE["id"]));
echo 'Logout';
}else{
echo "Error!";
}
}else{
?>
<img src="img/20210908_214559.jpg" alt="Logo"
style="display: table; margin: 0 auto; max-width: 150px;">
<form action="" method=:POST>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="email" class="form-control" id="exampleInputEmail1"
placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1"
placeholder="Enter password">
</div>
<button type="submit" class="btn btn-primary">Login</button>
<button onClick="window.location = '<?php echo $login_url;?>'" type="button" class="btn btn-danger">Login with Google</button>
</div>
</form>
<?php } ?>
</body>
</html>
It looks like you're expecting to collect the google username and password and then pass that to the google auth engine? That's not the way I've implemented the solution.
Google provide instructions for integrating their sign-in service.
I recommend following those instructions. This will require the following files:
A login page which contains the google sign-in button. You could conceivably add this to any of your existing pages. The relevant code is:
<div class="g-signin2" data-longtitle="true" data-onsuccess="onSignIn"></div>
A javascript file which contains the onSignIn function and a signOut function if you want one. This file handles the redirect to a successful logged in page and also passes the attributes you want to collect from the user's Google account. I'm using XMLHttpRequest, but you could use POST if you wish. This page contains the page that the user will be directed to upon successful login, set in xhr.onreadystatechange = function() {}:
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id_token = googleUser.getAuthResponse().id_token;
// console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
var xhr = new XMLHttpRequest();
xhr.open('POST', 'includes/oauth.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
window.location = "../loggedin.php"; //Redirect to loggedin page on completion of oauth.php. Determine if new user or existing user and process accordingly
}
xhr.send('idtoken=' + id_token + '&googleId=' + profile.getId() + '&name=' + profile.getName() + '&imageURL=' + profile.getImageUrl() + '&email=' + profile.getEmail());
}
function signOut() {
gapi.load('auth2', function() {
gapi.auth2.init().then(function(){
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
document.location.href = 'includes/logout.php';
});
});
});
}
A file to handle the authentication (referred to as includes/oauth.php in my javascript file above). Note the settings for $leeway - this caused me a lot of grief figuring out that the clock on my server was slower than the Google auth server's clock!):
require_once '../vendor/autoload.php';
$jwt = new \Firebase\JWT\JWT; //Allow for discrepancies between server and auth times
$jwt::$leeway = 60;
$CLIENT_ID = "ENTER_YOUR_CLIENT_ID_HERE";
$client = new Google_Client(['client_id' => $CLIENT_ID]); // Specify the CLIENT_ID of the app that accesses the backend
$client->setRedirectUri("http://localhost/includes/oauth.php");
$client->addScope("email");
$client->addScope("profile");
if (isset($_POST['idtoken'])){
$id_token = $_POST['idtoken'];
$attempt = 0;
do {
try {
$payload = $client->verifyIdToken($id_token);
$retry = false;
} catch (Firebase\JWT\BeforeValidException $e) {
error_log("JWT server time mismatch. Retry attempt: " . strval($attempt) . "Error: " . $e, 0);
$attempt++;
$retry = $attempt < 3;
}
} while ($retry);
if ($payload) {
$userid = $payload['sub'];
...
YOUR VALIDATION, SESSION SETTING, ETC. CODE HERE
...
} else {
// Invalid ID token
print("Invalid ID token");
}
} else { //Attempt to access this page directly, redirect to Google login page
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
}
The page that will displayed upon successful login. I used an interstitial page here because the authenticated user could be new to my site and need to create a profile, or could be an existing user and want to go about their activities. I look to verify whether a SESSION has been started and whether this includes a successful authentication.
I'm trying to make some php message sender and receiver Pages.
From the "Admin.php" page, administrator can send messages to the website visitors. And the "receiver.php" page is the visitor's inbox.
Here is the codes:
Admin.php:
<form method="post" action="sender.php">
<input type="text" name="message">
<input type="submit" value="Submit">
</form>
Sender.php:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$message = $POST["message"];
echo "data: {$message}\n\n";
flush();
?>
Receiver.php:
<!DOCTYPE html>
<html>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("sender.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
why doesn't this work?
The problem is that you are trying to use "sender.php" to do two things.
From the admin form you need to submit to one php script that will store the messages, in a database of some kind.
Then in "receiver.php" you need to connect to a different PHP script, whose job is to keep polling that database for new entries, and when it sees one it should send it to the client. This latter PHP script will run in an infinite loop.
Hello guys my friend using a trick his upload cookies on his side sometime visitor click on log out button then cookies
not work his create a cookies activator please anyone tell me how its done this
i Just trying to say like this
set cookies(my target side like example.com )
how to log in on anyone using my username password using my HTML page
without knowing my account detail ....
So, first of all you need to make a page that'll set a cookie. For example consider this file named setCookie.php:
<?php
setcookie("user", "Alex Porter", time()+3600);
Now in your regular page HTML button:
<button id="cookieSetter">Set Cookie</button>
Now using jQuery send an AJAX request to setCookie.php file:
$('#cookieSetter').click(function(e) {
e.preventDefault();
$.ajax({
type: "GET",
url: "setCookie.php.php"
});
});
<?php
// you should start the session before any html
session_start();
// Creating some session variables like this
$_SESSION['pseudo'] = 'pseudo';
$_SESSION['password'] = 'password';
setcookie('pseudo', 'whatever', time() + 365*24*3600, null, null, false, true); // Setting up a cookie
setcookie('location', 'Russia', time() + 365*24*3600, null, null, false, true); // Just another one...
// And only after that you cant write html code.
?>
<!DOCTYPE html>
<html>
<head>
<title>Your page Title</title>
</head>
<body>
<p>
Hello <?php echo $_SESSION['pseudo']; ?> !<br />
You are in (login.php).
</p>
<p>
Hey ! I remember you !<br />
Your name is <?php echo $_COOKIE['pseudo']; ?> and you are located in <?php echo $_COOKIE['location']; ?> is that true?
</p>
<p>
Log out<br />
</p>
</body>
</html>
I think the problem is in the "aif.php" file"
I am trying to fetch and display an array using PHP but the HTML element <br> is showing up in my result from the following scrip. I know I have to escape the HTML tags but I'm just not sure how! Also, any other advice on this code would be greatly appreciated (i.e. is there any redundancy or areas to improve? Thanks.
HTML
<DOCTYPE! html>
<html>
<head>
<title>The Auditors' Report: Data Entry</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<header><h1>Work Station<h1></header>
<div = id="leftnav">
<h2>Select Action</h2>
Name: <input type="text" id="name">
<input type="submit" id="grab" Value="Grab">
</div>
<div id="content"></div>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="aif.js"></script>
</body>
</html>
PHP - config (filename: "config.php")
<?php
$dbhost = "localhost";
$dbname = "x";
$dbuser = "y";
$dbpass = "z";
$dsn = "mysql:host=$dbhost;dbname=$dbname";
$dbh = NULL
?>
PHP - query / resulting content (filename: "aif.php")
<?php
require "config.php";
$dbh = new PDO($dsn, $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = "SELECT * FROM table1 LIMIT 0,10";
$sth = $dbh->prepare($sql);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo $row['field1'],"<br>";
echo $row['field2'],"<br>";
echo $row['field3'],"<br>";
}
?>
Javascript
$('input#grab').on('click', function() {
var name = $('input#name').val();
if ($.trim(name) !='') {
$.post('aif.php', {name: name}, function(data) {
$('div#content').text(data);
});
}
});
If you want to html encode a line like this:
this is <br /> a test
into a line like this:
this is <br /> a test
Use the nifty little function described here: HTML-encoding lost when attribute read from input field
I made a simple error in the Javascript. I wanted to pass back HTML and not TEXT.
With the following change, the PHP is rendered properly:
$('div#content').text(data);
to
$('div#content').html(data);
I'm a beginner in jQuery area and I have simple question like this :
I want to load (AJAX) MySQL result in array, let's say :
$row[0] = first name
$row[1] = last name
$row[2] = phone number
I have no problem with PHP part, but I have difficulties to display each of that array content on different id. because syntax I found loads everything processed by PHP :
<script type="text/javascript">
$(document).ready(function(){
$('#mysql-result').load('ajax.php');
});
</script>
how to get 'First Name', 'Last Name' and 'Phone Number' from PHP with only one time load and still I can put the result in different . thank you.
UPDATE
I give you real example about what I need. Here's my HTML file named ajax.html :
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Ajax Trial</title>
</head>
<body>
<div id = "fistname"><!-- ajax result goes here --></div>
<div id = "lastname"><!-- ajax result goes here --></div>
<div id = "phonenumber"><!-- ajax result goes here --></div>
</body>
</html>
and here's my PHP file, named ajax.php :
<?php
require_once 'config-min.php';
$con = mysql_connect($DbServer,$DbUser,$DbPassword);
mysql_select_db($DbName, $con);
$result = mysql_query("SELECT FirstName, LastName, PhoneNumber FROM User WHERE ID = '201' LIMIT 1");
$row = mysql_fetch_array($result);
echo $row[0];
echo $row[1];
echo $row[2];
mysql_close($con);
?>
now, my question still same... how to get this PHP result (3 echos), load once, then displayed in those 3 different divs
I too wanted to do something like you wish to.And I did the following code and It worked. Hope this helps you too.
<script type="text/javascript" src="/jquery.js"></script>
<script>
$(document).ready(function(){
$("#form_plat").submit(function(e){
var str = $(this).serialize();
row[0]=$('#First_name').val();
row[1]=$('#last_name').val();
row[2]=$('#phonenumber').val();
$.ajax({
type: "POST",
url : 'Insert_Into.pl', //if you wish to store in database
data : {'firstname_name':row[0],'last_name': row[1],'phonenumber':row[2]},
beforeSend: function() {
console.log("hey i am here");
},
success: function(){
$('#note').html('Thank you for your submission!');
$('#note').hide();
$("#fields").fadeOut('slow');
}
});
return false;
});
});
</script>);
Have you tried adding to your php code:
echo $firstname.' '.$lastname.' '.$phonenumber;