I am trying receive the JSON data using PhoneGap application. I am using server xampp php server. On this server I have server code api.php for receiving data from database. My laptop's IP address is 192.168.1.4 so the URL of this local server is http ://192.168.1.4/Experiements/webservices/api.php".
I am able to receive the data using
alert(JSON.stringify(response));
but I want to add this _email_id_ information to
<div id="email">Email_id< /div >
which is defined in index.html.
From my Android phone I want to just log in and and receive the email_id of that user. Please see the image of my database and and data receive on my phone using
alert(JSON.stringify(response)).
My server code is api.php
<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
mysql_connect("localhost","root","1234");
mysql_select_db("demo");
if(isset($_GET['type']))
{
if($_GET['type']=="login"){
$username=$_GET['UserName'];
$Password=$_GET['Password'];
$query="Select * from registration where UserName='$username' and Password='$Password'";
$result=mysql_query($query);
$totalRows=mysql_num_rows($result);
if($totalRows>0){
$recipes=array();
while($recipe=mysql_fetch_array($result, MYSQL_ASSOC)){
$recipes[]=array('User'=>$recipe);
}
$output=json_encode(($recipes));
echo $output;
}
}
}
else{
echo "Invalid format";
}
My PhoneGap application code is in index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="format-detection" content="telephone=no"/>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<title> Database Application</title>
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, width=device-width">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, target-densitydpi=medium-dpi, user-scalable=0" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.js"></script>
<script>
$(document).ready(function(){
$("#btnLogin").click(function(){
var userId = document.getElementById('id').value;
var userPassword = document.getElementById('password').value;
$.ajax({
url:"http://192.168.0.106/Experiements/webservices/api.php",
type:"GET",
dataType:"json",
data:{type:"login", UserName:userId,Password:userPassword},
ContentType:"application/json",
success: function(response){
alert(JSON.stringify(response));
console.log(JSON.stringify(response));
var userEmail = response[0].User.email; // Find the email from the JSON
var emailDiv = $("div#email"); // Find the div for email with jQuery selector
emailDiv.text(userEmail); // Put user's email as text to that div
},
error: function(err){
alert(JSON.stringify(err));
}
})
});
});
</script>
<script type="text/javascript">
document.addEventListener("deviceready",OnDeviceReady,false);
function OnDeviceReady(){
//alert("cordova is loaded");
}
</script>
</head>
<body>
User ID : <input type="text" id="id" name="user" />
User Password : <input type="text" id="password" name="password" />
<input type="button" id="btnLogin" name="btnLogin" value="Login"/>
<div id="email">Email_id</div>
</body>
</html>
DataBase: demo, user: root, password: 1234, table: registration
Screen shot of my phone:
So if I understood you correctly, what you want to do is to get the email_id from the response and put the content into the div called email.
What you need to do is to first get the user's email from the JSON object which is in your case Array with just one item. This first item of array again is Object which contains field called email which is exactly what we want. After that we need to locate the div from the DOM with jQuery element selector and insert the user's email in it. Example is found below.
var userEmail = response[0].User.email; // Find the email from the JSON
var emailDiv = $("div#email"); // Find the div for email with jQuery selector
emailDiv.text(userEmail); // Put user's email as text to that div
Related
There is a brand new drawing pad (pen tool) plugin from Jquery found in that link:
https://www.jqueryscript.net/other/signature-draw-pad.html.
As it is new I cannot see how to transform it into image to save it to database with php.
I cannot find any explanation on how to use this plugin for that purpose.
Anyone has information on how to do that ?
Thank you !!
A little inspect/devtools shows that the doodle/image/drawing is stored in html canvas element.
You can get the content of html canvas element with toDataURL() function.
Here is MDN docs: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL
Example: var base64Image = $("#target canvas").get(0).toDataURL();
You can then post it (example: via ajax, via form post, etc) to your backend and store the base64 in database.
Here is example snippet
$(document).ready(function() {
// set background
var urlBackground = 'https://picsum.photos/id/100/500/400';
var imageBackground = new Image();
imageBackground.src = urlBackground;
//imageBackground.crossorigin = "anonymous";
imageBackground.setAttribute('crossorigin', 'anonymous');
$("#target").drawpad();
var contextCanvas = $("#target canvas").get(0).getContext('2d');
imageBackground.onload = function(){
contextCanvas.drawImage(imageBackground, 0, 0);
}
// post the base64 image to some endpoint
$("#saveToDatabase").click(function() {
var base64Image = $("#target canvas").get(0).toDataURL();
console.log(base64Image);
$("#outputBase64FormInput").val(base64Image);
$("#outputBase64").html(base64Image);
});
// form submit
$("#myform").submit(function() {
var base64Image = $("#target canvas").get(0).toDataURL();
console.log(base64Image);
$("#outputBase64FormInput").val(base64Image);
$("#outputBase64").html(base64Image);
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://cnbilgin.github.io/jquery-drawpad/jquery-drawpad.css" />
<style>
body {background-color:rgb(248, 255, 227)}
#target {
width:500px;
height:400px;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cnbilgin.github.io/jquery-drawpad/jquery-drawpad.js"></script>
</head>
<body>
<button id="saveToDatabase">Save Drawing</button>
<div id="target" class="drawpad-dashed"></div>
<div id="outputBase64"></div>
<form id='myform' method="POST">
value1 <input id='value1' name='myvalue1' />
value2 <input id='value2' name='myvalue2' />
<input type='hidden' id='outputBase64FormInput' name='mybase64image'>
<input type='submit'>
</form>
</body>
</html>
Edit:
the OP asked to add image in canvas (and also posted the image to endpoint)
I'm trying to get the data value on success from the php. However when I alert(data) in the success, it returns the page html.
HTML:
<input type="text" class="form-control" name="project_name" id="projectName" required>
Jquery AJAX:
$('#projectName').on('blur', function(){
var projectName = $(this).val();
$.ajax({
url: 'page.php',
type: 'POST',
dataType: 'text',
data: {
'projectChecked': 1,
'project_name': projectName,
},
success: function(data){
if (data == 'taken') {
$('#projectName').addClass('border-red');
}
}
});
});
PHP:
if(isset($_POST['projectChecked'])){
echo 'taken';
exit;
}
Alert Message:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8"/>
<link rel="shortcut icon" href="/favicon.png"/>
<title>Page Title</title>
<meta name="description" content="Meta Description">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"/>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlTw8HfCJo=" crossorigin="anonymous"></script>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-157194354-1"></script>
You should use exit in php code to get return data use following code
if(isset($_POST['projectChecked'])){
echo 'taken';
exit;
}
can you check the html code when you do alert(data); and post here?
alternatively, you might want to check the developer tools of browser and validate network tab to monitor parameters and response of ajax request.
It is possible that you are getting http 400/500 response and you are actually seeing default error page (which is of course not a JSON response) in the data variable (this depends on the way server is configured)
been tring to send var form js to php and do some manipulation but I keep receving this error. Is it even possible to send the value through to php?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<script
src="https://code.jquery.com/jquery-3.5.0.min.js"
integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ="
crossorigin="anonymous">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/d3js/5.15.1/d3.min.js"></script>
</head>
<body>
<input type="text" name='name'>
<p id="hey"></p>
<?php
echo $_POST['name'];
?>
<button id='button'>hi</button>
</body>
<script src="index.js"></script>
</html>
$("#button").click(function(){
$.post("index.php",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
$("#hey").append(status);
});
});
I created one index.php file here this should work for you.
<?php
if ($_POST) {
echo json_encode(['data' => $_POST['name'], 'success' => true]);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<script
src="https://code.jquery.com/jquery-3.5.0.min.js"
integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ="
crossorigin="anonymous">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/d3js/5.15.1/d3.min.js"></script>
</head>
<body>
<input type="text" name='name'>
<p id="hey"></p>
<div id='test'></div>
<button id='button'>hi</button>
</body>
<script>
let data = {
name: "Donald Duck",
city: "Duckburg"
};
$("#button").click(function(){
$.ajax({
type: "POST",
url: 'index.php',
data: data,
dataType: 'json'
}).done(function(response) {
if (response.success) {
$('#hey').html('success');
$('#test').html(response.data);
}
});
});
</script>
</html>
This does not work because when you first load the page $_POST['name'] is undefined. Your javascript code does not trigger a submit (= reload to send the data). $_POST['name'] is never set because it will not be updated on the fly. To make this work make a separate php file which only handles the POST data from your javascript and returning a value.
/* call post.php and add console.log to track data */
$("#button").click(function(){
$.post("post.php",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
$("#hey").append(status);
console.log(data);
});
});
<?php
// post.php
if($_SERVER['REQUEST_METHOD'] == "POST") {
echo $_POST['name'];
}
This is of course very basic. In order to communicate effectively you should look into formating the data e.g. into JSON.
I want to send an email address to my submit.php as post and receive a response with jquery.
submit.php and index.html are in website root and script.js is in 'js' folder.
my index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input id="email" type="email" placeholder=" Email"><br>
<button id="submit-btn">send</button>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous">
</script>
<script src="js/script.js"></script>
</body>
</html>
my script.js:
$(document).ready(()=>{
$("#submit-btn").click(()=>{
$.post("../submit.php", { user_email: $("#email").val()})
.done((data)=>{
alert(data);
})
.fail((xhr, status, error)=>{
alert(error);
});
});
});
my submit.php:
<?php
$email = (isset($_POST['user_email']) ? $_POST['user_email'] : "nothing");
echo $email;
I expect the output to be my email address, but the actual output is not found.
I think my request has failed
Since you say that both files are in the same folder, there is no need for the ../ in front of your request.
$.post("../submit.php", { user_email: $("#email").val()})
$.post("submit.php", { user_email: $("#email").val()})
Hi I'm making a change to a text area and thanks to this plugin I can mention users from a db after entering # in a textarea you place the complete code.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css">
<link href="bootstrap-suggest.css" rel="stylesheet" type="text/css">
</head>
<body>
<textarea class="form-control" rows="8" id="example-1"></textarea>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="bootstrap-suggest.js"></script>
<script>
var users = [
{username: 'lodev09', fullname: 'Jovanni Lo'}
];
$('#example-1').suggest('#', {
data: users,
map: function(user) {
return {
value: user.username,
text: '<strong>'+user.username+'</strong> <small>'+user.fullname+'</small>'
}
}
})
</script>
</body>
</html>
in the user variable there are the search fields by default, I ask you for help, which instead of the defaul fields in the variable, the search is done in a php page, the data to search from my database sql, how can I change the code? how do I change defaul fields with dynamic fields taken from the database? Thanks I hope you help me
So I pretty much just followed the documentation on http://lodev09.github.io/bootstrap-suggest/#api
I wanted to include Axios as that's a more preferred way to fetch data in large scale applications.
and in their example return $.getJSON("users/data.json", { q: q }); using q by default will look up all the keys in the array. You can specify if you only want to search say for username with { username: q }
Here's my working db example you can use from {} myjson
Now the part that'd you change for getting this to work with your php backend is the api and api endpoint you've setup.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" />
<link href="bootstrap-suggest.css" rel="stylesheet" type="text/css" />
</head>
<body>
<textarea class="form-control" rows="8" id="example-1">type after -> #</textarea>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://lodev09.github.io/bootstrap-suggest/bower_components/bootstrap-suggest/bootstrap-suggest.js"></script>
<script>
$('#example-1').suggest('#', {
data: function(q) {
if (q) {
return $.getJSON('https://api.myjson.com/bins/18vsxq', {
q: q
}).then(function(Response) {
return Response.users
});
}
},
map: function(user) {
return {
value: user.username,
text: '<strong>' + user.username + '</strong> <small>' + user.fullname + '</small>'
}
}
})
</script>
</body>
</html>
anyways hopes this helps,
-Brendan