How to use file_get_contents and json_decode in Javascript - javascript

I am trying to use this PHP API in Javascript. How can I use file_get_contents and json_decode in Javascript?
PHP API Code
$content=#file_get_contents("http://doma.in/api/?url=http://www.google.com&api=APIKEY");
$url=json_decode($content,TRUE);//Decodes json into an array
if(!$url["error"]){ // If there is no error
echo $url["short"]; //Outputs the short url
}else{
echo $url["msg"]; //Outputs the error message
}
Javascript
(function( $ ) {
$(document).ready(function() {
var url = window.location.href;
var host = window.location.hostname;
var title = $('title').text();
title = escape(title);
var twitter = 'http://twitter.com/home?status='+title+'%20'+url;
var facebook = 'http://www.facebook.com/sharer.php?u='+url;
var tbar = '<div id="sicons">';
tbar += 'Twitter';
tbar += 'Facebook';
tbar += '</div>';
});
})(jQuery);
Edit: Thanks to the replies
data.php
$content = #file_get_contents('http://doma.in/api.php?api=asd4sdf5634d&url=' . urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
echo $content;
I have added this to the Top of the Javascript
$.getJSON('data.php', function(data) {
if(!data.error){ // If there is no error
alert(data.short) //Outputs the short url
}else{
alert(data.msg)
}
});
The Javascript is now looking like this
(function( $ ) {
$(document).ready(function() {
var shorturl = data.short;
var title = $('title').text();
title = escape(title);
var twitter = 'http://twitter.com/home?status='+title+'%20'+url;
var facebook = 'http://www.facebook.com/sharer.php?u='+url;
var tbar = '<div id="sicons">';
tbar += 'Twitter';
tbar += 'Facebook';
tbar += '</div>';
});
})(jQuery);
I am sure I am doing something wrong. Sorry but I am beginner in Coding (C, C++)

Loading data via AJAX is asynchronous. Your first call ($.getJSON) is executed as soon as the page is loaded, but the callback function that you pass as a parameter, is executed only as soon as the underlying HTTP request is finished. This means that your program does not block to wait for the HTTP request; after calling $.getJSON(...) your program runs on, and the callback method is called at some time when the HTTP request finished.
You evaluate your data (in your second function) as soon as the page is loaded. But, since your data is loaded asynchronously, it is not yet loaded when the document is rendered and your function is executed.
The solution for your problem would be to move the code that evaluates your data into the callback function of $.getJSON(...):
$.getJSON('data.php', function(data) {
if (!data.error) {
// Process your data here!
} else {
alert(data.msg)
}
});

Related

AJAX progress bar of load script

I have a big problem to make a progress bar in AJAX. The whole page is in AJAX, inside one of the webpage is AJAX which loads a function to get some big rows from the database.
I tried to make progress bar in this script in a foreach loop a flush() method and by writing/reading to $_SESSION, but still nothing. I really tried everything I don`t know how to do this. Need only this to complete my project. Could someone help me with this?
It is anyway which script I want to load, how is the template for this progress bar to use it in GET or POST ajax, for any AJAX.
<script>
jQuery(document).ready(function($) {
$(document).on('click','#save',function () {
setTimeout(getProgress,1000);
$(this).text('Pobieram analizę...');
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return decodeURI(results[1]) || 0;
}
}
var id = $.urlParam('id');
var idt = $.urlParam('idt');
$.ajax({
url: "views/getresults.php?id="+id+"&idt="+idt,
success: function(data) {
$("#loadresults").append(data);
}
});
setTimeout(getProgress,3000);
return false;
});
function getProgress(){
$.ajax({
url: 'views/listen.php',
success: function(data) {
if(data<=100 && data>=0){
console.log(data);
$('#loadresults').html('<div id="progress"><div class="progress-bar" role="progressbar" style="width:'+ (data / 100)*100 +'%">'+ data + '/' +100+'</div></div>');
setTimeout(getProgress,1000);
console.log('Repeat');
} else {
$('#loadresults').text('Pobieram dane');
console.log('End');
}
}
});
}
});
</script>
and here is a getresults.php
foreach($result as $resul) {
$count++;
session_start();
$_SESSION['progress'] = $count;
$_SESSION['total'] = 100;
session_write_close();
sleep(1);
}
unset($_SESSION['progress']);
and a get progress function listen.php
<?php
session_start();
echo (!empty($_SESSION['progress']) ? $_SESSION['progress'] : '');
if (!empty($_SESSION['progress']) && $_SESSION['progress'] >= $_SESSION['total']) {
unset($_SESSION['progress']);
}
?>
Writing and reading session doesn't work because the standard behavior of PHP is to lock the session file while your main code is being executed.
Try to create a file and update the its content with the percentage done during the execution of your function. Something like:
<?php
function slowFunction() {
$file = uniqid();
file_put_contents($file, 0);
// Long while that makes your stuff
// you have to know how many loops you will make to calculate the progress
$total = 100;
$done = 0;
while($done < $total) {
$done++;
// You may want not to write to the file every time to minimize changes of being writing the file
// at the same time your ajax page is fetching it, i'll let it to you...
$progress = $done / $total;
file_put_contents($file, $progress);
}
unlink($file); // Remove your progress file
}
?>
You can't get the progress of the data download from ajax. Once you request you to the server, the next response will be only after fetching the data or when the error occurs.
The solution to you is, get the data as fractions. Such as first download the 1/10th of the data, and in the success callback, recursively call the ajax again requesting the 2/10th data. On each success callback, you could change the progress bar.
Take a look at Server Side Events or Long polling as options

Validating a directory from a javascript page using $.post to call a webservice PHP function

I am trying without success to use the $.post function to test (via a webservice that calls a PHP function "is_dir") if a folder already exists on a server and then I want it to return a string or boolean value back to my javascript page before I proceed to dynamically write the new files that will be placed there. The file path of the folder to be tested is "built" using jQuery which captures form data. I need to define (in a variable) if the directory exists and then be able to access that variable from outside of the $.post function (not from within, using success callback). This is so I can proceed in javascript as follows:
if {directory exists} then
capture more form data (via jQuery) and
$.post to webservice that calls PHP to update database
Outside of the $.post function, the value of my return variable is undefined.
I think I may be over-complicating this. Any suggestions? Thank you, in advance.
Please see my comment to #Steve above:
<script type='text/javascript'>
//function gathers form data, validates constructed file path and then writes to DB
function post_FormData() {
var week_number = $("#form_week_number").val();
var program = $("#form_program").val();
var course = $.trim($("#form_course_number").val());
var form_content_type = $("input:radio[name=content_type]:checked").val();
var content_type = "";
var activity_title_Val = $.trim($("#form_activity_name").val());
var activity_title_Split = activity_title_Val.split(" ");
var activity_title_Clean = new Array();
//this for-loop constructs a valid directory folder name from form data
for(var i=0, l=activity_title_Split.length; i<l; i++) {
activity_title_Split[i] = activity_title_Split[i].replace(/[^a-z0-9\s]/gi,"");
activity_title_Clean[i] = activity_title_Split[i];
activity_title_Split[i] = activity_title_Split[i].replace(/\b[a-z]/g, function(letter){return letter.toUpperCase();});
}
var activity_title = activity_title_Split.join("");
var file_path = "";
file_path += "/CourseFiles/" + program + "/" + program + course + "/" + content_type + "/Week" + week_number + "/activity-" + activity_title;
var message = "<div id=\"confirmation_container_contents\"><p><b>Confirm Content Repository file path: </b><br></p>";
//begin web service call to PHP function
$.post('webservices/create_PA_webservices.php', {web_service: "go_check_if_exists", data_file_path: file_path}, function(data){
var exists = data.does_exist; //json_encoded RESPONSE FROM ASYNC REQUEST
if(exists == "Y") {
message += file_path;
message += "<br><br><br><center><b>An activity folder with this name already exists.</b></center>";
message += "<br><br><center>Please edit the activity title and resubmit.</center>";
message += "<br><br><br><center><input type=\"image\" src=\"pa_images/editButton.jpg\" id=\"editButton\" value=\"edit\"></center></div>";
$("#confirmation_container").empty();
$("#confirmation_container").append(message);
}
else if(exists == "N") {
message += file_path;
message += "<br><br><center><input type=\"image\" src=\"pa_images/editButton.jpg\" id=\"editButton\" value=\"edit\">";
message += "&nbsp\;&nbsp\;&nbsp\;<input type=\"image\" src=\"pa_images/confirmButton.jpg\" id=\"confirmButton\" value=\"confirm\"></center></div>";
$("#confirmation_container").empty();
$("#confirmation_container").append(message);
}
$(function(){//edit proposed file path
$("#editButton").click(function() {
$("#confirmation_container").empty();
});//end function edit path button
});//end anonymous function
$(function(){//confirm proposed file path and write to DB
$("#confirmButton").click(function() {
go_post_FormData(activity_title_Val, file_path, week_number, program, course, content_type);
$("#create_practice_activity").hide();
$("#build_practice_activity").show();
$("#activity_is_new").val("N");
});//end function confirm path button
});//end anonymous function
}, "json").fail(function() {alert("The go_check_if_exists webservice call has failed");}); //end web service call
}//end function post_FormData declaration
</script>

Sending multiple GET variables in URL with Javascript

I'm trying to retrieve multiple $_GET variables within PHP. Javascript is sending the URL and it seems to have an issue with the '&' between variables.
One variable works:
//JAVASCRIPT
var price = "http://<site>/realtime/bittrex-realtime.php?symbol=LTC";
//THE PHP END
$coinSymbol = $_GET['symbol'];
echo $coinSymbol
OUTPUT: LTC
With two variables:
//JAVASCRIPT
var price = "http://<site>/realtime/bittrex-realtime.php?type=price&symbol=LTC";
//THE PHP END
$coinSymbol = $_GET['symbol'];
$type = $_GET['type'];
echo $coinSymbol
echo $type
OUTPUT: price
It just seems to ignore everything after the '&'. I know that the PHP end works fine because if I manually type the address into the browser, it prints both variables.
http://<site>/realtime/bittrex-realtime.php?type=price&symbol=LTC
OUTPUT ON THE PAGE
priceLTC
Any ideas? It's driving me nuts - Thanks
UPDATE - JAVASCRIPT CODE
jQuery(document).ready(function() {
refresh();
jQuery('#bittrex-price').load(price);
});
function refresh() {
setTimeout( function() {
//document.write(mintpalUrl);
jQuery('#bittrex-price').fadeOut('slow').load(price).fadeIn('slow');
refresh();
}, 30000);
}
Separate the url and the data that you will be sending
var price = "http://<site>/realtime/bittrex-realtime.php";
function refresh() {
var params = {type:'price', symbol: 'LTC'};
setTimeout( function() {
//document.write(mintpalUrl);
jQuery('#bittrex-price').fadeOut('slow').load(price, params).fadeIn('slow');
refresh();
}, 30000);
}
And in your PHP use $_POST or you can do it like this
$coinSymbol = isset($_POST['symbol']) ? $_POST['symbol'] : $_GET['symbol'];
Refer to here for more information jquery .load()

How to return success after running a script

I'm really new to both Perl and Ajax and I was wondering how do I return a message for ajax to know if a script ran successfully and run a success script after knowing the perl script was successful.
On my main html page I have an ajax script like this:
$(document).on('click', '.archive-button', function(){
var notice_id = $(this).data('notice_id');
var archiveaddress = '/user/notices/archivenotice/' + notice_id;
$.post(archiveaddress, {notice_id: notice_id});
});
which send its to the archivenotice.html page which runs a Perl script which just marks the time the notice was read.
my $update_needed = 0;
unless ($notice->read_on()) {
$notice->read_on(scalar localtime);
$update_needed = 1;
}
What should I add to the Perl script on the archivenotice.html pages so that the ajax on my main html page knows the script ran successfully and initiate another script called "successful"
Open a channel of communication between your main.html page and archivenotice Perl script.
main.html
$(document).on('click', '.archive-button', function(){
var notice_id = $(this).data('notice_id');
var archiveaddress = '/user/notices/archivenotice/' + notice_id;
$.post(archiveaddress, {notice_id: notice_id}, function( data ) {
if ( data ) { alert('Update needed!'); }
else { alert('Update not needed.'); }
});
});
archivenotice
my $update_needed = 0;
unless ($notice->read_on()) {
$notice->read_on(scalar localtime);
$update_needed = 1;
}
print "Content-type: text/plain\n\n";
print $update_needed;
exit;
Try this:
$(document).on('click', '.archive-button', function(){
var notice_id = $(this).data('notice_id');
var archiveaddress = '/user/notices/archivenotice/' + notice_id;
$.post(archiveaddress, {notice_id: notice_id}).done(function() {
alert( "update success" );
});
});

jQuery load() return json value

I have a page where I use jQuery load() method to display a table of results based on a post request of some fields. But I need this load() to display the table and also inform javascript if a condition is met in the PHP script, so probably I need a json response. I don't know if it's possible to use the complete() callback to achieve that. I only need a single variable to pass from my PHP script to javascript.
I'm using load() because I believe other ajax methods need to do the HTML template part from javascript, am I right?
Hope I made myself clear, thanks
UPDATE1:
Here is my js code:
$("#listaNegraView").load('procesos/funcionesAjax.php',
{accion: 'listaNegra',
nombres: $("#nombres").val(),
apellidoP: $("#apellidoP").val(),
apellidoM: $("#apellidoM").val(),
nacimiento: $("#nacimiento").val()},
function(data){console.log(data);}
);
And here is PHP script:
case 'listaNegra':
$_POST['nombres'] = mb_convert_encoding($_POST['nombres'], 'Windows-1252', 'UTF-8');
$_POST['apellidoP'] = mb_convert_encoding($_POST['apellidoP'], 'Windows-1252', 'UTF-8');
$_POST['apellidoM'] = mb_convert_encoding($_POST['apellidoM'], 'Windows-1252', 'UTF-8');
$listaNegra = $personaDB->existsPersonaListaNegra($_POST);
$pct100 = false;
if(!empty($listaNegra) && is_array($listaNegra)){
foreach($listaNegra as &$persona){
$persona['match'] = '';
$porcentaje = 80;
if(strtolower($persona['nombres']) == strtolower($_POST['nombres'])){
$persona['match'] .= 'name';
$porcentaje += 10;
}
if($_POST['nacimiento'] == $persona['fecha_nacimiento']){
$persona['match'] .= 'date';
$porcentaje += 10;
}
$persona['porcentaje'] = $porcentaje;
if($porcentaje == 100)
$pct100 = true;
}
unset($persona);
}
include(ROOT.RUTA_TPL.'ventas/listanegra.tpl.php');
break;
UPDATE 2:
Specifically the condition I want to pass to jasvascript is variable $pct100
You are "directly" outputting HTML code so I think, as a quick workaround, you should write the $pct100 in a hidden field/dom element and then access it with the complete callback in your javascript code.
This is an example of what I am suggesting
$("#listaNegraView").load(
'procesos/funcionesAjax.php',
{accion: 'listaNegra',
nombres: $("#nombres").val(),
apellidoP: $("#apellidoP").val(),
apellidoM: $("#apellidoM").val(),
nacimiento: $("#nacimiento").val()
},
function(data){
$('#where-to-put-html-code').html(data);
var pct100 = $('#where-to-put-html-code #hidden-field-id').val() == '1' ? true : false;
}
);
Answer added by the suggestion of the asker.

Categories

Resources