I am reading a rss feed with php and creating html DOM from the same. Now I have a bunch of <li>'s with news feed. when a user clicks on a particular <li> I want to post certain data to another php file which performs some other function.
How I want the data is tricky. I have a URL for all the feed elements. When a user clicks on a particular feed, I need to retrieve the URL associated with that particular feed.
I want to run a $.click() function in which I am going to $.post to the next php script.
How do I get that URL without storing it in the HTML itself. I do not want to store the URL in the html document for security puposes.
I am new with PHP.
You will need to assign unique id (uid) to each list element that corresponds to the url. A good way of handling this would be a database. You send the list item's identifier, look up in the database the associated url, perform some magic, and send the response back to the client. You can use jQuery's data method that leverages the html5 data attribute to store the information. Here is the basic pseudocode.
html
<li class="feed" data-uid="12345">Go</li>
javascript
$('li.feed').click( function() {
$.post({ id: $(this).data('uid') }, function(data) {
//do something with data
});
});
php
$uid = $_POST['uid'];
//db lookup of url
//do something with url
//return data to page
you could encrypt the url being sent from the server and then decrypt when it's sent back from the client. Just use a simple salt encryption method. I assume you're going to use ajax or the like to post back from the client to the server in which case, this methodology would work for you.
alternatively, you could create an array and store the urls in a collection with an associative key that you send to the client, then look up the url on the server side by that key. You could also implement a database solution to do this same thing where the key is the ID in the db.
U have to encode the variable url...
PHP
var url = ...;
JavaScript
$(function (){ var d1 = <?php echo json_encode(array($url)); ?>;});
Related
I have a static site (let's call it settings page), and my Javascript function takes with AJAX data from mysql table and draws table on a HTML document.
It works like a charm - it takes all the data I need and doing it in a proper way.
Here's my function:
function get_people()
{
$.post("/controller/get_people", function(data,status,xhr)
{
if(status=="success")
{
people_data = data;
draw_table();
}
})
}
The thing is, on ANOTHER PAGE I have table with all people and checkboxes next to them.
I'm checking this checkboxes, clicking a button and I want to get into settings page - and my get_people function will select data from mysql only about people checked on previous page.
technically the problem is - how can I pass an array to javascript function from another page? Can I save it on a DOM or something and read it from JS?
Please provide me some ideas : ]
You can use sessionStorage and JSON.parse.
On your first page:
var arrayJSON = JSON.stringify(yourArray);
sessionStorage.setItem("tabledata",arrayJSON);
On your second page:
var tableData = JSON.parse(sessionStorage.getItem("tabledata"));
This will save the data as a string in your browser for the duration of the current session. If you want it to be stored more permanently, you can use localStorage instead of sessionStorage (same syntax) and it will be stored even if the user closes the browser and comes back later.
There's more on sessionStorage and localStorage at the MDN docs
I am developing mobile applications, and I was thinking, if I need to download a picture from a server, I cannot actually run the PHP natively (I am using a PhoneGap type setup), so how could I download a picture from a database, run it though JavaScript and then display it to the user?
I would imagine something like:
Ajax request,
Return HTML string of binary data
Do some stuff to that?
Or
Ajax request,
Return a HTML string of reference to the picture, for example: picture1.jpg.
In JavaScript, write something like document.write <img src="http://blahh/img/"+imagePath
I'm not sure what the best way to do this is.
To my mind, the simplest way to dynamically load external pictures is to get a JSON object from a PHP script containing the picture URL (like http://www.example.com/pictures/getPicture/YOUR_PICTURE_ID).
Server side
<?php
$pictureUrl = 'http://example.com/pictures/picture.jpg'; //You can get it with a database query
$pictureName = 'Foo';
$pictureAltText = 'Bar';
// You can do some stuff here.
// At the end of the script, write result.
echo json_encode(compact('pictureUrl', 'pictureName', 'pictureAltText'));
?>
Client side
<script type="text/javascript">
// With jQuery
$.getJSON('http://www.example.com/pictures/getPicture/YOUR_PICTURE_ID', function(data){
console.log(data.pictureUrl, data.pictureName, pictureAltText);
var img = new Image();
img.src = data.pictureUrl;
img.setAttribute('alt', data.pictureAltText);
img.onload = function(){
// Displaying picture when download completed
$(img).appendTo('body');
}
});
</script>
If you don't use jQuery, you have to use XMLHttpRequest to get the JSON encoded response and to parse it (you can see the MDN documentation at https://developer.mozilla.org/en-US/docs/JSON).
You can do this, but not purely in JavaScript.
Since you mentioned PHP, I will go in that direction:
make table in database in which you will store all images. You need
to have some kind of image_content field and load every image in
some baseline64 encoder like:
http://www.motobit.com/util/base64-decoder-encoder.asp. And store
returned string into that image_content field.
Or you can write some script that will convert all images you want
to Base64 directly in PHP by using http://php.net/manual/en/function.base64-encode.php.
make a PHP file. For example, giveme_encoded_img.php in that file you
need to have one parameter in the URL like gimme_encoded_img.php?image_name=header_bg.
Then get image_name with $_REQUEST and do a MySQL query with that
data in the WHERE statement so that you can select an encoded image string
from the database.
After that, just print it.
When you do an Ajax request to a file above, just update the desired
image src with the response. The best way for doing this is to take the response
and get some element by id, like
var header_bg = document.getElementById('header_bg'); header_bg.src
= response;
The final HTML needs to look something like this:
img alt="Embedded Image" id="header_bg" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..."
Baseline64 embedding is really good, especially if you need to embed images in emails, then a lot of email clients show them by default instead of hiding the remote images from your server.
I hope I was clear enough.
Still this is not a purely JavaScript solution.
I try to filling some data from one website into another website, which both website are not holding in the same server and I have no right to access into the back end of the other website.
For example:
I created a website that will collect the following data from the user
- name
- telephone number
- address
Then I have to pass those data (auto fill-in so that I do not have to manually enter the same data) into the other independent website for user information checking (t0 make sure that the address, telephone and address is the valid data).
Does anyone know how can I do it in php/javascript? Any example or tutorial can show?
I would use JSONP to move data between different domains and use JQuery's getJSON method to make a call to the server. The PHP file should return the data in proper format and the client should be able to read it using JQuery.
Here is a sample:
The server-side PHP code
<?php
header("content-type: application/json");
// Create a generic object.
// Assign it the property 'message' - the feedback message we want the user to see.
$rtnjsonobj->message = "You got an AJAX response via JSONP from another site!";
// Wrap and write a JSON-formatted object with a function call, using the supplied value of parm 'callback' in the URL:
echo $_GET['callback']. '('. json_encode($rtnjsonobj) . ')';
?>
Get data from client
$(document).ready(function() {
$("#jsonpbtn").click(function() {
var surl = "http://www.otherdomain.com/abovepage.php?callback=?";
$.getJSON(surl, function(rtndata) {
alert(rtndata.message);
});
});
});
What your asking is exactly cross-site scripting (XSS). All modern browsers will prevent you from executing any front-end (JS) script on any url which is not in the original domain.
You can try passing GET values into the page and if the devs built handles into their PHP for that, you might be able to populate the fields. I highly doubt this would work because of the massive security hole it would expose.
I don't know what it is your trying to do at the end of the day, but BE VERY CAREFUL. XSS is an exploit and there's a good chance you could get into trouble for it.
I need to redirect users to a unique url when they visit a specific link which corresponds to a certain/row/column in the mysql database.
Here is what I mean:
The mysql database has a table table123 with a row id 123 and inside a column name "column123".
This row and column correspond to the webpage1.html
Normal javascript redirection is like this:
<script>location.replace('http://website.com/webpage2.html');</script>
What I need to do is extract the value from column123 of the webpage1.html and add it to the redirection url, so it would redirect specifically with that value.
For example:
<script>location.replace('http://website.com/webpage2.html/go/dbtable123row123column123value');</script>
This redirection script will be placed on top of the php page that will call the other php pages, so it has to be dynamic every time, thus the redirection script has to use dynamic placeholder, not static value, except the domain name.
Thanks
If the table really is mysql table and the javascript has no way to access that information, follow other suggestions and deal with it on the server-side. If somehow, the table data are printed on the html document where you want the redirect to take place then you can consider the following. (Though, it would really make more sense to manage this server-side).
Assuming you have given unique id to your column and assuming that the table is on the web page that you have your location.replace call on.
location.replace("http://website.com/webpage2.html/go/" + $('#column123').text())
Without jQuery, you could use
document.getElementById('#column123').innerHTML (or text?)
If it is not practical to assign an id to the column, you can possibly use some jQuery selector magic with :eq
location.replace("http://website.com/webpage2.html/go/" + $('#dbtable123 > tr:eq(1) > td:eq(3)').text())
(none tested)
Assuming you can't redirect in PHP for whatever reason, here's what I'd do. Grab the proper web page from your database using AJAX. I'd suggest using a library such as jQuery to help you do that. If you use jQuery it'll look something like this:
$(function() {
$.get(
'/script/that/queries/db.php',
'your=query_string&goes=here',
function(data) {
if(data.url.length > 0) {
location.href = data.url;
}
},
'json'
);
});
You didn't specify when you want this redirect to fire, so I just put it in the standard body onload. Anyway, after you write that $.get() function call, then in your /script/that/queries/db.php, you'll want to perform your database query based on the get variable(s), and print a JSON encoded array with the valid page you want to redirect to:
$json = array('url' => '/webpage2.html');
print json_encode($json);
Of course I've just written some pseudo code, but hopefully it'll help get the idea across. You'll want to make sure you validate/sanitize all info being querying the database, etc.
Do it simply.Make dynamic url with php script.
header('Location: http://website.com/'.$table123row123column123);
Another question by a newbie. I have a php variable that queries the database for a value. It is stored in the variable $publish and its value will change (in the database) when a user clicks on a hyperlink.
if ($publish == '') {
Link to publish.html
} else {
Link to edit.html
}
What is happening in the background is i am querying a database table for some data that i stored in the $publish variable. If the $publish is empty, it will add a link for publish.html in a popup. The popup will process a form and will add the data to the database and which means that the $publish is no more empty. What i would like to achieve is that as soon as the form is processed in the popup and a data has been added to the database, the link should change to edit.html. This can happen when the page will re-query the database but it should happen without page refresh.
How can it be donw using javascript, jquery or ajax?? Please assist.
Javascript by itself cannot be used to deal with database. That is done using php (Or the server side language of your choice). Ajax is used to send a request to your php script using javascript which will in turn communicate with the db. And it doesn't require a page refresh.
So what you are trying to do can be easily achieved using ajax. Since you mentioned jquery, you can check out the $.ajax or $.post methods in jquery which make the process even more simple.
You need to process the form using ajax. The ajax request is sent to a php script which will make the necessary changes in the database and send the new link (link to edit.html) in the response. Upon getting the response, just replace the current anchor element with the new one ..
for eg..
$.post(url, formdataobject , function (resp) {
$("a.youra").text('edit').attr('href', resp);
});
url - where the php script is located
formdataobject - a javascript object that will have the form data as key value pairs
the third parameter is an anonymous function also known as callback function since it will be invoked only when the response is received from the server. This is because ajax requests are asynchronous.
Inside the callback function, jquery is used to change the text inside the anchor element to edit and the href attribute is changed to value that came in the response.
$.post means we are using the post method. so the parameters can be accessed as elements of $_POST array in php.
After updating the db, you can simply echo out the new link and it will be received in the response.
Also, there are other formats in which you can get the response for eg. xml, json.
I'll try to leave the technical jargon aside and give a more generic response since I think you might be confused with client-side and server-side scripting.
Think of javascript as a language that can only instruct your WEB BROWSER how to act. Javascript executes after the server has already finished processing your web page.
PHP on the other hand runs on your web server and has the ability to communicate with your database. If you want to get information from your database using javascript, you'll need to have javascript ask PHP to query the database through an AJAX call to a PHP script.
For example, you could have javascript call a script like:
http://www.myserver.com/ajax_function.php?do=queryTheDatabase
In summary: Javascript can't connect to the database but it can ask PHP to do so. I hope that helps.
Let me try, you want to change the link in a page from a pop-up that handles a form processing. Try to give your link a container:
<div id="publish_link">Publish</div>
As for the form submission use Ajax to submit data to the server to do an update and get a response back to change the link to edit or something:
$.post("submit.php", { some_field: "some_value"}, function(response) {
if(response.isPublished)
$('#publish_link', window.opener.document).html('Edit');
});
Basically your publish link is contained in a div with an ID publish_link so you change its content later after data processing without reloading the page. In the pop-up where you would do the form processing it is done using jQuery Ajax POST method to submit the data. Your script then accepts that data, update the database and if successful returns a response. jQuery POST function receives that response and there's a check there if isPublished is true, get the pop-up's opener window (your main window) and update the link to Edit. Just an idea, may not be the best out there.
It cannot be made with javascript, jquery or ajax. only server side script can query a database. with ajax request you can get the script output. ajax requests can be sent either with pure javascript or jquery.
Well, i think i understand your quaestion, but you have to get a starting point, try to understand this:
try to understand what are client variables and server variables.
javascript does not comunicate with database.
you can use javascript to retrieve data to a specific "Object variable".
Using ajax methods of jquery you can post that data do other page, that will execute the
proper actions
you can ;)
at first you must create php file to query database and return something like true or flase and then with file url check the function and get answer
function find_published(folder_id) {
var aj_url = "{{server_path}}/ajax/url"
var list;
$.getJSON(aj_url+"?callback=?&",
function(data) {
//here is your data... true false ... do every thing you want
}
);
};
this app for node.js does mysql queries https://github.com/felixge/node-mysql
You need to use AJAX for this, like .post() or .get() or JSON.