sending data from Javascript to remote php - php

I am modifying a script to make up a firefox extension for my website. The original script ( chrome extension) stores data into a local websql database. I want it rather to send the three variable to a php file using this format
http://mysite.com/receiver.php?id=href&&title=hostname&&article=article&&article=title
The part of Js that is normally sending the data is the following
// post credentials to background
chrome.extension.sendRequest({
action: 'queryDatabase',
crud: 'create',
record: [
window.location.href,
window.location.hostname,
title,
article
]
});
I would be glad if any one can lead me through the modification of this code

You can use jQuery's ajax() method to accomplish this:
// post credentials to http://mysite.com/receiver.php
jQuery.ajax({
url: "http://mysite.com/receiver.php",
type: 'GET',
data: {
id: "href",
title: "hostname",
article: "article"
}
}).success(function ( data ) {
alert("completed successfully");
}).error(function ( data ) {
alert("there was an error");
});
http://api.jquery.com/jQuery.ajax/

example of the image/PHP solution. The jQuery Ajax solution listed is good if you need to know what was returned (I use it on things like http://jsErrLog.appspot.com and it's a great solution), the image is good if you just want to throw something over the fence and move on. Both as non-blocking
in the HTML page the Javascript would need to trigger a call that requests an image:
<script>
databaseImage = new Image();
databaseImage.src = "http://mysite.com/receiver.php?id=href&&title=hostname&&article=article&&article=title";
</script>
and the PHP page that it calls would, after storing the data, would need to return an image (cleaner than sending back something inappropriate) -
<?
$im = file_get_contents('{path to your 1px .gif}');
header('content-type: image/gif');
echo $im;
?>

Related

Get JSON from Vine API with PHP and call it with Jquery Ajax

I'm trying to build a Vine video feed from a certain users timeline. Because Vine does not offer an API, i'm using the unoffical Vine API wich works great!
The following URL for example, returns a JSON with the latest videos from a given Vine channel. https://api.vineapp.com/timelines/users/1127944909723439104?page=1&size=100
Now as far as i know (correct me if i'm wrong) is it not possible to access this JSON directly through an Jquery Ajax/getJSON call.
Because of that, i'm using PHP in combination with a Cronjob to fetch the JSON once a day from the URL and save it in a JSON file on my own server. I'm able to access then this saved JSON file by Jquery Ajax.
That's what i have right now:
PHP:
<?php
file_put_contents("sbxvine.json", fopen("https://api.vineapp.com/timelines/users/1127944909723439104?page=1&size=100", 'r'));
?>
Jquery:
$(function(){
$.getJSON( "sbxvine.json", function( data ) {
var getvines = data.data.records;
for(var i = 0; i < getvines.length; i++){
$('.vinefeed').append('<div class="item"><div class="content"><video width="100%" height="100%" src="' + getvines[i].videoUrl + '" poster="'+ getvines[i].thumbnailUrl+'" loop controls preload="none"></video></div></div>')
}
});
});
Now the problem here is, that i don't know what time the User is uploading new stuff each day, wich means, that the feed is not synced with the Vine channel. And firing a Cronjob every 5Minutes is not what i'm looking for.
So what i need is to get rid of all that Cronjob stuff and fetch the JSON live from the URL when the Ajax call requests it.
To achieve this, i tried doing this:
PHP:
<?php
header('Access-Control-Allow-Origin: *');
$json = file_get_contents('https://api.vineapp.com/timelines/users/1127944909723439104?page=1&size=100');
$obj = json_decode($json,true);
echo $obj;
?>
And then, with Jquery:
$(function(){
$.ajax({
url: 'getvines.php',
dataType: 'json',
type: 'GET',
success: function(data) {
console.log(data);
},
error: function(){
console.log("nope");
}
});
});
Unfortunately, this is not working and i'm not sure what i'm doing wrong. It logs "nope" after one or two seconds.
Or is there a completely different solution to do all this in a better way?
Ahh stupid misstake, i just had to remove json_decode from the php because the URL already returns the JSON in the right format for the Ajax call.
Just an additional Question: Is this a good way to build this feed? What are the cons and what could be recommendations to enhance it (like make it fast as possible or "best practise" options)?

PHP send form data more than one form/pages

I am a PHP beginner.
I want to send a form data to more than one form/pages. Is it possible?
It sends data to use.php. But I want that it also sends data to two more PHP files: lock.php and unlock.php.
How is it possible?
Make your formdata go to one script, and simply include to the other scripts and they'll have access to the $_POST variable as well.
I use this a lot myself. I have a script where everything runs through the index.php file, but functions are stored in different php files depending on what they're doing. My index.php includes all the php files I need, and inside these php files I have scripting like this:
index.php:
<?php
include('pagename.php');
include('otherpage.php');
echo $return; //output from previous pages
?>
and pagename.php:
<?php
if( $_GET['page'] != 'pagename' )
{
return ('');
}
if( isset($_POST['var']) )
{
// some code
}
You can use Ajax on a client side. I recommend Jquery because it is very easy to start with, or you can use CURL on server side, but it is much more complicated, you can find a bunch of tutorials, just google: sending post data with curl.
Now Jquery Ajax approach:
Lets say your form has an ID of myForm:
make a selector:
$(document).ready(function () {
$("myForm").submit(function (e) {
e.preventDefault(); //prevent default form submit
var url1 = 'your path to url1';
var url2 = 'your path to url2';
var url3 = 'your path to url3';
sendAjax(data,url1);
sendAjax(data,url2);
sendAjax(data,url3);
//do the regular submit
$(this).submit();
});
function sendAjax(data,url){
$.ajax({
url: url,
type:'POST',
data: data,
success: function (data) {
//here you do all the return functionality
},
cache: false
});
});
}
What have we done here:
prevented default sending of form,
made X ajax requests, and send the form normally.
We have made a function for simple ajax handeling just to make our code cleaner.
The problem with this method is that you must make form checking in javascript before you start sending.

xhr return value from a php page

Ok guys im a bit stuck here. I usually use jquery to do this but i found out it cant be done with jquery so im doing it this way ok so this is my code
var url = ("upload.php?loc="+uplocation);
var xhr = new XMLHttpRequest();
if(xhr.upload){ // check if upload property exists
xhr.open("POST", url, true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
}
And all it does is sends a file to a php page, but the php page doesn't upload the image which isn't what i want, so is their anyway of returning all the contents thats displayed on the page
if it was jquery i would do something like this
$.ajax({
type: "POST",
url: 'json/submitsongs.php',
data: loca,
success: function(data){
alert(data);
}
});
so my question is how to do return what ever is echoed on the php page and alert it(for debugging reasons).
thanks for your help
You would add an event listener for whatever event you desired (load, error, progress, etc). So in your case you would use the 'load' event which signifies that the file has finished loading:
xhr.addEventListener('load', onComplete, false);
The onComplete is your callback function which has the event as a parameter. This event contains the response text:
function onComplete(event) {
alert(event.target.responseText);
}
As of today, u can not upload async using Ajax.
Either use Iframes (like Google) or some nifty Flash (or Java) upload app.
Not sure, but might be HTML5 has a solution for that, but it won't be cross browser.

Calling PHP function when link is clicked

I have a PHP function
function ExportExcel()
{
// code
}
and a link on the page Download in Excel
<a>Download in Excel</a>
So what I want is when users clicks on that link, PHP function would be called and data will be downloaded in excel.
I may need to Ajax for that. How do I go about doing that ?
You could possibly just use a GET statement, so it would look something like this...
HTML
Download in Excel
PHP
function ExportExcel()
{
// code
}
if($_GET['init'])
{
ExportExcel();
}
here is the function i implemeted recently:
$('#toexcel').live("click",function() {
$.ajax({
url: "toExcel.php",
data: "sql="+encodeURIComponent(sql),
beforeSend: function(){
$("#wait").show();
},
complete: function(){
$("#wait").hide();
},
success: function(response){
window.location.href = response.url;
}
});
});
where sql variable actually stores sql query to the server,
and then toExcel.php if getting passed sql, submitting it to the server and outputs the result using PHPExcel() object.
EDIT
i think i understood what you trying to achieve. your ExporExcel() function already outputs the results you need, right? is so, then you can do it as follow:
$('#toexcel').click(function() {
$.ajax({
url: "toExcel.php", // should contain and _call_ you ExportExcel() function
beforeSend: function(){
$("#wait").show(); // this is loading img to show
},
complete: function(){
$("#wait").hide(); ;// this is loading img to hide once complete
},
success: function(response){
window.location.href = response.url;
}
});
});
first let me make sure you know php is only parsed when the page is first being distributed. If you click a link on the page, it has no idea the php function on the same page exists because the function only existed server-side while the code was being parsed. That being said, you can easily make a separate page called download.php and call your function on that page. Then your link can just link to that page.
If you want your custom download page to return to the user as an excel file, you can use custom php headers to convince the browser that it is downloading an excel file. (you'd have to specify the MIME type for excel files)
edit:
this would cause a download to start of an excel file created by your function call and activated by your link click. You don't need any JS or JQuery for this.
edit2:
here's example code for the download file to get you started
<?php
header("Content-type: application/excel");
print($data); /* print out the contents of the excel file here */
exit();
?>
If you do it like this, your php page will not redirect from your original page, but will bring up a download box from the browser instead. If your using csv files instead of xls files, you'll need to change the mime type.
you can handle the request in your js scrpit file
$("a").click(function(){
jQuery.ajax({
url: "path/to/controller",
type: "POST",
dataType: 'json',
data: {'mentod':'ExportExcel'},
success: successCallback,
error:failureCallback
});
});
Just provide link of that excel file in href of anchor , browser will download automatically
If your file form DB then providelink of excel.php , and in excel.php do processing of getting excel file and creation of it .
read this artical..do like that

Reading from a MYSQL table every 5 seconds and dynamically displaying results on a PHP page without refreshing

I'm looking to display data from a table in a mysql database using PHP, however, I want the data to automatically update itself and retrieve current values every 5 seconds.. WITHOUT having to refresh the page. Is this possible? Maybe with JQuery/ AJAX? If so, please explain how it can be done / point me to a resource where I can find such information
Thanks
If you use window.setInterval() and jQuery's .load() you should be able to do what you want. The PHP script should return the HTML that needs to replace the previous one.
Javascript:
function refreshData()
{
// Load the content of "path/to/script.php" into an element with ID "#container".
$('#container').load('path/to/script.php');
}
// Execute every 5 seconds
window.setInterval(refreshData, 5000);
A really basic example:
function poll(){
$.ajax({
type: "GET",
url: "your/php/script/",
success: function(data){
// do something with data
}
});
};
setInterval(poll, 5000);
jQuery is a good option. Here are the docs for ajax.
You will want to make this call with setInterval
Something like this might get your started.
setIntervla(updateFromDb,5000);
function updateFromDb(){
$.ajax({
url: "getUpdates.php",
success: function(){
$(this).addClass("done");
}
});
};
What you are describing is exactly the type of the AJAX is used for, AJAX allows for asynchronous requests to be made to your server.
For learning I would suggest using a framework like Jquery and look into the AJAX api.
Basicly you will need a PHP script that query the database and responds the results the way you want them. A suggestion would be to JSON encode them.
In JavaScript on the client you will need to you things like:
var poll = setInterval(function(){
$.ajax({
type:"GET",
url: "yourpage.php",
success: function(data){
//HANDLE DATA
// use JSON.parse(data); if your JSON encoding your data
}
});
},5000)
Just go to the documentation of jQuery:
http://api.jquery.com/category/ajax/
Use the command "jQuery.get()" or better "jQuery.getJson()" to make a http request to the server. Use JSON to get a better communication between server and client. Return from server side a json string and convert this on the client to an javascript object. (the function jQuery.getJson already do this for you) so you can easily access the key and values in the data array.
Just an example:
SERVER Part with PHP:
<?
$data = array('key'=>'value');
return json_encode($data, true);
CLIENT Part:
$.getJSON('myurl.php', function(data) {
// THIS ONE IS CALLED with your PHP data
alert(data.key);
});
$(function(){
window.setInterval(function(){
$.post("filename.php",{'field1':field1,'field2':field2,'field3':field3},function(data){
//callbackfunction(data)
})
},30000);//millisecs
});
And have your php file do all your sql

Categories