Javascript method similar to php file_getcontents - javascript

Is there any mehtod similar to file_getcontents in javascript or jquery.
<?php $html = file_get_contents('http://m.uploadedit.com/b037/1405919727889.txt');
echo ($html);?>
This works fine but i dont want to use php i want to jquery or javascript i have tried this method
$(document).ready(function () {
$.ajax({
url:"http://m.uploadedit.com/b037/1405919727889.txt",
type: "Get",
success: function (data) {
alert(data)
}
});
});
But i get nothing. Any recommendations?

You cannot do cross domain requests, you need to setup a php proxy, like, create a php file in your server say get_contents.php,
$html = file_get_contents('http://m.uploadedit.com/b037/1405919727889.txt');
echo ($html);
and in jquery, access your php, as:
$(document).ready(function () {
$.ajax({
url:"http://your_server.com/get_contents.php",
type: "GET",
success: function (data) {
alert(data)
}
});
});

Javascript cant get content of a file, but as you can see, php can. What I suggest to you is to work with togeter
$(document).ready(function () {
$.ajax({
url:"http://m.uploadedit.com/content/somehash",
type: "Get",
success: function (data) {
alert(data)
}
});
});
And in '/content/somehash' put a php file:
<?php echo file_get_contents('http://m.uploadedit.com/content/somehash');
I suggest you to hide the real name of filename. If you expose information like that, what do you expect if some malicious user try to http://m.uploadedit.com/content/../../.htaccess (for example). The risk is to give too many information. And it's not a good idea.
Exists an alternative and its name is NodeJs:
fs.readFile('/content/somehash', function (err, data) {
if (err) throw err;
// here you can output the content ...
});

Here is a solution. I found this and working fine
$( document ).ready(function() {
$.ajaxPrefilter(function(options) {
if(options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
$.get(
'http://m.uploadedit.com/b037/1405919727889.txt',
function(response) {
$("#content").html(response);
alert(response);
});

Related

Unable to send multiple data parameters with jQuery AJAX

I am trying to send values to other page Using Ajax
But i am unable to receive those values , i don't know where i am wrong
here is my code
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var dataString1 = "fval="+fval;
alert(fval);
var sval = document.getElementById('country').value;
var dataString2 = "sval="+sval;
alert(sval);
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: "{'data1':'" + dataString1+ "', 'data2':'" + dataString2+ "'}",
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
in alert i am getting those value but in page 'getmoreinfo.php' i am not receiving any values
here is my 'getmoreinfo.php' page code
if ($_POST) {
$country = $_POST['fval'];
$country1 = $_POST['sval'];
echo $country1;
echo "<br>";
echo $country;
}
Please let me know where i am wrong .! sorry for bad English
You are passing the parameters with different names than you are attempting to read them with.
Your data: parameter could be done much more simply as below
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var sval = document.getElementById('country').value;
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: {fval: fval, sval: sval},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
Or cut out the intermediary variables as well and use the jquery method of getting data from an element with an id like this.
<script type="text/javascript">
function get_more_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: { fval: $("#get_usecompny").val(),
sval: $("#country").val()
},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
No need to create 'dataString' variables. You can present data as an object:
$.ajax({
...
data: {
'fval': fval,
'sval': sval
},
...
});
In your PHP, you can then access the data like this:
$country = $_POST['fval'];
$country1 = $_POST['sval'];
The property "data" from JQuery ajax object need to be a simple object data. JQuery will automatically parse object as parameters on request:
$.ajax({
type: "POST",
url: "getmoreinfo.php",
data: {
fval: document.getElementById('get_usecompny').value,
sval: document.getElementById('country').value
},
success: function(html) {
$("#get_more_info_dt").html(html);
}
});

Not receiving data from ajax to php

I want to send data from javascript to another php page where I want to display it. I found that I need to use Ajax to pass the data to php so I tried myself.
My file where is the javascript:
$('#button').on('click', function () {
$.jstree.reference('#albero').select_all();
var selectedElmsIds = [];
var selectedElmsIds = $('#albero').jstree("get_selected", true);
var i = 0;
$.each(selectedElmsIds, function() {
var nomenodo = $('#albero').jstree('get_selected', true)[i].text;
//var idnodo = selectedElmsIds.push(this.id);
var livellonodo = $('#albero').jstree('get_selected', true)[i].parents.length;
//console.log("ID nodo: " + selectedElmsIds.push(this.id) + " Nome nodo: " + $('#albero').jstree('get_selected', true)[i].text);
//console.log("Livello: " + $('#albero').jstree('get_selected', true)[i].parents.length);
i++;
$.ajax({
type: "POST",
data: { 'namenodo': nomenodo,
'levelnodo': livellonodo
},
success: function(data)
{
$("#content").html(data);
}
});
});
});
I want to send the data to another php page which consists of:
<?php echo $_POST["namenodo"]; ?>
But when I try to go to the page there's no data displayed.
This is a very basic mistake I think every beginner (including me) does while posting a data using ajax to another php page.
Your ajax code is actually posting the data to lamiadownline.php (if you are using the variables correctly) but you can't get that data by simply using echo.
Ajax post method post data to your php page (lamiadownline.php) but when you want to echo the same data on the receiver page (lamiadownline.php), you are actually reloading the lamiadownline.php page again which makes the $_POST["namenodo"] value null.
Hope this will help.
First of all you won't be able to see what you have post by browsing to that page.
Secondly, is this
<?php echo $_POST["namenodo"]; ?>
in the current page?
Otherwise, specify the url
$.ajax({
url: "lamiadownline.php",
type: "POST",
data: { 'namenodo': nomenodo,
'levelnodo': livellonodo},
success: function(data) {
$("#content").html(data);
}
});
//try this
$.ajax({
type: "POST",
url:"Your_php_page.php"
data: { namenodo: nomenodo levelnodo: livellonodo},
success: function(data)
{
$("#content").html(data);
}
});

Pages loaded by AJAX from the PHP back-end

What I'm tring to do is to load information from different pages, without having to refresh the whole main page...
Could you tell me how to adapt this code for loading files with different names (like about.html and project.html?
Note: this code is made just for loading 'page_.html' files.
var default_content="";
$(document).ready(function(){
checkURL();
$('ul li a').click(function (e){
checkURL(this.hash);
});
default_content = $('#pageContent').html();
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
if(hash=="")
$('#pageContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url)
{
url=url.replace('#page','');
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
$('#loading').css('visibility','hidden');
}
}
});
}
Here is the php file:
if(!$_POST['page']) die("0");
$page = (int)$_POST['page'];
if(file_exists('pages/page_'.$page.'.html'))
echo file_get_contents('pages/page_'.$page.'.html');
else echo 'There is no such page!';
You can make multiple ajax requests this is the jquery load method:
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});
do that 2x and your well off!
Keep in mind for this to work you'll need the jquery library.
I was doing a similar thing on my site here is my code:
window.setInterval("check()",60000);
//request information notice is inside a function called check() (it's not required to put inside function I only do this if I will be making the same request multiple time throughout the program)
function check() {
var request = $.ajax({
url: "file.php",
type: "POST",
dataType: "html"
});
request.done(function(msg) {
//when request is done:
$(".wheretoputnewdata").html(msg);
});
request.fail(function(jqXHR, textStatus) {
//if request failed do this:
alert( "Request failed: " + textStatus );
});
}
Replace this line
if(file_exists('pages/page_'.$page.'.html'))
with this
if(file_exists('pages/'.$page.'.html'))

Get done a php file with a simple click with jquery

I am Totally Newbie, i just want a very very simple example for my question.
Think i have this piece of PHP code :
<?php
echo "Test";
?>
And a piece of jquery like this :
$(document).ready(function() {
$('.div').click(function(){
$('.loading').show();
// DO PHP NOW
$('.loading').hide();
});
});
And HTML :
<div class="div">Click here</div>
I want a simple code , to connect Jquery to PHP file.
When the .div clicked, then php code get happen with No refreshing the page. Just this.
How should i do this ?
(i need a simple way to ajaxify a PHP !)
+ If i want to do Ajax, i have to write code for every every PHP code i write or one piece of Ajax code for ALL PHP codes ?
thanks
If you want to display some value from php in your div use $(".div").load("/url/to/your/php");
Or use
$.post("url/to/php",{val:val,val:val},function(callback){
alert("callback");
$(".div").html(callback);
}
Or AJAX
$.ajax({
url: "/php/code/sd.php",
type: "POST",
date: {
username: "asdasd",
password: "asdasd"
},
success: function(callback){
$(".div").html(callback);
}
});
$(function() {
$('.div').click(function(){
var $this = $(this);
$('.loading').fadeIn(200);
$.ajax({
url: 'url_to_your_file.php',
type: 'GET',
data: {},
success: function(data) {
//do smthing OR
$(data).insertAfter($this);
},
error: function(e) {
//do smthing when error
alert('Error happen!');
console.log(e);
},
complete: function(data) {
$('.loading').fadeOut(200);
}
});
});
});

using javascript onload() and ajax to retrieve php array

I'm using onload() and ajax to get the array from php, but it didnt work. The html page should be able to get the array from n1.php and alert("GOOD"), but it's not giving any response, not even alerting GOOD or BAD so i really dont know what's wrong with the code. How can I fix this??
n1.html:
<!DOCTYPE html>
<html>
<body onload="getArr();">
here
</body>
<script type="text/javascript">
function getArr(){
alert('return sent');
$.ajax({
url: "n1.php",
dataType: 'json',
success: function(json_data){
var data_array = $.parseJSON(json_data);
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
}
</script></html>
n1.php:
<?php
$output = array("cat","dog");
echo json_encode($output);
?>
The request must contains the type of request. Also the dataType refers on data you are going to send,as long as you don't send any data, it does not need here.
Try this:
$.ajax({
url: "n1.php",
type: "GET",
success: function(json_data){
var data_array = $.parseJSON(json_data);
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
Try this
$.ajax({
url: "n1.php",
dataType: 'json',
success: function(json_data){
var data_array = json_data; // Do not parse json_data because dataType is 'json'
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
Now, two things to note here:
You have not passed HTTP Method in the ajax but by default it is GET as mentioned here in jQuery AJAX docs. Please pass appropriate method type if it is not GET.
Since you have sent dataType as 'json', you need not parse json received in the response in success handler.

Categories