I'm using phonegap, html, ajax, jquery , mysql, and php.
In my Phonagep Application I have form that contain username, password, userphoto.
I want to submit this form from the html page. lets say register.html
form data should be sent to php page that is uploaded on my server in a folder named services lets say the path is "http://www.example.com/services/register.php".
this page should handle mysql insert process to a database that is also uploaded on the same server.
on this server I have also folder named images where user image should be uploaded and its full bath should be inserted in the mysql database.
I have tried using ajax to post user name and passowrd to this page and inserted data succssfully. but I face problem with the data when using serialize().
also I can't upload the image using ajax?
I used this code .. I get response for username and password without sending the image path but nothing happens when sending the image path
<html>
<head>
<title>Basic Upload</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type='text/javascript' src='http://code.jquery.com/jquery-latest.pack.js'></script>
<script type="text/javascript" charset="utf-8">
function sub(e){
var ft = new FileTransfer();
var options = new FileUploadOptions();
options.fileKey="myImg";
options.fileName=$('#myImg').val();
options.mimeType="image/jpeg";
options.mimeType="image/png";
options.chunkedMode = false;
var PATH = options.fileName;
var form_data= new Object();
form_data['user_name']= 'User';
form_data['password']= '1234';
form_data['user_image_path']= PATH;
var url = "http://localhost/stacktest/register.php";
$.getJSON(""+url+"?callback=?"+"&form_data="+JSON.stringify(form_data),
function (response) {
try {
// Get Your Response
alert(response);
}
catch(ex) {
console.log(ex);
}
}
);
}
</script>
</head>
<body>
<form method="post" enctype="multipart/form-data" id="registerForm" onsubmit="sub(this.value);">
<input type="file" name="myImg" id="myImg" />
<input type="submit" value="Upload" name="submitButton" id="submitButton" />
</form>
</body>
</html>
You should use PHP Webservice with Json to perform following task
Access Web Service Like :-
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
var PATH = 'Image Path';
var form_data= new Object();
form_data['user_name']= 'User';
form_data['password']= '1234';
form_data['user_image_path']= PATH;
var url = "http://localhost/stacktest/register.php";
$.getJSON(""+url+"?callback=?"+"&form_data="+JSON.stringify(form_data),
function (response) {
try {
// Get Your Response
alert(response);
}
catch(ex) {
console.log(ex);
}
}
);
</script>
Create PHP Webservice(register.php) like :-
<?php
$form_data = json_decode(stripslashes($_GET["form_data"]));
$user_name = $form_data->user_name;
$password = $form_data->password;
$user_image_path = $form_data->user_image_path;
//Perform Your Task like Insert into Database etc
$res= 'Your Response which you want to return';
echo $_GET["callback"].'('.json_encode($res).')';
I think your path is incorrect because webservice can't access the path of your file which scope is within your app. to upload your file read more about Cordova File Transfer
[Update]
You can download the working project from GitHub
Read PhonegapFileUpload Blog
Related
Currently on my website, I allow users to paste JSON data into an HTML form, then I use the JSON data to alter the rendering of the page. How do I replace the form with a file upload feature? I do not need to store the data on the Web server. As long as it all works within the browser it is okay. My website is written in PHP. Thanks.
Here's a simple demonstrator that prompts the user for a file, reads it, and posts the content to a <textarea>. It also parses the JSON content to a variable and sends that to the console.log. From here you should be able to unpack the data and update your page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Reader Demo</title>
</head>
<body>
<form id="fileForm">
<input type="file" name="fileItem" id="fileItem" required>
<input type="submit">
</form>
<textarea id="fileContents"></textarea>
<script>
(function(){
"use strict";
// Add an event handler to the form's submit event
document.getElementById('fileForm').addEventListener('submit', function(e){
// Stop the browser submitting anything
e.preventDefault();
// Get the file object
let file = document.getElementById('fileItem').files[0];
// Check the file is actually JSON
if (file.type !== "application/json") {
document.getElementById('fileContents').value = "Invalid file type"+file.type;
} else {
// Create a file reader
let reader = new FileReader();
// Add an event handler to the 'load' event
reader.addEventListener('load', function (e) {
// Post the file contents to the page
document.getElementById('fileContents').value = e.target.result;
// parse the JSON
let jsonData = JSON.parse(e.target.result);
// Process incoming JSON data here.
console.log(jsonData);
})
// Read the file as text. We'll parse it with JSON.parse later
reader.readAsText(file);
}
})
})();
</script>
</body>
</html>
I have a html form in which I want to save all the entries of all the fields into a file using php.
If I am able to save entries successfully then I want to give popup message saying {bytes} bytes written to file.
If I am not able to write successfully then I want to give popup message saying There was an error writing this file.
And if the user doesn't have write access then it should give popup message - Write access revoked.
I call save.php file from the form action to save all the entries in a file and add do some sort of validations.
Below is my index.php file which has form in it -
<?php
declare(strict_types = 1);
session_start();
require_once 'helpers.php';
if (! check_auth()) {
redirect('login.php');
return;
}
?>
<!doctype html>
<html lang="en">
<head>
<title>Home</title>
</head>
<body>
<div>
<h1>Website Title</h1>
Logout
</div>
<div>
<p>Welcome back, <?= $_SESSION['user_id'] ?>!</p>
</div>
<form action="save.php" method="POST">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" name="submit" value="Save Data">
</form>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</body>
</html>
And below is my save.php file -
<?php
declare(strict_types = 1);
session_start();
require_once 'helpers.php';
if (!check_auth())
{
redirect('login.php');
return;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if (!isWriteAccess())
{
echo json_encode(['success' => false, 'message' => 'Write access revoked', ]);
return;
}
// Your code here...
if (isset($_POST['field1']) && isset($_POST['field2']))
{
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\r\n";
$ret = file_put_contents('mydata.txt', $data, LOCK_EX);
if ($ret === false)
{
die('There was an error writing this file');
}
else
{
echo "$ret bytes written to file";
}
}
else
{
die('no post data to process');
}
}
Problem Statement
As of now whenever I click save button on my form which is in index.php, it just prints everything on my browser as the response and also redirects to save.php but I don't want that. I want to show all messages on popup window but it should stay on same index.php file.
If I am able to write successfully to the file, then I should see some bytes written to the file as a popup but it should stay on index.php file only.
If there is a write access issue then it should show Write access revoked as a popup but it should stay on index.php file only.
How can I make sure that whenever I click save button on my form which is in index.php it should stay on the same page but still do all sorts of validations and save entries in a file?
You already have jquery connected, so use $.ajax() to submit the form like this example or this. In the 'success:' handler the data variable will contain responce from your save.php:
success: function(data) {
$('#result').html(data);
}
therefore you can pop up a window with this results. Something like that in your index.php:
<script>
$(function() {
//This submits a form
$("#idForm").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
var method = form.attr('method');
$.ajax({
type: method, // "POST"
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data) {
alert(data); // show response from the php script.
}
});
});
</script>
PS: You can easily get answer to your question by yourself, such questions was answered here a lot. All trick is to add site:stackoverflow.com to your request in Google.
re this post AJAX Post to self in PHP
When using exit() doesn't something have to be printed before this call?
I have written markup/ph with references to external css php scripts. The script uses print (or echo) and a
call to header('type: text/css'). Isn't this useful or necessary in self processing php pages? I find
them endlessly useful. A whole site can be displayed in any state by one page using get queries and posts
from forms. I remember the text I was reading early on when beginning to learn php asserted that when
the page submits to itself, the browser will automatically use asynchronous requests. But in certain situations
an explicit ajax call is useful.
Here is what I am doing and what I am trying to do.
I have a text field and a button in a page
I write text to the text field and click the button
The javascript click event handler for the button gets the text field value
and appends it to a get query attached to the url in the request. The method is get
edit: to specify the environment in which this has been successful.
I am using Firefox v12.0 On Mac OSX with pre-installed apache server on local machine.
(anyone with a Mac running OSX, there is a pre installed apache server, but activating php requires
editing the httpd.com file to un comment the line(s) that load the php module. Also, there is a line
that tells Apache what extensions to use to look for and execute php code. You also must tell it
to take index.php as an index file to run the php in it and have it act as a directory index file)
the javascript code:
function _FETCH()
{
this.init = function(oName, elem, txt)
{
var but = document.getElementById(elem);
but.addEventListener('click', function(){ oName.req('GET', self, '', null, oName, txt) } )
}
this.req = function(method, url, type, msg, oName, txt)
{
var field = document.getElementById(txt);
url+="?ajxTst="+encodeURIComponent(field.value);
var it = new XMLHttpRequest();
it.open(method, url, type);
it.setRequestHeader('Content-Type', 'text/plain');
it.onreadystatechange = function()
{
var elem = document.getElementById('well');
switch(it.readyState)
{
case 0:
case 1:
break;
case 2:
case 3:
elem.childNodes[0].data = " waiting";
break;
case 4:
oName.handleResponse(it.responseText);
break;
default:
alert('ajax processing error');
break;
}
}
it.send(msg);
}
this.handleResponse = function(resp)
{
var elem = document.getElementById('well');
elem.childNodes[0].data = " "+resp;
}
}
The php, javascript and markup in the page:
<?php
/*
created 11/4/2014
*/
$_self = basename($_SERVER['PHP_SELF']);
if($_POST || $_GET)
{
if($_GET['ajxTst'])
{
header("Content-Type: text/plain");
print $_GET['ajxTst'];
exit();
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>JS lab 2</title>
<link rel="stylesheet" type="text/css" href="local.css" media="screen" />
<script type="text/javascript" src="local.js">
</script>
<script type="text/javascript">
//<![CDATA[
var self = "<?php print $_self; ?>";
window.onload = function()
{
var ajx = new _FETCH();
ajx.init(ajx, 'send', 'tlk');
}
//]]>
</script>
</head>
<body>
<div class="panel">
<p class="title">Js Lab 2</p>
<p class="norm">Lab 3 home</p>
<p class="norm">Work with ajax and self processing page (this)</p>
<hr />
<p class="norm" id="well"> idle </p>
<p class="norm">
<input type="text" id="tlk" value="" /><input type="button" id="send" value="send" />
</p>
</div>
</body>
</html>
I hope That someone looking for this will find it. It took me a while to get it right
I got stuck with passing a configuration to our angular application. My problem is
We have configuration is stored in database, so far it's URL of web service to communicate with
Page is rendered by PHP
How can I pass URL stored in database to ng-app?
So far I have hard-coded services.js
app.constant('config', {ws_url: 'ws://domain/ws'});
app.factory('wampy', function ($rootScope, config) {
var url = config.ws_url;
var ws = new Wampy(url, { autoReconnect: true });
return {
something: function () {
console.log(url); // usage of url
}
}
}
Then it is included into main html code (index.php)
<head>
<script type="text/javascript" src="http://dev.local/js/ng/app.js"></script>
<script type="text/javascript" src="http://dev.local/js/ng/services.js"></script>
</head>
But it can be amended / moved to somewhere else.
Any thoughts?
You could have a snippet of javascript rendered by php into a script tag like so
$config = array('ws_url' => 'ws://domain/ws');
$jsonConfig = json_encode($config);
$snippet = <<<EOS
<script type="text/javascript">
angular.module('appName').constant('config', $jsonConfig);
</script>
EOS;
and then output this $snippet somewhere in your page.
I have installed XAMPP to run PHP files on my computer, here is my PHP file I am attempting to execute
<?php
if(isset($_GET['input']))
{
$string = $_GET['input'];
echo strrev($string);
}
?>
Here is my basic HTML file
<html land="en">
<head>
<meta carset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css";
</head>
<body>
<!-- Document Ready Event -->
<input id="text" type="text" /><input id="submit" type="button" value="Submit" />
<div id="feedback"></div>
<script src="../jquery-1.10.2.min.js"></script>
<script src="script.js"></script>
</body>
</html>
And here is my JS file
//Pass a value to a PHP file and taking the contents and showing the contents
$('#submit').click( function()
{
var text = $('#text').val();
$.get( 'C:/xampp/htdocs/amit/reverse.php', { 'input': text }, function( data )
{
$('#feedback').text( data );
});
});
When the button is clicked Chrome tells me the this.
Header is
Request URL:file:///C:/xampp/htdocs/amit/reverse.php?input=Hello
Query String Parametersview sourceview URL encoded
input:Hello
and the Response is
<?php
if(isset($_GET['input']))
{
$string = $_GET['input'];
echo strrev($string);
}
?>
Now I have put a different file on my XAMPP PHP side and it works fine, but this one just doesn't response, can anyone see what I am doing wrong at all?
You need to pass the files to your webserver -- make the GET request to a URI on your web server instead of making the request to a file on your computer.
So, change the line:
C:/xampp/htdocs/amit/reverse.php
to
http://localhost/amit/reverse.php
Alternatively, if all your files are in the same directory with a structure as follows:
-- htdocs
- amit
- <somefile>.html
- script.js
- style.css
- reverse.php
Then, you could simply use reverse.php instead of specifying the full path.
Full code as an example:
$('#submit').click( function()
{
var text = $('#text').val();
$.get( 'http://localhost/amit/reverse.php', { 'input': text }, function( data )
{
$('#feedback').text( data );
});
});
You need to get the file through a request to your XAMPP server. Try something like
$.get( 'http://localhost/amit/reverse.php', { 'input': text }, function( data )
{
$('#feedback').text( data );
});
Use relative path instead of local path on your-drive. Just type the filename (if filename is in root-directory). Try not to use absolute paths (like http://localhost/reverse.php) because then you would have to change it when uploading/changing it to another server and that is not a sustainable solution.
$.get( '/reverse.php', { 'input': text }, function( data )
{
$('#feedback').text( data );
});
Secondly, I would recommend using other variable names. I think you're getting problems using text a variable because text() is function in jQuery.
Try:
var textOfElement = $('#text').val();
$.get( '/reverse.php', { 'input': textOfElement }, function( data )
{
$('#feedback').text( data );
});
An in some cases it's fine to be generic about naming, but input and text is far to genereic. Those names doesn't say a bit about the actual context.