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.
Related
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
What Im trying to do: Display a loading gif or text... at the very least show a black screen before and during the time the php is being executed.
What I have tried.
I have tested using flush () and I get nothing until the entire php process is finished. I dont particularly like this concept either but I'll take anything.
I am considering using two pages to accomplish this though the current project is nearly complete and would take some time to consolidate the scattered html/php code.
Currently I'm doing 3-simpleXML_load_file(), 1-include(), 1-file_get_contents()
I have javascript function plotting data from one of the simpleXML_Load_file()...
Im up for moving parts of the code to a different file but it's a big task. So id like some advise or suggestions on how to proceed.
If I need to elaborate more just ask!
Thanks,
JT
<html>
<head>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
?>
<script type="text/javascript">
<!--Plot function-->
$(function()
{
var d =
[
<?php
//Pulling in hourly data to plot temp vs time
$i=0;
$array=array();
while ($i<=100)
{
echo '['. (strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000) .','.$weather_hourly->data->parameters->temperature->value[$i] .'],';
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$value = (string) $value;
$min_sec_array[] = $value;
}
?>
</script>
</head>
<body>
<div id=graph>
</div>
</body
The main way you can accomplish this is by using AJAX and multiple pages. To accomplish this, the first page should not do any of the processing, just put the loading image here. Next, make an AJAX request, and once the request is finished, you can show the results on the page or redirect to a different page.
Example:
File 1 (jQuery must be included also), put this in the body along with the loader animation:
<script language="javascript" type="text/javascript">
$(function(){
var mydata = {};
$.post('/myajaxfile.php', mydata, function(resp){
// process response here or redirect page
}, 'json');
});
</script>
Update: Here is a more complete example based on your code. This has not been tested and needs to have the jQuery library included, but this should give you a good idea:
File 1: file1.html
</head>
<body>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
?>
<!-- Include jQuery here! Also have the loading animation here. -->
<script type="text/javascript">
$(function(){
$.get('/file2.php?Lat=<?php echo $lat; ?>&Lon=<?php echo $long; ?>', null, function(resp){
// resp will have the data from file2.php
console.log(resp);
console.log(resp['min_sec_array']);
console.log(resp['main']);
// here is where you will setup the graph
// with the data loaded
<!--Plot function-->
}, 'json');
});
</script>
<div id=graph>
</div>
</body
</html>
File 2: file2.php
I'm not sure if you needed the $min_sec_array, but I had this example return that as well as the main data you were using before.
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
//Pulling in hourly data to plot temp vs time
$i=0;
$main = array();
$array=array();
while ($i<=100)
{
$main[] = array((strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000), $weather_hourly->data->parameters->temperature->value[$i]);
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$min_sec_array[] = (string) $value;
}
echo json_encode(array(
'min_sec_array' =>$min_sec_array,
'main' => $main
));
exit();
?>
I would recommend not to do this with plain html and php if u expect it modify the page after it is loaded. Because php is server side processing, so it is executed before the page is send to the user. U need Javascript. Using Javascript will enable u to dynamically add or remove html elements to or from the DOM tree after the page was send to the user. It is executed by the users browser.
For easier start I would recommend jQuery, because there are lots of tutorials on such topics.
JQuery
JQuery learning center
A small example:
HTML
<head>
<meta charset="utf-8" />
<title> </title>
<script type="text/javascript" src="js/lib/jquery-1.9.1.js"></script>
</head>
<body>
<h1>Addition</h1>
<div id="error_msg"> </div>
<div id="content">
<!-- show loading image when opening the page -->
<img src="images/loading.gif"/>
</div>
<script type="text/javascript">
// your script to load content from php goes here
</script>
</body>
this will be nothing more then the following until now:
adding the following php file
<?php
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
$result = $num1 + $num2;
echo '<p>Calculating '.$num1.' + '.$num2.' took a lot of time, but finally we were able to evaluate it to '.$result.'.</p>'
.'<p> '.$num1.' + '.$num2.' = '.$result.'</p>';
?>
wont change anything of the html, but adding javascript/ Jquery inside the HTML will be kind of connection between static html and server side php.
$(document).ready(function(){
$.ajax({ // call php script
url: 'php/script.php?num1=258&num2=121',
type:'GET',
timeout: 500,
contentType: 'html'
}).success(function(data){
// remove loading image and add content received from php
$('div#content').html(data);
}).error(function(jqXHR, textStatus, errorThrown){
// in case something went wrong, show error
$('div#error_msg').append('Sorry, something went wrong: ' + textStatus + ' (' + errorThrown + ')');
});
});
This will change your page to show the loading animation until the php script returns its data, like:
So you can setup the whole page in plain html, add some loading gifs, call several php scripts and change the content without reloading the page itself.
It is kind of nasty solution to your problem...
But this can work:
You work with those -
ob_start();
//printing done here...
ob_end_flush();
at the beginning you will create your rotating ajax gif...
Then you do all the processing and calculating you want...
At the end of the processing, just echo a small script that does a hide to your gif...
Depends on the exact need, maybe ajax can be more elegant solution.
In response to your conversation with David Constantine below, did you try using ob_flush()?
ob_start();
echo '<img src="pics/loading.gif">';
ob_flush();
// Do your processing here
ob_end_flush();
I think you don't have a problem with flushing your PHP output to the browser, but more likely with getting the browser to start rendering the partial html output. Unfortunately, browser behavior on partial html is browser-specific, so if you want something to work the same in any browser, the AJAX solution suggested in other answers is the better way to go.
But if you don't like that added complexity of a full AJAX solution, you can try to make your html output "nice" in the sense of providing some body output that can be formatted without needing the rest of the html output. This is were your sample code fails: It spends most of its time outputting data into a script tag inside the html header. The browser never even sees the start of the body until your PHP code has practically finished executing. If you first write your complete body, then add the script tag for the data there, you give the browser something to at least try to render whilst waiting for the final script to be completed.
I've found the same issue (albeit not in PHP) discussed here: Stack Overflow question "When do browsers start to render partially transmitted HTML?" In particular, the accepted answer there provides a fairly minimal non-AJAX example to display and hide a placeholder whilst the html file hasn't completely loaded yet.
I know this is an old question, but the answer provided in this page by rpnew is extremely clear and easy to adjust to your project's requirements.
It is a combination of AJAX and PHP.
The HTML page PHPAjax.html which calls the PHP script:
<html>
<head>
<script type="text/javascript">
document.write('<div id="loading">Loading...</div>');
//Ajax Function
function getHTTPObject()
{
var xmlhttp;
if (window.ActiveXObject)
{
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E)
{
xmlhttp = false;
}
}
}
else
{
xmlhttp = false;
}
if (window.XMLHttpRequest)
{
try
{
xmlhttp = new XMLHttpRequest();
}
catch (e)
{
xmlhttp = false;
}
}
return xmlhttp;
}
//HTTP Objects..
var http = getHTTPObject();
//Function which we are calling...
function AjaxFunction()
{
url='PHPScript.php';
http.open("GET",url, true);
http.onreadystatechange = function()
{
if (http.readyState == 4)
{
//Change the text when result comes.....
document.getElementById("content").innerHTML="http. responseText";
}
}
http.send(null);
}
</script>
</head>
<body onload="AjaxFunction()">
</body>
</html>
The Background PHP Script PHPScript.php:
<?php
sleep(10);
echo "I'm from PHP Script";
?>
Save both files in the same directory. From your browser open the HTML file. It will show 'Loading...' for 10 seconds and then you will see the message changing to "I'm from PHP Script".
My question is that how to pass query string variables on same page without refreshing the page in php? My code is given below:
<img src="a.jpg">
<?php
$a = $_GET['id'];
$b = $_GET['pid'];
?>
Please help me to resolve this issue
<html>
<head>
<title>Test</title>
<meta name="" content="">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#image_id").click(function(){
var dataString = 'a=10&b=20';
$.ajax({
type:'POST',
url:'foo.php',
data:dataString,
success:function(data) {
if(data=="Something") {
// Do Something
} else {
// Do Something
}
}
});
});
});
</script>
</head>
<body>
<img id="image_id" src="images/bg.jpg" />
</body>
</html>
Then in the 'foo.php' page do this
if(isset($_POST['a'])) {
// DO SOMETHING
}
Remember the things that you want to send to the 'data' of
success:function(data)
must be echoed out in the foo.php page
You can't.
PHP requires execution on the server and so you'd have to either use AJAX and update your page accordingly, or just refresh your page.
You can by sending an AJAX request to the server. Ajax is a way to send asynchronous request via Javascript. Notice that jQuery has a good library about it.
Use jquery to resolve this. By using the $.ajax in jquery you can do the stuff you need without page refresh.
I have .js and .php files and html pages. I am including js files in html files and php files in js files.
I want to pass 'cat' value from js file to php file using address bar when I go to this page;
/demo/convert.html?cat=volume
But I have no idea how to do this.
By the way, this is a blacberry project and I am not sure if I can use address bar to pass value. Any idea is welcome.
Test this sample code with an URL like :
http://sputnick-area.net/test/index.php?foobar=works_as_a_charm
<?php
$var = $_GET['foobar'];
echo <<<EOF
<html>
<head>
<title></title>
</head>
<body>
demo of using PHP GET variable in Javascript :
<script type="text/javascript">
alert("$var");
</script>
</body>
</html>
EOF
?>
Edit :
if you'd like to handle GET variables from within JavaScript, consider the following HTML + JavaScript sample : http://sputnick-area.net/test/index.html?foobar=works_as_a_charm
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var vars = [], hash;
var hashes = window.location.href.slice(
window.location.href.indexOf('?') + 1
).split('&');
for(var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
alert(vars['foobar']);
</script>
</body>
</html>
Sure you can. When your JS function is called, you would have to do something like this:
function someFunction(someParameters) {
//Do whatever you need to do
window.location = "/demo/convert.html?variableName=" + variable;
}
This will cause a page reload with the new variable accessible through PHP in the $_GET array. For example:
<?php
$name = $_GET['variableName'];
if(length($name) < 3) {
echo "That is a short name!";
}
?>
A page reload (used here), is necessary to send value to PHP as it is run server side. Your only other solution would be to use AJAX and load page content dynamically. This, however, would be the simplest solution.
EDIT:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var urlvariable = getUrlVars()['variableName'];
I am using below code for automatically redirect to the page in a fraction of seconds.
<script language="Javascript" type="text/javascript">
<!--
var testTimerID;
testTimerID = window.setTimeout(autoDirect, 30*250 );
function autoDirect() {
window.location = 'home';
}
</script>
This script works fine in all browser except in safari browser.it does not automatically redirect to the another page(home). what is the issue?.how can i solve it?.
Try it like this:
<script language="Javascript" type="text/javascript">
//<!--
var testTimerID;
testTimerID = window.setTimeout(function(){
window.location.href = '/home';
}, 30*250 );
//-->
</script>
Usually JS does not work properly and in same way through all the web browsers... Therefore I advise to use jQuery as it is debugged for all common browsers...
Try aslo reading through this: How to redirect to another webpage in JavaScript/jQuery?
Also instead of relative URL You shoudl use absolute like http://www.mydomain.com/home/, so the code should be:
...
window.location.href = 'http://www.mydomain.com/home/';
...
.
This works perfectly in Safari 5 for windows
<script language="Javascript" type="text/javascript">
var testTimerID;
testTimerID = window.setTimeout(autoDirect, 30*250 );
function autoDirect() {
window.location = 'http://google.com/';
}
</script>