Send data to website through widget on blog - php

I am looking to create a widget/plugin that can send across a simple variable when clicked. The idea is that when this widget is added to a blog, and clicked by one of its readers, it sends a message across to my domain (for example, www.example.com) with the url of the blog in question (Which can then be used to increment a count or something, for example).
I'm very new to widgets/plugins, so I am not entirely sure if this is possible. I am not looking to be spoonfed with code, just a few pointers in the right direction would be of immense help.
Forgive me, I am yet to try anything as I am unsure of where to start. Please let me know if I need to give any more information, if my tags are incorrect, or if my question is unclear!

Most distributable widget would have following aspects :
Widget Script (Controlled by you) and included by end user in their site.
Something like <script src="http://example.com/yourAwesomeScript.php"></script> where example.com is your site or cdn.
Widget Container (Embedded by the end user) to tell the script where to inject the widget code. If your widget is not position container dependent (for eg. fixed/absolute elements) this can be skipped.
You can use Javascript library such as jQuery to make your life easier to code in Javascript.
I have below very basic widget to subscribe. I am using PHP to output Javascript this will allow your widget to send dynamic data. You can also pass params to your script like
http://example.com/yourAwesomeScript.php?user_key=1234564789
end-user.html
Head
<script src="http://example.com/yourAwesomeScript.php"></script>
Body
<div id="widgetCont"></div>
yourAwesomeScript.php
<?php
if($_POST){
if($_POST['email']){
$new_subscribed = true ; //check and add to database and return if subscribed
if($new_subscribed){
echo "You have successfully subscribed";
}else{
echo "You are already subscribed";
}
}
}else{
?>
$(document).ready(function(){
$input = $('<input/>').prop("type","text").prop("id","widget_email");
$submit = $('<input/>').prop("type","button").prop("value","Subscribe").prop("id","submit_email");
$('#widgetCont').html($input,$submit);
$('#widgetCont #submit_email').click(function(){
$.ajax({
url : "http://example.com/yourAwesomeScript.php",
method : "post",
data : {email:$("#widget_email").val()},
success :function(data){
alert(data);
}
})
});
});
<?php
}
?>
I hope this helps.

In PHP you can use cURL to activate code on another domain. You can set GET or POST variables in cURL that will be sent to that page. These can then be manipulated in PHP via the $_GET and the $_POST arrays.
example of cURL:
http://php.net/manual/en/curl.examples-basic.php

You should try to set up a HTTP service on your domain and then create a widget which perform POST requests against your HTTP service.
A good function for this would be cURL in PHP.
Client URL Library
Here is a small guide of how to use cURL
cURL guide

Related

Filling data from one website into another website in php/javascript

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.

PHP redirect to pdf then navigate to another page?

I am using php and an apache server. My application gathers data from the user, put's it in a database, then uses PDFLib to display the formatted data back to the user as a pdf. My problem is, I would like the pdf to display as a new page, this works. But, I also have a blank page left up with the URL containing the variables used to display the pdf. I would like this page to show a different summary page, in HTML, without the variables in the URL, but I don't know how to do that. In the code that follows, I am going to the summary page if the medical flag is false. What I would like is to go to BOTH pages if the medical flag is true. Is this possible?
if($medical_flag) {
header("Location: {$_SERVER['PHP_SELF']}/./index.php?step=wc_pdf&id={$event_id}");
} else {
header("Location: {$_SERVER['PHP_SELF']}?step=success&id={$event_id}");
}
exit;
OK, I understand how this is impossible, but I still haven't figured out how to solve the problem. I thought I could toss the opening of the PDF back at jQuery with something like this:
jQuery(document).ready(function ()
{
function display_pdf_page(data, textStatus) {
var current_record = data || {};
//somehow display the pdf now
}
function show_pdf(eventid){
jQuery.getJSON(
'./inc/get_current_record_data_json.php',
{'id': eventid},
display_pdf_page
);
}
...
});
Then after I process the data in php "call" the above using:
echo '<script type="text/javascript">'
, 'show_pdf($event_id);'
, '</script>';
But that doesn't work either, php doesn't know where to find show_pdf. My lack of understanding of client/server side events is killing me here. Call be obtuse... I don't get it.
This solution will not work as designed.
First, if you want to hide the data, you should switch to POST rather than GET. This way, the data is included in the HTTP payload instead of the URI.
Secondly, you should either include a hidden iframe for javascript to access the page for which generate the PDF. On successful execution of the AJAX call (or whatever method you use), you can then redirect the page to your desired destination.
As suggested by sixeightzero, POST should be used instead of GET in such cases.
However, maybe you could accomplish the desired effect with a big iframe spaning the window (100% width and height)?

Why can't I query the wordpress database from a php script?

I also posted this at the Wordpress forums:
http://wordpress.org/support/topic/how-to-query-post-content-with-javascript?replies=1
but no one replied, so I thought I'd try SO as well.
I'll lay out the code that I'm using in its entirety, but what it boils down to is, how do I get the content of a post from the wordpress database and replace the contents of an HTML with that content?
At page load time, I have php that generates the post ID for the corresponding image, i.e.:
onmousedown="javascript:getDescription('<?php the_ID(); ?>');"
That onmousedown() calls a javascript that passes the value of the post I want to query to a php file, i.e.:
`<script type="text/javascript">
function getDescription(for_id) {
$.ajax({
type: 'GET',
url: "<?php bloginfo('template_url');/>/assets/includes/get-description.php?id=" + for_id,
success: function(data, textStatus, jqXHR){
$('#textdescription').html(data);
}
});
}
</script>`
The php file get-description.php then should do the query and return the post contents, which the javascript then uses to update the <div> contents:
`<p><?php
$contentVar = $_GET['id'];
$post = get_post($contentVar);
$content = $post->post_content;
echo $title;
?></p>`
So this is all tested and working, except for the php file that is supposed to do the database query--- I can't get it to return anything when I query. I can return other content including my incoming post id, so I know all the pipes are connected and working.
I'm not a very sophisticated programmer, so it's probably something really simple and fundamental that I'm missing. But I would be ever so grateful if you could help me figure it out. Thanks!
Have you tried including the necessary WordPress headers in the PHP file you want to make the call to get_post() from?
try slappin this at the top of your get-description.php file...
<?php require_once ('path/to/wordpress/wp-blog-header.php');?>
The header should be included at the global scope (outside of any function) or you may run into some problems with WordPress thinking it hasn't been configured/installed.
You can also try following the instructions here: Integrating WordPress with Your Website
Consider putting your get-description.php code as part of a plugin, and then look at the Wordpress Codex for step by step instructions on how to make it all work. Specifically, Ajax on the Viewer Facing side and 'wp_ajax_my_action', which in your case might be 'wp_ajax_get_description'.
Quick Update: Bear in mind that calls to get_post() go through all the standard filters, so you should also quickly check to see if any other plugins are affecting the call.

PHP GET variable in same document

how can i pass a variable from javascript to php using same file
in this example page keeps refreshing and i don't get to see the result
it works only if i separate the scripts... but i need it somehow like on ajax..
<SCRIPT language="JavaScript">
var carname="Volvo";
location.href="http://localhost/put.php?Result=" + carname;
</SCRIPT>
and this is the seccond part of the script ( they are both in same file )
<?php
Id = $_GET[Result];
echo $dbId;
?>
As Brian said you should put it in a conditional statement.. also your PHP is bad. Try the following
<?php if(isset($_GET["Result"])) : ?>
// do work with set variable
<?php $dbID = $_GET["Result"];
echo($dbID); ?>
<?php else : ?>
// "Result" not set
<SCRIPT language="JavaScript">
var carname="Volvo";
location.href="http://localhost/put.php?Result=" + carname;
</SCRIPT>
<? endif; ?>
I think this is a good exercise if you're trying to learn the Ajax method, in the real world I recommend using a framework like jQuery. Of course understanding how this works will help you build better applications in the end.
So you could do something like this in the PHP script:
if (!isset($_GET['Result']))
{
// include the javascript portion with the redirect
}
I'm with the others, though--I'm not seeing the value in a page load followed by an immediate redirect to the same page.
What you are trying to do cannot be done. Your script runs on the client in real time but the php will run on the server during the request. You will need to make an AJAX request.
First you will want to use Firefox with firebug and the web developer toolbar. Firebug gives a great view of ajax traffic and the web developer toolbar helps you see what's going on in the page.
Use jQuery make an ajax request to "send" the value to another php file. Don't be afraid to separate out files, in fact it's encouraged and considered good programming. If you find your sending a lot if information to a php script you will want to use JSON instead of as part of the url.
Man, you should follow a client-server pattern.. So the Client page can use some ajax to make a request to a Server page. This will response to the Client and you can make with the data what you want.
of course it will keep refreshing:)) Because as soon as the browser gets the js code, it will load that page you specify, which will send your browser the same page... you get the idea. It's like writing for(;;){}
Your question is difficult to understand (for me at least.) My guess is that you are wanting to use AJAX to send data to the server and receive a response without leaving the page.
Probably the easiest way to accomplish this is to use a library such as jQuery. (see jQuery.ajax())
PHP only runs on the server and the javascript only runs on the client. By the time your client is running the javascript, no more PHP can be executed on that request.

Using Ajax to Send Data Back to the Server

I understand there is a method send for xmlHttpRequest objects, but I've been working on this site all day and I'm unable to find any halfway decent tutorials on the subject and my brain feels like mush. Ajax is hard.
What I'm trying to do is send data from one Javascript file back to a PHP script on the server, where the data is simply a string and a small number. Is this possible? Why can't I find a good article on the subject?
tl;dr How do I use the send method to pass a string and a number from a javascript file to a php file?
Why don't you user jQuery or similar library?
Sending a variables with jQuery will be simple as that:
$.post("save.php", { name: "John", time: "2pm" } );
In your save.php file you can handle POST variables as you wish:
$name = $_POST["name"];
$time = $_POST["time"];
You can check it out: http://jquery.com/
I think you are wasting your time trying to make self made methods ...
It's definitely possible. This is a really nicely organized tutorial that walks you through the XmlHttpRequest object, how to set it up, and how to consume it on the server.
The server-side code is PHP, and I'm more of a C# guy, and it made total sense to me. (Maybe I should switch to PHP??).
I hope this helps! Good luck.
EDIT: In response to a previous SO question, I put this jsfiddle together to demo how to use XmlHttpRequest. Hope this also helps.
lots of good links here, so I'm not going to add to that. Just as a sidenote, you're dealing with a light case of ajaxness here :) - typically you'd want to send something back from the server that changes the state of the page in response to what was sent from the page in the first place (in fact one might argue why you need ajax in the first place and not simply post, if the page's not supposed to change - but I can see how there might be situations where you'd want ajax anyway). I'm just saying that because you're going to encounter a lot of content about how to deal with the stuff sent back from the server - just making sure you're aware that's not needed for what you're trying to do (I'm always glad when I know what I can leave out in the first pass ;)
step 1:
get jquery. all you have to do is download the latest file and include it on your page.
step 2:
make 2 files:
somepage.html:
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
$.get("someScript.php",
// data to send if you want
{
'someVar' : 'someValue'
},
// receive and do something with response
function(response){
alert(response);
} // function (response)
); // .get()
</script>
someScript.php
<?php
echo $_GET['someVar'] . " response!";
?>
step 3:
upload all your files to your server and go to somepage.html
That's all there is to it. Though, you would generally put that code inside some kind of onclick or whatever, depending on what you want to use ajax for. But the comments in there are pretty self explanatory. jquery is used to make the ajax request, with an example of sending data to the server-side script receiving the request (using GET method). You would do whatever in someScript.php but in this example, it simply echoes back the value you sent. Then jquery takes what someScript.php echoes out and just throws it in a popup.
Using jQuery, you can use the post method:
$.post("test.php", { name: "John", number: 2 } );
Behind the scenes, this uses xmlHttpRequest, have a look at the source to see how they do it.

Categories