AngularJS with PHP to get and update a link - php

I am trying to use AngularJS to access a PHP variable. Here is my HTML and Angular code:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="mainCtrl">
Your Link: <div> <span ng-bind="fetchLink.link"></span></div>
</div>
<script>
angular.module('myApp', [])
.controller('mainCtrl', ['$http', function($http) {
var self = this;
self.link = "";
self.newTodo = {}; //Keys (as in key: value pairs) are automatically created when declared in form
var fetchLink = function() {
return $http.get('link.php').then(
function(response) {
self.link = response.data;
}, function(errResponse) {
console.error('Error while fetching notes');
});
};
}]);
</script>
</body>
</html>
And here is my PHP:
<?php
{ $link = 0x00;
"link":[{$link}];
$link= ($link + 1);
}
?>
I am trying to use the Angular code to access the 'link' variable that has to be updated each time it is accessed by any user (a hexidecimal value that is increased by 1). This is so that each user gets a unique link which they can access and share with their friends. When i preview the html page it just says your link: without any value next to it. I also thought about using a JSON object which I believe plays nicely with Angular, but I don't know if JSON objects can be updated with each use (because they are a client-side object, not server side).

<?php
$link = "http://example.com/".time();
echo json_encode(array("link"=>$link));
?>
Use time() and something else like rand() for create unique link and return link in json using json_encode() function.

Related

Change value of PHP variable with AJAX

The PHP:
<?php
$mainView = "views/dashboardView.php";
?>
The HTML:
<div class="mainContent">
<?php include($mainView); ?>
</div>
I would like the click event of a button to change what view .mainContent shows and I believe AJAX can accomplish this but as yet have not been able to get it to work.
Any advice?
You would have to modify your PHP script to allow for this.
For example:
PHP:
if (isset($_POST['change']))
{
$mainView = $_POST['change'];
echo $mainView;
}
HTML & jQuery:
<button id="change">Change the var</button>
<script>
$("#change").click(function() {
$.post("file.php", {change: $(this).val()},
function (data)
{
$("#mainContent").html(data);
});
});
</script>
<script type="text/javascript>
function changePage(pageDest){
var xmlobject = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlobject.onreadystatechange = function (){
if(xmlobject.readyState == 4 && xmlobject.status == 200){
document.getElementById("mainContent").innerHTML = xmlobject.responseText;
}
else{
document.getElementById("mainContent").innerHTML = 'Loading...';
}
}
xmlobject.open("GET",pageDest,true);
xmlobject.send();
}
</script>
<div class="mainContent" id="mainContent">
Change this HTML
</div>
<div onmouseup="changePage('views/dashboardView.php')">Get dashboard view</div>
The parameter in the changePage function is the location of the page that you would like to place in your mainContent <div>
Does this help?
You cannot change the value of a PHP variable, as PHP is Server Side (done first), and JS is Client Side (done after Server Side).
Typically AJAX is used to repopulate an area of a web page, but that would suit your purpose. In the example below, ajax/test.php is the new file you want to include. Obviously change the path/name as you wish, and create that file.
I will add though, if you are repopulating a large chunk of your page, it will probably be just as quick to fully reload it.
$(function(){
$('.your-button-class').on('click', function(){
$.post('ajax/test.php', function(data) {
$('.mainContent').html(data);
});
});
});
Storing the View in the session, will keep the site displaying this view until the user closes the browser and ends the session, the session expires or they change the view again.
The include that sets mainView
<?php
session_start();
$mainView = "views/dashboardView.php"; // default
if(isset($_SESSION['mainView']))
{
$mainView =$_SESSION['mainView'];
}
?>
// the ajax script that sets the mainView
<?php
session_start();
$_SESSION['mainView']='views/'.$_GET['mainView'].'.php';
?>
the javascript link for ajax
ajaxURL='ajax.php?mainView=otherDasboard';
you may also want to check for empty session variable and that the file exists before setting it

How to save file after it had been edited with jquery using php?

Here I created a jquery function that gets css-color and creates element with background of css-color: Edit my jsFiddle
html
<div ID="wrapper">
<div ID="addColor">
<input type="text" ID="hex">
<div ID="color">Your color</div>
<button ID="add">Add color</button>
<div CLASS="clear"></div> <!-- Clear float -->
</div>
<div ID="wrapGallery">
<h1>My Color Gallery</h1>
<ul ID="gallery"></ul>
</div>
</div>
js/jquery
$(function() {
//float left with some margin
$('#addColor')
.children().not('#add, .clear').css({
'float':'left',
'margin-right': '5px'
});
//Showing color on keyup
$('#hex').keyup(function() {
var hexCode = $(this).val();
$('#color').css('background-color', hexCode);
if ( hexCode !== '') {
$('#color').text('');
}else{
$('#color').text('Your color');
}
});
//Adding colors
$gallery = $('#gallery');
$('#add').click(function() {
var storedHex = $('#hex').val();
//check if empty
if (storedHex == '') {
alert('Enter something');
}
else {
//adding li
$("<li>").css('background-color', storedHex)
.hover(
function () {
$(this).text(storedHex);
},
function () {
$(this).text('');
})
.appendTo($gallery);
}
});
});
The only thing I need to do is to save the created elements permanently in the file, so I can access whenever I want. I have no idea how to do that.
It is currently not possible for Javascript (in a browser) to edit/save files like you want. However, you can use .ajax() to send the data back to a PHP file so that the PHP file can save it using file_put_contents() (though it would usually save it in a database instead).
Read up on JQuery Ajax function and also read about JSON objects.
With AJAX and JQuery you can easily send a JSON object to your server like so:
function saveElements(myJsonObj) {
$.ajax({
method: "POST",
dataType: "json",
url: "path/to/savemyobject.php",
data: {json:myJsonObj}
});
}
A JSON file may look something like this:
{ "myData":
{
"some_text":"this could be the CSS code",
"name":"some name",
"number":"some number"
}
}
You could generate a JSON string representing a JSON object and send it to a PHP file with the Ajax function (as above).
In PHP you would do this to obtain the object:
<?php
$json_string = $_POST["json"]; //the same variable key we sent it in
$json_obj = json_decode($json_string, true);
// get data
$myDataCode = $json_obj["myData"]["some_text"];
// do some processing
...
?>
You could also convert an array in PHP to a JSON object using the PHP json_encode function.
Read more:
http://www.w3schools.com/json/default.asp
http://php.net/manual/en/function.json-decode.php
http://php.net/manual/en/function.json-encode.php
http://api.jquery.com/jQuery.ajax/

How to pass value from javascript to php using address bar

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'];

Pass JSON from php to javascript

I want to localize my webapp. Since localization through javascript only is not recommended I thought using php would be an alternative.
So with php I read a messages.json file that stores all localization data.
$json = file_get_contents("_locales/en/messages.json");
In the header of my webapp I generate some javascript with php according to the user's browser language.
echo "var localeObj = " . $json . ";";
So this is just a var that holds all data from the messages.json file that looks like that
{
"extTitle": {
"message": "Test1"
},
"extName":{
"message": "Test2"
}
}
Now I want to be able to access each item from the json like
var title = getItem("extTitle");
and it returns Test1. Any idea how to do that?
I am not very familar with json but if I just alert the localeObj it gives me just [object Object].
var getItem = function(item) {
return localObj[item].message;
};
You could always encapsulate your i18n strings too...
(function() {
var localObj = { ... };
window.getItem = function(item) {
return localObj[item].message;
};
})();
This way, no other variables can possibly clobber your localObj.
You use array syntax [], or dot syntax ., to access javascript object properties.
Example:
localeObj["extTitle"];
localeObj.extTitle;
I would recommend reading something like this to get more familier with JSON.
You can initialize javascript variable like this.
var json = eval(<? echo $json ?>);
alert(json.extTitle.message+ ' '+json.extName.message);
Inside messages.php:
<?php
header('Content-type:application/javascript');
$messages = array(
"yes"=>"hai",
"no"=>"iie"
);
$messages = json_encode($messages);
echo "window.messages = $messages";
?>
Inside index.html:
<html>
<body>
<script type="text/javascript" src="messages.php"></script>
<script type="text/javascript">
console.log(window.messages)
</script>
</body>
</html>
As long as you tell the browser to interpret the php file as a javascript file, you can echo anything you want.

is my code victim of same origin policy?

Here is my code. You have to kindly look does it suffer from 'same origin policy' in this shape. The domain for HTML is (http://127.0.0.1/jqload.html) & php file (http://127.0.0.1/conn_sql.php). This is json format : [{"options":"smart_exp"},{"options":"user_int"},{"options":"blahblah"}]
I actually want to append json data that I receive in HTYML with user input & I am suffering in that. If I use eval for parsing, it works fine to point its put here. But if I use JSON.parse to parse, the whole code stops working & this error message is issued '"IMPORTANT: Remove this line from json2.js before deployment". I put my code for some other question on stackoverflow forum & I was told that my code suffer from 'same origin policy' that causes the problems in appending JSON data. So can you kindly see does my code suffer from this policy? Though I have doubts it suffers from that policy as I learn that it restricts if files reside on different domains, here both files reside next to each other.
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html><head></head>
<body>
<form name="index">
<p><input type = "text" id = "txt" name = "txt"></input>
<p><input type = "button" id = "send" name = "send" value = "send" onClick=
"ADDLISTITEM"></input>
<p><select name="user_spec" id="user_spec" />
</form>
<script>
function ADDLISTITEM()
{
alert (json.length); // working
alert json.options[1]; // do not show any value, message just for testing
json.options[json.length+1] = 'newOption'; //not working; HELP HERE
jsonString = JSON.stringify(json);//working fine for current data
alert(jsonString);
//here I have to implement send this stringify(json) back to server,HELP
//HERE
}
</script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var json;
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
json = jsonData;
$.each(jsonData, function (i, j) {
document.index.user_spec.options[i] = new Option(j.options);
});
});
});
</script>
</body>
</html>
You're on the right track, but here: $.each(jsonData, function (i, j) { ... } you are actually looping through each character of the jsonData string, and not the json object. Just change jsonData to json inside the $.each(), and it should work fine (regardless of whether you're using eval or JSON.parse, but I recommend the latter).
Edited: Since you are using jQuery.getJSON(), you don't need to use eval or JSON.parse - jQuery does it for you. So inside your callback function, just set json = jsonData .
<script>
var json;
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
json = jsonData;
$.each(json, function (i, j) {
document.index.user_spec.options[i] = new Option(j.options);
});
});
});
</script>

Categories