I am working with phonegap for the first time to build hybrid mobile app with back-end(php, mysql). So i am doing a test on how phonegap can connect to php on localhost to send and retrieve data. But no data was retrieved, I have reduced my codes to the this and i see no errors in both ajax call and php code. So i guess it should be the way phonegap connects to backend that i am getting wrong, please help.
html form and ajax call:
<form id="form1">
<input type="text" id="email" />
<input type="password" id="password" />
<input type="submit" name="login" id="login" value="Login">
</form>
<script type="text/javascript">
$("form").submit(function(){
var data= ("#form1").serialize();
$.post("http://localhost/securityapp/login.php",data,function(response){
alert(response);
});
});
</script>
php file:
<?php
include 'db.php';
session_start();
if ($_POST ) {
echo $_POST;
}
?>
Basically it is meant to alert to values sent to php script as the response but it is not doing so, network tab says 200 for status. what am i doing wrong? I feel phonegap isn't connecting to the url defined
This is how I solved this issue:
created a table on a database that holds the current URL/IP of the server
Created a check-url.php file, this file runs a query on the database to see IP/URL of
the server
I created a connection.js file, this file basically makes a request to a check-url.php
to get current IP of the server to use in Cordova app
check-url.php
header("Access-Control-Allow-Origin: *"); //to allow phonegap access it because of cross origin and domain restrictions
require 'db.php';
$query= "SELECT url FROM settings";
$query= mysqli_query($conn,$query);
$row = mysqli_fetch_assoc($query);
$row= $row['url'];
echo $row; //current IP exmaple:http://127.0.0.1:80/
connection.js
//check current server ip from database
export function check_url(callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) { // request is done
if (httpRequest.status === 200) { // successfully
callback(httpRequest.responseText); // we're calling our method
}
}
};
httpRequest.open('GET', "http://127.0.0.1:80/projectname/check-url.php");
httpRequest.send();
}
So any time I want to connect to backend by Cordova I import the function check-url() from connection.js into my front-end ajax request url like this:
<script type="module">
import {check-url} from './connection.js';
check-url(function(result) {
var currentIP= result;
$.ajax({
type:"POST",
url: currentIP + "projectapp/login.php",
data:data,
success: function(data){
//do something
}
});
});
</script>
Note: The URL/IP in connection.js, database, and server IP should be the same, as this helps you not to repeat IP always and also to test when using PhoneGap mobile and also when you switch to live, change it to the current IP address of your project.
Related
I want to submit a react form making an ajax call to php server. I have used react hook but since I am new to it, I cant not figure out error actually.
function App() {
const [name, setName] = useState("");
const [result, setResult] = useState("");
const handleChange = (e) => {
setName(e.target.value);
};
const handleSumbit = (e) => {
e.preventDefault();
const form = $(e.target);
$.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
success(data) {
setResult(data);
}
});
};
return (
<div>
<form
action="server.php"
method="post"
onSubmit={(event) => handleSumbit(event)}
>
<label htmlFor="name">Name: </label>
<input
type="text"
id="name"
name="name"
value={name}
onChange={(event) => handleChange(event)}
/>
<br />
<button type="submit">Submit</button>
</form>
<h1>{result}</h1>
</div>
);
}
const header4 = ReactDOM.createRoot(document.getElementById('header4')) ;
header4.render(<App />);
I have skipped the import part. The above code runs without any error but when I click the button, nothing happens.
This is my php code:
<?php
header('Access-Control-Allow-Origin: http://localhost:3000');
$user = $_POST['name'];
echo ("Hello from server: $user");
?>
I verified that your react code is working fine, and if you check in network tab in developer tools in any browser, there is a POST request going to http://localhost:3000/server.php. The reason you see nothing happening is that this url might not be what you server is listening to.
If we don't provide the absolute url, relative path causes your request to be handled by react at http://localhost:3000/server.php and it errors out as there is no resource to handle it.
To fix the issue, change form action attribute to:
http://<serverhost>:<serverport>/server.php
This should work for localhost based servers. For production applications, you might consider making POST request to a server instead of form submission.
Please try and let me know if this fixes your issue.
I am trying to get the data from mysql in my Angularjs page and I am using PHP as my server side language. I am not able to get the data in my page, however I got the data from my PHP file. And if you have some alternative of it please tell me.
Here is my code:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body ng-app="myapp" ng-controller="myctrl">
<h2>here is the info</h2>
<table>
<tr ng-repeat="country in countries">
<td>{{country.Empno}}</td>
<td>{{country.Ename}}</td>
<td>{{country.Job}}</td>
<td>{{country.Hiredate}}</td>
<td>{{country.Salary}}</td>
</tr>
</table>
</body>
<script>
var app = angular.module('myapp', []);
app.controller('myCtrl', ['$scope', '$http', function ($scope, $http) {
$http({
method: 'get',
url: 'one.php'
}).then(function successCallback(response) {
// Store response data
$scope.country = response.data;
});
}]);
</script>
</html>
here is the one.php file
<?php
$link=mysqli_connect("localhost","root","vikash","jarvis");
if($link==false){
die("you are not connected to database ".mysqli_connect_error());
}
$query="SELECT * FROM emp";
$data=array();
if($result=mysqli_query($link,$query))
{
if(mysqli_num_rows($result)>0)
{
while($row=mysqli_fetch_assoc($result))
{
$data[]=array("Empno"=>$row['empno'],"Ename"=>$row['ename'],"Job"=>$row['job'],"Hiredate"=>['hiredate'],"Salary"=>['sal']);
}
}
else
{
echo "no records are matching";
}
}
else
{
die("could not able to execue the command ".mysqli_error($link));
}
echo json_encode($data);
mysqli_close($link);
?>
You are getting confused between absolute file paths and internet addresses. one.php is not a URL, it is a system file path.
You need to serve your one.php file via a webserver which will give is an address like http://localhost/one.php and then use that as your URL in your angularJS code.
This is because you are using angular's $http module, which is designed for IP (Internet Protocol). It is not designed for system file access.
In my AngularJS app, the data entered into the form are not stored in the MySQL database after hitting the submit button. An alert after successful form data submit however indicates that it is working.
Also, after hitting the submit button, I want the app to proceed to the next view (#/setup-step2) - however it remains at step1.
html partial (#/setup-step1):
<form ng-submit="submitForm1()">
Job title: <input type="text" name="jobtitle" ng-model="formData1.jobtitle">
Vacancy ID: <input type="text" name="vacancyid" ng-model="formData1.vacancyid">
<button type="submit" class="animatedbutton"> Proceed </button>
</form>
controller.js:
var ctr = angular.module('myApp.controller', []);
ctr.controller
('Step1Controller', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http){
$scope.formData1 = {};
$scope.submitForm1 = function() {
$http({
method: 'POST',
url: 'php/setup-step1.php',
data: $.param($scope.formData1),
headers: { 'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data){
console.log(data);
alert("It worked");
})
.error(function(data) {
console.log(data);
alert("It didn't work");
})
}
}]);
setup-step1.php in folder /php:
<?php
include_once('db.php');
// Check connection
if(mysqli_connect_errno())
{echo '<p>Connection to MySQL server failed: '.mysqli_connect_error().'</p>';}
else
{echo '<p>Connection to MySQL server successful.</p>';}
$_POST = json_decode(file_get_contents("php://input"), true);
if (empty($_POST['jobtitle']))
{$errors['jobtitle'] = 'Job title is required.';}
else {
// Escape user inputs for security
$jobtitle = $_POST['jobtitle'];
$vacancyid = $_POST['vacancyid'];
$data = "INSERT INTO campaign (Job_title, Job_id) VALUES ('$jobtitle','$vacancyid')";mysql_query("INSERT INTO campaign (Job_title, Job_id) VALUES ('$jobtitle', '$vacancyid')");}
if ($connect->query($data) === TRUE)
{$conn->close();}
else
{echo "Error: " . $sql . "<br>" . $conn->error;}
exit();
?>
First,
Be sure that you enable the cors before performing any request to the server.When you are working with angularjs this usually means that you are making cors requests to the server.If you didn't enable cors option you cannot call any method from the server since it is not allowed.
Second,
just keep php code inside your setup-step1.php.You don't need any html code there since it will return result of your requet only.
Third,
As I know you cannot change location of the webpage from erver because server domin and website domains are different.You need to redirect the user to another page in angularjs. You can find the ways of redirecting in angularjs by using $location or $state.
I found the answer myself. The problem was incorrect php and mysql syntax. Updated the code the way it works now.
It's not updating and I'm missing what I'm doing wrong. Uses HTML, jQuery, and PHP. All code is posted below.
What I'm trying to do is allow a user to change a 'client' seed and when it' changed it's updated. In the it's displayed. All that does is refresh every 100ms from a file that's echoing it out. There's no issue there.
PHP Code:
<?php
session_start();
include_once('db.php');
if(isset($_POST['action'])) {
switch($_POST['action']) {
case 'get_client':
echo json_encode(array('result' => $_SESSION['client']));
break;
case 'modify_client':
if(isset($_POST['client']) && strlen($_POST['client']) == 6 && is_numeric($_POST['client'])) {
$_SESSION['client'] = $_POST['client'];
echo json_encode(array('result' => true));
$secret = 123;
$_SESSION['server'] = hash('sha512', $_SESSION['roll'] . $_SESSION['client'] . $secret );
}
else {
echo json_encode(array('result' => false));
}
break;
}
}
?>
Javascript/jQuery:
<script type="text/javascript">
$.post('./php/show_client.php', { action: 'get_client' }, function(result) {
var result = JSON.parse(result);
})
});
$("#client_seed_modify").on("click", function() {
$.post('./php/show_client.php', { action: 'modify_client', client: $("#client_seed").val() }, function(result) {
var result = JSON.parse(result);
if(result ) {
if(result.result) {
alert('Your Client Seed has been changed. This has also changed the server seed. Please note that you have the ability to change your client seed freely, but regardless of whether or not you decide to, it does NOT stay the same every roll.');
}
}
});
</script>
HTML:
<a>Current Client Seed: <span class="clientShow" style=""> </span></a>
<p class="field">
<input type="text" placeholder="Change your Client Seed" name="client" id="cient_seed" class="client_seed">
</p>
<p class="field">
<input type="submit" value="Change Client Seed" style="width: 360px;" name="client_seed_modify" id="client_seed_modify">
</p>
You are confusing server side code and client side code. PHP executes on the server, meaning that any links to resources should be file paths to where the actual files on the server are located. Javascript/JQuery is client side code, meaning that it runs in the user's browser, so any links should be urls not file paths.
Instead of using a local file path on the server like you are now with:
$.post('./php/show_client.php' ...
Your url passed to $.post() should be a URL which accesses that PHP script.
$.post('mysite.com/directory/show_client.php' ...
UPDATED AND SOLVED
Thanks to #Christofer Eliasson for the hint. Adding:
header("access-control-allow-origin: *");
to my PHP file solved the issue. Perhaps not the most beautiful way of dealing with the problem but this works.
To make it a bit better/safer:
$http_origin = $_SERVER['HTTP_ORIGIN'];
if ($http_origin == "http://domain1.com")
{
header('Access-Control-Allow-Origin: *');
}
Here is another cross-domain related question.
I have a simple HTML form on domain1.com where a user can add his/her email to a mailing list, here a simple json file, "mails.json", hosted on a second domain (domain2.com).
When the user submits his/her email, a JS script is called whose aim is to check the email and to send the data of the form (here the user's email) to the mails.json file hosted on domain2.com via ajax GET and JSONP.
Ajax calls a PHP script hosted on domain2.com that should get the user's email and write it to mails.json. Moreover, it should send back to domain1.com some messages regarding the success or errors, given that the user has already entered his email before.
Currently, the email is sent and saved to mails.json but I cannot manage to get my PHP script to send back messages to domain1 regarding its execution. Thanks for your advices and feel free to check and modify the code below.
The HTML form hosted on domain1.com
<div id="mail">
<form method="post" action="http://domain2.com/script.php" class="notifyme">
<input type="email" value="" name="email" class="email" id="email" placeholder="Type your email here" required>
<input type="submit" value="Get notified ยป" id="submit" name="submit">
<div class="clear"></div>
</form>
<div class="errmail hide"><span class="uremail"></span> is not a valid email address. Try again :)</div>
<div class="error hide">Ouch :( <span class="uremail"></span> is already registered.</div>
<div class="success hide">Thank You :) <span class="uremail"></span> will be notified once we're ready.</div>
</div>
The Javascript file hosted on domain1.com
//jQuery Initialization
$(function(){
// Form
$('#submit').click(function () { //onSubmit
$('.error,.errmail,.success').hide();
var email = $('input[name=email]').val();
//Email validation
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
var valid = pattern.test(email);
if (!valid && email !== 'undefined') {
$('.errmail').removeClass('hide').show('fast');
if (!email){$('.uremail').append('This');}
else{$('.uremail').append(email);}
return false;
} else {
//start Ajax
$.ajax({
url: "http://domain2.com/script.php?json_callback=?",
dataType: "jsonp text",
//GET method is used
type: "GET",
//pass the data
data: 'email=' + email,
//Do not cache the page
cache: false,
//Cross Domain
crossDomain: true,
//success
success: function (html) {
//if list.php returned 1/true (send mail success)
if (html==1) {
$('.success').removeClass('hide').show('fast');$('.uremail').append(email);
}
else if (html == 0){
$('.error').removeClass('hide').show('fast');$('.uremail').append(email);
}
else { alert('Sorry, unexpected error. Please try again later.'); }
}
});
}
//cancel the submit button default behaviours
return false;
});
});
UPDATED
The PHP "script.php" file hosted on domain2.com
header('content-type: application/json; charset=utf-8');
$http_origin = $_SERVER['HTTP_ORIGIN'];
if ($http_origin == "http://domain1.com")
{
header('Access-Control-Allow-Origin: *');
}
$logname = 'mails.json';
$logcontents = file_get_contents($logname);
//Retrieve form data.
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
if(strpos($logcontents,$email) !== false) {
if ($_POST) {die('You are already subscribed.');}
else{ $result = 0;echo $result; }
}
else {
$filecontents = $email.',';
$fileopen = fopen($logname,'a+');
$filewrite = fwrite($fileopen, json_encode($filecontents) );
$fileclose = fclose($fileopen);
if(!$fileopen or !$filewrite or !$fileclose) {
if ($_POST) {die('Error occured');}
else{ $result = 0;echo $result; }
}
else {
if ($_POST) {echo 'Your email has been added.';}
else{ $result = 1;echo $result; }
}
}
As you set the proper content-type header at the beginning of your script, you can return the data with a regular echo. You will just have to prepare the data to match the JSONP-format first. Something like this:
<?
// Some data to return
$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
// JSONP response
echo $_GET['callback'] . '('.json_encode($data).')';
?>
// For this example, the response would be something like this:
// jsonp1277656587731([1,2,3,4,5,6,7,8,9])
When you do a JSONP ajax-request with jQuery, jQuery will automatically send a callback GET-variable for you to use on the server-side. As seen in the example.
Some additional reading: http://www.geekality.net/2010/06/27/php-how-to-easily-provide-json-and-jsonp/
I faced a similar problem in the past and I did try to tinker around with cross domain settings on webserver(Apache2) but no luck. By hit and try I eliminated the hostname from the 'url' parameter of my ajax call and it worked for me. I still did not understand completely though.
Can you quickly check url parameter from :
http://domain2.com/script.php?json_callback=?
to just:
script.php?json_callback=?.
There may be additional web server configuration settings ..but just wanted to see if that worked....