load content of a page using only javavascript noe jquery - javascript

i working on a simple script that load users last posts in there blog and website !
the page is works well without any problem !
this is an example : http://parsclub.net/tools/widget/load-rss.php?u=reza-shady&l=5&w=200&c=4DC7FF
i want to load that link blow in external page !
for that i used this script and put it on a file
<?php
$user = trim($_GET["u"]);
$limit = trim($_GET["l"]);
$width = trim($_GET["w"]);
$color = trim($_GET["c"]);
header("Content-Type: text/javascript; charset=utf-8");
?>
document.write('<div id="parsclub_widget"><img src="http://parsclub.net/themes/parsclub/imgs/loading_posts.gif" style="margin:20px;display:inline-block;"/></div>');
function ajaxRequest() {
var activexmodes = ["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]
if (window.ActiveXObject) {
for (var i = 0; i < activexmodes.length; i++) {
try {
return new ActiveXObject(activexmodes[i])
} catch (e) {
}
}
} else if (window.XMLHttpRequest) return new XMLHttpRequest()
else return false;
}
function load_widget() {
var mygetrequest = new ajaxRequest()
if (mygetrequest.overrideMimeType) mygetrequest.overrideMimeType('text/html')
mygetrequest.onreadystatechange = function () {
if (mygetrequest.readyState == 4) {
if (mygetrequest.status == 200 || window.location.href.indexOf("http") == -1) {
var data = mygetrequest.responseText;
document.getElementById("parsclub_widget").innerHTML = data;
} else {
alert("خطایی در هنگام دریافت اطلاعات رخ داده است");
}
}
}
mygetrequest.open("GET", "http://parsclub.net/tools/widget/load-rss.php?u=<?= $user ?>&l=<?= $limit ?>&w=<?= $width ?>&c=<?= $color ?>", true);
mygetrequest.send(null);
return false;
}
load_widget();
but it don't work when i put it on a external page
you can see the result here !
http://up.pc-t.ir/New%20Text%20Document.html
i know i cant simply load it with jquery load() function but i want it pure JavaScript
can anyone help me with this ?
so sorry for my bad English
EDIT
#merlin-denker 10x for your help i found solution for my problem by adding this headers to the load-rss.php file
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type');

As Barmar already stated in a comment, the AJAX Request is failing because of the same origin policy.
The solution to this is to add a PHP-Script to your Website that simply reads the content of the other URL and echoes it.
<?php echo file_get_contents(YOUR_URL_HERE); ?>
Then let your Javascript call the script that is located on the same webserver and it will work.
Read more here: http://www.php.net/manual/function.file-get-contents.php

Related

Wordpress Widget: AJAX Request fails

I'm trying to make an AJAX-Request within a Wordpress Plugin in frontend, after clicking a button. -> Actually it is a Widget. So I implemented the frontend via extending de WP_Widget Class. I don't know if this is worth knowing.
I always get a 400 bad Request and '0'.
I dont wanted to use JQuery, but i also tried and there I get a 500 Internal Server Error.
Now im really confused.
I really searched up and down the internet and every question in this forum (I know there are many similar questions - but nothing worked to me)
I'm so thankful if anyone can help me.
Main Plugin File:
function scriptloader(){
$scripturl = plugin_dir_url(__FILE__) . 'includes/public/script.js';
wp_enqueue_script('script-js', $scripturl, array( 'jquery' ));
$styleurl = plugin_dir_url(__FILE__) . 'includes/public/css/main.css';
wp_enqueue_style('script-js', $styleurl, [], null, false);
$js_variable = [
'ajax_url' => admin_url('admin-ajax.php'),
'ajax_nonce' => wp_create_nonce( 'ajax_public' ),
'mystring' => "LOL!"
];
wp_localize_script('script-js', 'phpwindowobject', $js_variable);
};
add_action( 'wp_enqueue_scripts', 'scriptloader');
function k_ajax_requester(){
$mystring = "SERVER ALIVE";
echo $mystring;
wp_die();
};
add_action('wp_ajax_k_ajax', 'k_ajax_requester');
add_action('wp_ajax_nopriv_k_ajax', 'k_ajax_requester');
There is a button in frontend.php which executes ajaxrequest() by clicking in
my script.js :
function ajaxrequest(){
var url = phpwindowobject.ajax_url;
var data = {action: "k_ajax",mystring: "K_AJAX"}
console.log("Data to send:")
console.log(data)
var xhrobj = new XMLHttpRequest;
xhrobj.open('POST', url, true);
xhrobj.setRequestHeader('Content-Type', 'text/html; charset=utf-8');
xhrobj.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
console.log('Request completed');
}
else console.log("Ajax error: No data received")
}
else console.log("Ajax error: " + xhrobj.statusText );
}
};
xhrobj.onload = function(){
var answer = (xhrobj.response);
console.log(answer);
}
xhrobj.send(data);
};
What do you think?
Thank you.

Why XmlHttpRequest wait until complete PHP response (proc_open) even with flush?

I 'm trying to execute commands (wp cli) with xhr.
My problem is when i call my file deploy.php with the javascript.
Without JS call the script works, the flush is immediate.
When i call deploy.php in a XmlHttpRequest, the response wait until the end of the php execution.
I try different commands (grep / wp cli / find) but the result is the same.
I work on WSL Debian + Chrome.
// PHP
public function liveExecuteCommand($cmd, $ajax = false)
{
ob_start();
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("file", "error-output.txt", "a")
);
$output = '';
$process = proc_open($cmd, $descriptorspec, $pipes);
if (is_resource($process)) {
fwrite($pipes[0], '<?php print_r($_ENV); ?>');
fclose($pipes[0]);
while ($s = fread($pipes[1], 8192)) {
$output .= $s;
print $s;
$this->doFlush();
}
fclose($pipes[1]);
$return_value = proc_close($process);
//echo "La commande a retourné $return_value\n";
}
if ($ajax == false) {
return $output;
}
}
$obj->liveExecuteCommand($cmd, true);
die();
// JS
function getLiveStream() {
var ajax = new XMLHttpRequest();
var url = 'https://www.monsite.local/deploy.php';
ajax.open('GET', url, true);
ajax.onprogress = function() {
document.getElementById("xhr_cmd_result").innerHTML = ajax.responseText;
console.log('onprogress');
}
ajax.onload = function() {
console.log('onload');
}
ajax.onreadystatechange = function() {
document.getElementById("xhr_cmd_result").innerHTML = ajax.responseText;
console.log('statechange');
}
ajax.send();
}
window.addEventListener('DOMContentLoaded', (event_loaded) => {
document.getElementById("xhr_cmd").onclick = getLiveStream;
});
In the Google chrome console, the result display all status directly (after 1 min), like the php result.
statechange
onprogress
statechange
onprogress
statechange
onprogress
statechange
onload
I would like have a console.log every time that the flush is called.
No problem when i execute the php file in the browser, the problem is certainly in the javascript.
How do I solve the problem?
Let me explain you in simple words.
Javascript's XMLHttpRequest(AJAX) call will request to server. It will only waits for response from server(final output from your php page), irrespective to internal process of server.

When including session I can not use $_FILES

I am uploading a csv file and sending it to page to process using the js fetch api. I have session included using my init file and all works well accept for the page that should process to file info. Without including the session it works fine and I can process the file, when including it, I can see al the session info, but $_FILES just stops working, I can't see any of the info for some reason.
I really hope this is something stupid
Some code if needed
The init file
<?php
//define Site Root and Includes Path
defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
defined('SITE_ROOT') ? null : define('SITE_ROOT', __DIR__ . DS );
defined('INCLUDES_PATH') ? null : define('INCLUDES_PATH', SITE_ROOT);
//get class files
include(INCLUDES_PATH.DS."Session.php");
require_once(INCLUDES_PATH.DS."functions.php");
require_once(INCLUDES_PATH.DS."DB.php");
require_once(INCLUDES_PATH.DS."Validation.php");
require_once(INCLUDES_PATH.DS."User.php");
require_once(INCLUDES_PATH.DS."Swp.php");
require_once(INCLUDES_PATH.DS."Incident.php");
require_once(INCLUDES_PATH.DS."Hira.php");
require_once(INCLUDES_PATH.DS."Mail.php");
The Session.php page
<?php
class Session
{
private $logged_in;
public $user_id;
function __construct()
{
session_start();
$this->check_login();
}
public function is_logged_in() {
return $this->logged_in;
}
private function check_login() {
if (isset($_SESSION['UserID'])) {
$this->user_id = $_SESSION['UserID'];
$this->logged_in = true;
} else {
unset($this->user_id);
$this->logged_in = false;
}
}
}
$session = new Session();
The form page
<?php
//get all the includes
require_once("../php_functions/_init.php");
print_r($_FILES);
//all rows from csv file
$rows = array_map('str_getcsv', file($_FILES['file']['tmp_name'][0]));
//get only the headers
$header = array_shift($rows);
//declare the array
$csv = array();
//create associative array using array_combine
foreach ($rows as $row) {
$csv[] = array_combine($header, $row);
}
print_r($csv);
like I mentioned if I removed the require once from this page it works as expected. Any ideas would help
Just in case you need it here is the js for uploading the file
document.querySelector("#upload_file").addEventListener("click", function () {
const url = 'php/employee/upload_employee_csv_form.php';
const files = document.querySelector('[type=file]').files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
let file = files[i];
formData.append('file[]', file);
}
console.log(formData);
fetch(url, {
method: 'POST',
body: formData
}).then(response => {
console.log(response);
});
});
I actually figured it out. So my session was being included before I actually added it, to fix this instead of just saying session_start I check to see if the session is there and then only start if necessary.
The code
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
Bonus tip :-)
The above code will work for php 5.4 and up if you are running something lower than 5.4 you can do the following:
if(session_id() == '') {
session_start();
}
Hope this helps

I want to clear contents of file in chrome extension and the file is on server. How to do that?

I have written the below code in my js file in chrome extension.
var xhr_put = new XMLHttpRequest();
xhr_put.open('PUT',"https://something/index.php",true);
xhr_put.onreadystatechange = function()
{
console.log('File Cleared',"Yes");
}
And the below code in my PHP file.
$requestmethod = 'PUT';
if ($_REQUEST['REQUEST_METHOD'] === $requestmethod)
{
$f = #fopen("facebookmsg.txt", "w");
print "in here";
if ($f !== false) {
ftruncate($f, 0);
fclose($f);
echo "here";
}
}
But my file on server is not getting empty. I need help as to what is wrong and how do i correct it?

ajax responseText contains php source code

I am trying to make a ajax call and validate a input html field. But, instead of getting simple echo message. I am getting complete source code in responseText.
JavaScript
function checkUsername() {
document.getElementById("username").className = "thinking";
usernameRequest = createRequest();
if (usernameRequest == null)
alert("Unable to create request");
else {
var theName = document.getElementById("username").value;
var username = escape(theName);
var url= "checkName.php?username=" + username;
usernameRequest.onreadystatechange = showUsernameStatus;
usernameRequest.open("GET", url, true);
usernameRequest.send(null);
}
}
function showUsernameStatus() {
alert(usernameRequest.responseText);
if (usernameRequest.readyState == 4)
{
if (usernameRequest.status == 200) {
if (usernameRequest.responseText == "okay") {
document.getElementById("username").className = "approved";
document.getElementById("register").disabled = false;
}
else {
document.getElementById("username").className = "denied";
document.getElementById("username").focus();
document.getElementById("username").select();
document.getElementById("register").disabled = true;
}
}
}
}
checkName.php
<?php
$takenUsernames = array('bill', 'ted');
sleep(2);
if (!in_array($_REQUEST['username'],$takenUsernames )) {
echo 'okay';
} else {
echo 'denied';
?>
Previously, I tried to integrate PHP into tomcat, but I was advice it was not a good practice. TRIAL TO INTEGRATE PHP
What I can make out of this situation is that Tomcat is not parsing PHP file and instead it is returning the source code. I believe there should be a means for me to let tomcat parse php files and send the right response.
I have also tried with simple php code, with one statment <?php echo 'HELLO'; ?> and I still get the source code.
Thanks in advance.
NOTE : I do not know php, I am working an example from HEAD FIRST AJAX
you need to install PHP for Tomcat & set its path to compile it.see the below link for php configuration settings.
http://php-java-bridge.sourceforge.net/doc/tomcat6.php
http://www.studytrails.com/blog/php-on-a-java-app-server-apache-tomcat-using-quercus/

Categories

Resources