How to call a PHP from a mobile app? - javascript

I have an HTML page that takes a login from user and authenticates and redirects to the different page. Now i converted this web-page to an app using phonegap app build function. Now i am trying to call the php thats on my server. What is the proper way to do so? Below is the code.
HTML
<script>
function PostData() {
// 1. Create XHR instance - Start
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
// 1. Create XHR instance - End
// 2. Define what to do when XHR feed you the response from the server - Start
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
document.getElementById('div1').innerHTML = xhr.responseText;
}
}
}
// 2. Define what to do when XHR feed you the response from the server - Start
var userid = document.getElementById("userid").value;
var pid = document.getElementById("pid").value;
// 3. Specify your action, location and Send to the server - Start
xhr.open('POST', 'www.xyz.com/abc/login.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("userid=" + userid + "&pid=" + pid);
// 3. Specify your action, location and Send to the server - End
}
</script>
</head>
<body>
<form>
<label for="userid">User ID :</label><br/>
<input type="text" name ="userid" id="userid" /><br/>
<label for="pid">Password :</label><br/>
<input type="password" name="password" id="pid" /><br><br/>
<div id="div1">
<input type="button" value ="Login" onClick="PostData()" />
</div>
</form>

Try this jQuery.
function PostData() {
$.ajax({
url: "/ajax/login_check.php",
type: "POST",
data: {userid : $("#userid").val(),pid : $("#pid").val()},
cache: false,
success: function (result) {
if(result.statu){
//Valide Div Screen Show
}
else{
//invalide Div Screen Show
}
}
});
}
check Valide Login use Check file
login_check.php
ur Mysql And Php COde Put in this file.
if { //if valide Use than
$responce['statu'] = "1";
$responce['msg'] = "Login success.";
}
else{
$responce['statu'] = "0";
$responce['msg'] = "Invalide Use name & Pass";
}
echo json_encode ($responce);
Exit;

Related

Do a javascript redirect after an ajax call

I'm trying to use ajax to parse data to be processed on a php page and have php echo a javascript redirect to another page but it is not working. I have read that js does not work after running an ajax call so I will like to know if there s a way around it. This is my code:
html
<form>
<div class="depart_time bottom_white w-40 ml-auto">
<p>Time</p>
<input type="time" name = "return_time" id = "rt">
</div>
<div class = "search_button r_search">
<button id = "r_search" onclick = "return false" onmousedown = "rent()">SEARCH</button>
</div>
</form>
ajax call is a normal xhttp request that gets sent to php for processing after which a redirection should occur:
if(isset($_POST['return_time'])){
echo '<script type="text/javascript">window.location.href="link.html"</script>';
}
Please an help is appreciated. I'm new to using ajax.
EDIT
the ajax code:
gid("r_search").addEventListener("mousedown", rent);
function rent(){
rt = gid('rt').value;
r_search = gid('r_search').value;
form_array = '&rt=' + rt +
'&r_search=' + r_search;
send_data = form_array;
ajax_data('app/rent.php', 'error', send_data);
//gid('error').innerHTML = send_data;
}
function ajax_data(php_file, getId, send_data){
gid(getId).innerHTML = "loading";
var xhttpReq = new XMLHttpRequest();
xhttpReq.open("POST", php_file, true);
xhttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttpReq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
gid(getId).innerHTML = xhttpReq.responseText;
}
};
xhttpReq.send(send_data);
}
please note that 'gid' is for getelementbyid
You have to make bit alteration to your way of redirection.
First you need to make changes in your PHP response
if(isset($_POST['return_time'])){
...
// If you get your process success return 1
if(success) {
echo 1; die();
} else {
// else set some flag that you could get on your AJAX response
echo 0; die();
}
}
Now, get this flag on your AJAX and make changes to your below functions:
function ajax_data(php_file, getId, send_data){
gid(getId).innerHTML = "loading";
var xhttpReq = new XMLHttpRequest();
xhttpReq.open("POST", php_file, true);
xhttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttpReq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if( xhttpReq.responseText == 1 ) window.location.href="URL where you wish to redirect page";
}
};
xhttpReq.send(send_data);
}
I've written this answer for others who come here for help.

How do I send request and recieve response from REST API using javascript?

I have a local server running on my computer which has an in-built REST API. the base url of api is: http://127.0.0.1:8090/ehr/api/v1 . Now I want to make a client application for this server using this api. To log in this server, the api url is baseurl/login with POST method. It takes username, password and organization as parameters and returns an auth token in json if the login is successful. Now I want to create a form in html and javascript which will ask the username, password, organization and log in the user if response is an auth token, otherwise if the response in an error instead of token, user will not be able to log in. What should be the html and javascript code for this form? I typed the following code to output the auth token but it showed no result. even the console log is empty.
<html>
<body>
<div class="login">
<h1>Login</h1>
<form method="post">
<input type="text" name="u" placeholder="Username" id="username" required="required" />
<input type="password" name="p" placeholder="Password" id="password" required="required" />
<input type="text" name="p" placeholder="Organization" id="organization" required="required" />
<button type="submit" onclick="loginfunc()">Let me in.</button>
</form>
</div>
<script>
function loginfunc(){
var baseurl = "http://localhost:8090/ehr/api/v1";
var funcurl = "/login";
var username = document.getElementById("username");
var password = document.getElementById("password");
var organization = document.getElementById("organization");
var url = baseurl+funcurl+"?username="+username+"&password="+password+"&organization="+organization
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "POST", url, true); // false for synchronous request
xmlHttp.send( null );
var response = JSON.parse(xmlhttp.responseText);
document.write(response)
}
</script>
</body></html>
edit: I changed the login function based on suggestions to this:
function loginfunc(){
var baseurl = "http://localhost:8090/ehr/api/v1";
var funcurl = "/login";
var username = document.getElementById("username");
var password = document.getElementById("password");
var organization = document.getElementById("organization");
var url = baseurl+funcurl+"?username="+username+"&password="+password+"&organization="+organization;
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if(xmlHttp.readyState === XMLHttpRequest.DONE && xmlHttp.status === 200) {
console.log(xmlHttp.responseText);
}
};
xmlHttp.open( "POST", url, true); // false for synchronous request
xmlHttp.send( null );
document.write(xmlHttp.responseText);
}
but now I get 401 unauthorized error at xmlHttp.send() function. I can't understand why as when I make request to same url using a REST client like insomnia, it works fine and returns auth token.
The request you're making to the server is asynchronous, so your code cannot just take the response immediately. This is done using a callback:
xmlHttp.onreadystatechange = function () {
if(xmlHttp.readyState === XMLHttpRequest.DONE && xmlHttp.status === 200) {
console.log(xmlHttp.responseText);
}
};

AJAX logic not working

I am new to AJAX and learning it. I am searching a food item in my HTML textbox and trying to communicate with the server to know if the item is available. The respective status of the item should be shown in the div tag below the textbox but it is not showing.
I haven't studied jQuery yet and would like to know the below things:
How to get the response from the server in plaintext using AJAX and JavaScript, and display it in the div tag below the textbox (advise the changes to be made in the code).
What change should I make in JavaScript code to send the AJAX request in POST method (I know about the changes in PHP code)?
//index.html
<head>
<script type="text/javascript" src="food.js">
</script>
</head>
<body>
<h3>The Cheff's Place</h3>
Enter the food you want to order
<input type="text" id="userInput" name="input" onkeypress="sendInfo()"></input>
<div id="underInput"></div>
</body>
</html>
//food.js
var request;
function sendInfo() {
var v = document.getElementById("userInput").value;
var url = "index.php?food=" + v;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
if (request.readyState == 0 || request.readyState == 4) {
try {
request.onreadystatechange = getInfo;
request.open("GET", url, true);
request.send(null);
} catch (e) {
alert("Unable to connect to server");
}
}
}
function getInfo() {
if (request.readyState == 4) {
if (request.status == 200) {
var val = request.responseText;
document.getElementById('underInput').innerHTML = val;
}
}
}
//index.php
<?php
header('Content-Type: text/plain');
$food = $_GET['food'];
$foodArray = array("paneer", "butter", "chicken", "tandoori", "dal");
if (in_array($food, $foodArray))
{
echo "We do have " .$food;
}
elseif($food == "")
{
echo "Kindly enter some food";
}
else
{
echo "We do not sell " .$food;
}
?>
I ran your code. It's working fine. Just replace onkeypress with onkeyup.
<input type="text" id="userInput" name="input" onkeyup="sendInfo()"></input>
Using JQuery (Assuming you have included jquery file or cdn) :
Include the following snippet in script tag at the end of the body.
$("#userInput").keyup(function(){
$.get("index.php", { food: $("#userInput").val() })
.done(function(data) {
$("#underInput").html(data)
})
});

Why I'm getting pure json data which can't be displayed

I'm trying to build a simple web which has 2 function:
1. get string (sms) message from server, and display it on screen
2. send (post) form data to server which send back the data, which will be logged.
The server code:
app.get('/sms', function (req, res) {
var smsMsg = fs.readFileSync('sms.txt');
console.log('Read File: ' + smsMsg.toString());
res.send(smsMsg.toString());
})
app.post('/result', function (req, res) {
console.log('Got Personal Information: ' + req.body.firstName + " " + req.body.lastName);
response = {
first_name:req.body.firstName,
last_name:req.body.lastName,
id:'0399'
};
console.log(response);
// value to a JSON string
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(response));
})
The client code:
<body>
<p>
<button onclick="sendRequestForSms()"> Get SMS From Server </button>
</br>
<h1 id="smsId"> SMS: <h1>
</br>
</p>
<p>
<form action="/result" method="post">
<fieldset>
<legend>Personal information:</legend>
First name:
<input type="text" name="firstName">
<br>
Last name:
<input type="text" name="lastName">
<br>
<input type="submit" value="Submit" id="submit">
</fieldset>
</form>
</p>
<script type="text/javascript">
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
console.log('State: ' + xmlhttp.readyState + ' status: ' + xmlhttp.status);
// 1: server connection established
// 4: request finished and response is ready
// 200: "OK"
// 404: Page not found
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
if (xmlhttp.getResponseHeader('Content-Type') == 'application/json')
{
console.log('Got Json');
var myArr = JSON.parse(xmlhttp.responseText);
console.log(myArr);
}
else
{
document.getElementById("smsId").innerHTML = xmlhttp.responseText;
}
}
};
function sendRequestForSms() {
xmlhttp.open("GET", "/sms", true);
xmlhttp.send();
}
</script>
</body>
When the user click on 'Get SMS From Server' I'm getting the result and display it on the relevant element ('smsId').
But :( When the user submit the form, I'm getting new page with json data (for example: '{"first_name":"test1","last_name":"test2","id":"0399"}')
so I the client code line: console.log('Got Json');
is not reached, why the client callback function isn't called ?
What am I doing wrong ?
Got Json is never going to be printed because /result (server) is currently set up to just echo the JSON it gets sent. It looks like it's being sent the correct info from the form, but the way you have it set up right now "Got Json" will only print from your "Get SMS" button. To do what you're trying to do, the way you're trying to do it, you would need to make /result output a new page that prints out the javascript you want to run after they submit. Does that make sense? I can clarify.
Example on the use of XMLHTTPRequest
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.w3schools.com/json/myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
Source: http://www.w3schools.com/json/json_http.asp
Live Example: http://www.w3schools.com/json/tryit.asp?filename=tryjson_http

Problems with XMLHttpRequest and PHP

I'm fairly new to both JavaScript and PHP, so I hope this problem isn't as complex as it seems to me. I'm trying to send data from a form to a PHP file using XMLHttpRequest, and then display the output of the PHP as an alert. Here's the HTML and JavaScript:
<form onSubmit="password_Check()">
<input type="password" size="40" name="password" id="pass">
<input type="submit" value="Go">
</form>
<script type="text/javascript">
function password_Check() {
var url = "test.php";
var pass = $("#pass").val();
var xhr = new XMLHttpRequest();
xhr.open("GET", url+"?pass="+pass, true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
}
</script>
And here's the PHP:
<?php
$pass = $_GET["pass"];
echo "The password is $pass! We've done it!";
?>
I've tried all sorts of ways to do this, like $.post, $.get, $.ajax, and an xhr using POST. But I can't seem to get this to work. Now it just appends "?password=(whatever I put)" onto the end of the current url, which does nothing, but it shows it's doing something.
In your code you are missing the send part where you actually trigger the request. If you are not triggering the request then there is no point of the event listeners which listen for the state changes.
do it like
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send();
Also in your question you are mentioning about jquery ajax, with $.get your code could be as simple as
$("#form1").on("submit",function(e){
e.preventDefault();
var url = "test.php?pass=" + $("#pass").val();
$.get(url,function(data){
//handle data here
});
});
You forgot to execute the request. xhr.send():
Also note that since you're having an XMLHTTPRequest, you need to prevent the default behavior (which is the form is going to be submitted) by using .preventDefault();
<form id="form1">
<input type="password" size="40" name="password" id="pass">
<input type="submit" value="Go">
</form>
<script type="text/javascript">
// handle the submission event
document.getElementById('form1').addEventListener('submit', function(e){
e.preventDefault(); // prevent from submitting
var url = "test.php";
var pass = document.getElementById('pass').value; // be faithful!, just use plain javascript
var xhr = new XMLHttpRequest();
var params = '?pass='+pass;
xhr.open("GET", url+params, true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(); // send it
});
</script>
If you are using jQuery then better use jQuery's ajax functions instead of xhr by yourself!
Also if you are submitting the password, better not submit it using GET request as it will be visible in the URL. Instead always use POST when handling Passwords!
Client side:
<form action="/index.php" id="myform" method="post">
<input type="password" size="40" name="password" id="pass">
<input type="submit" value="Go">
</form>
<script type="text/javascript">
$('#myform').on('submit', function() {
$.ajax({
type: $(this).attr('method'), //Taking for the form attribute
url: $(this).attr('action'),
data: $(this).serialize(), //Takes care of all input fields in the form! No need to pass one by one!
success: function(response) {
if(response == 'success') {
window.location.href = '/url-to-goto'; //Set your redirect url here
}
else {
//Handle invalid password here
alert(response);
}
}
});
return false;
});
</script>
Server side:
<?php
//If you are handling password, better to put it in the post body instead of url for security reasons
if($_SERVER['REQUEST_METHOD'] == 'POST') {
//Check password here
if(isset($_POST['password']) && $_POST['password'] == '123') {
die('success'); //successful! redirect user!
}
die('Invalid password!');
}
?>
Hope that helps you better understand!

Categories