how to parse html already store in variable - php

I want to parse a shoutcast page like this :
http://relay.181.fm:8800/played.html
So, i just make ajax to call a php file. The php file return all the content of the page.
i store the html content to a var in js. Here is the code:
PHP:
function getcontent($server, $port, $file){
$cont = "";
$ip = gethostbyname($server);
$fp = fsockopen($ip, $port);
if (!$fp){
return "Unknown";
}
else{
$com = "GET $file HTTP/1.1\r\nAccept: */*\r\nAccept-Language: de-ch\r\n"
."Accept-Encoding: gzip, deflate\r\nUser-Agent: Mozilla/4.0 (compatible;"
." MSIE 6.0;Windows NT 5.0)\r\nHost: $server:$port\r\n"
."Connection: Keep-Alive\r\n\r\n";
fputs($fp, $com);
while (!feof($fp))
{
$cont .= fread($fp, 500);
}
fclose($fp);
$cont = substr($cont, strpos($cont, "\r\n\r\n") + 4);
return $cont;
}
}
echo (getcontent("relay.181.fm", "8800", "/played.html"));
Here is my js:
var xhr = new XMLHttpRequest();
var parsed;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
parsed=xhr.response;
}
};
xhr.open("GET", 'http://localhost/getsong.php', true);
xhr.send(null);
And that is what i want to get:
$(document).ready(function(){
var songs=new Array();
var time=new Array();
for (var i = 0; i < 10; i++) {
songs[i]=$('table:eq(2) tr:eq('+(i+1)+') td:eq(1)').text();
time[i]=$('table:eq(2) tr:eq('+(i+1)+') td:eq(0)').text();
};
});
if i copy the xhr.response content and i put it in the html file and i execute this js, it return me exactly what i want.
but i dont get how i can do when the html is in a variable... :'(
PS: i work on a wamp env., And a node.js env.

Since you tagged it with jQuery, why not use the built in ajax functionality:
$.ajax({
url: 'http://localhost/getsong.php',
dataType: 'html'
}).done(function(data){
//do something with the HTML
var $html = $(data),
tdtexts = $html.find('table:eq(2) tr td:first').text();
});
Is this what you're asking for?

I think, you can use innerHTML to resolve
var xhr = new XMLHttpRequest();
var parsed;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
parsed=xhr.response;
document.getElementById('#div').innerHTML = parsed;
}
};
xhr.open("GET", 'http://localhost/getsong.php', true);
xhr.send(null);

Proceeding further after getting response may help you like,
var xhr = new XMLHttpRequest();
var parsed;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
parsed=$.parseHTML(xhr.response);
var songs=new Array();
var time=new Array();
for (var i = 0; i < 10; i++) {
songs[i]=$(parsed).find('table:eq(2) tr:eq('+(i+1)+') td:eq(1)').text();// use find function for parsed string
time[i]=$(parsed).find('table:eq(2) tr:eq('+(i+1)+') td:eq(0)').text();
};
}
};
xhr.open("GET", 'http://localhost/getsong.php', true);
xhr.send(null);
By using $.ajax()
$(function(){
$.ajax({
url:'http://localhost/getsong.php',
dataType:'html',
success:function(parsed){
var songs=new Array();
var time=new Array();
for (var i = 0; i < 10; i++) {
songs[i]=$(parsed).find('table:eq(2) tr:eq('+(i+1)+') td:eq(1)').text();// use find function for parsed string
time[i]=$(parsed).find('table:eq(2) tr:eq('+(i+1)+') td:eq(0)').text();
};
}
});
});

I think you're looking for jQuery.parseHTML(). It will parse your string into an array of DOM nodes.
http://api.jquery.com/jQuery.parseHTML/
Here's a quick example for your case:
$.get('http://relay.181.fm:8800/played.html')
.done(function(data) {
var parsed = $.parseHTML(data);
// Now parsed is an array of DOM elements which you can use selectors on, eg:
var song1 = $(parsed).find('table:eq(2) tr:eq(1) td:eq(1)').text();
console.log(song1);
});

Related

can not convert it into content-type:application/json

let formData2 = new FormData();
formData2.append('_token', vm.response._token);
formData2.append('file', vm.response.content[i].path);
formData2.append('type', vm.response.content[i].type);
// this part is progress bar
var xhr = new XMLHttpRequest();
xhr.open("POST", "page/file/create/upload", true);
if (xhr.upload) {
xhr.upload.onprogress = function (e) {
if (e.lengthComputable) {
progressBar.max = e.total;
progressBar.value = e.loaded;
display.innerText = Math.floor((e.loaded / e.total) * 100) + '%';
}
}
xhr.upload.onloadstart = function (e) {
progressBar.value = 0;
display.innerText = '0%';
}
xhr.upload.onloadend = function (e) {
progressBar.value = e.loaded;
}
}
xhr.send(formData2);
i saw in network tab after pressing f12 that in response-header my content-type is text/html. i think this is the main reason of getting 500 error. because in ajax needs JSON. i am working with laravel and my controller get NULL.
so how can i covert it into json?
let formData2 = new FormData();
formData2.append('file', vm.response.content[i].path);
// this part is progress bar
var xhr = new XMLHttpRequest();
xhr.open("POST", "page/file/create/upload", true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.setRequestHeader('X-CSRF-TOKEN', vm.response._token);
if (xhr.upload) {
xhr.upload.onprogress = function (e) {
if (e.lengthComputable) {
progressBar.max = e.total;
progressBar.value = e.loaded;
display.innerText = Math.floor((e.loaded / e.total) * 100) + '%';
}
}
xhr.upload.onloadstart = function (e) {
progressBar.value = 0;
display.innerText = '0%';
}
xhr.upload.onloadend = function (e) {
progressBar.value = e.loaded;
}
}
xhr.send(formData2);
#ksoni still m getting 500 error code. and content-header is still text/html. what mistake i have done with my formData2(image or any file). what is the procedure. can u explain a bit.

AJAX JSON Post to PHP

I'm trying to post JSON String via AJAX to PHP, but all examples not work.
First of all I learn https://www.w3schools.com/js/js_json_php.asp
https://www.w3schools.com/js/tryit.asp?filename=tryjson_php_db_post
Then i write own code. But no one of my example code below not working. And return one result:
index.php:6:string '[object Object]' (length=15)
index.php:7:null
index.php:8:null
First variant:
<?php
$JsonPost = file_get_contents('php://input');
if ($JsonPost != null) {
var_dump($JsonPost);
var_dump(json_decode($JsonPost, true));
var_dump(json_decode($JsonPost));
} else {
?>
<html>
<script type="text/javascript">
var RequestObject = new XMLHttpRequest();
RequestObject.open("POST", window.location.href, true)
RequestObject.setRequestHeader('Content-type', 'application/json');
var SomeObject = {};
SomeObject.Field1 = 'lalala';
SomeObject.Array1 = [
'lala1', 'lala2'
];
RequestObject.onreadystatechange = function() {
if (RequestObject.readyState == 4 && RequestObject.status == 200) {
document.getElementById("body").innerHTML = RequestObject.responseText;
}
};
var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
RequestObject.send(JsonStr);
</script>
<body id="body"></body>
</html>
<?php
}
?>
Second variant:
<?php
if (isset($_POST['JsonPost'])) {
var_dump($_POST['JsonPost']);
var_dump(json_decode($_POST['JsonPost'], true));
var_dump(json_decode($_POST['JsonPost']));
} else {
?>
<html>
<script type="text/javascript">
var RequestObject = new XMLHttpRequest();
RequestObject.open("POST", window.location.href, true)
RequestObject.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=utf-8');
var SomeObject = {};
SomeObject.Field1 = 'lalala';
SomeObject.Array1 = [
'lala1', 'lala2'
];
RequestObject.onreadystatechange = function() {
if (RequestObject.readyState == 4 && RequestObject.status == 200) {
document.getElementById("body").innerHTML = RequestObject.responseText;
}
};
var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
RequestObject.send("JsonPost=" + JsonStr);
</script>
<body id="body"></body>
</html>
<?php
}
?>
Please help.
PHP Version 5.6.28
XAMPP v3.2.2 on Windows 10 (64-bit)
Browser Chrome 56.0.2924.87 (64-bit)
UPDATED
Working Example.
<?php
$JsonPost = file_get_contents('php://input');
if ($JsonPost != null) {
var_dump($JsonPost);
var_dump(json_decode($JsonPost, true));
var_dump(json_decode($JsonPost));
} else {
?>
<html>
<script type="text/javascript">
var RequestObject = new XMLHttpRequest();
RequestObject.open("POST", window.location.href, true)
RequestObject.setRequestHeader('Content-type', 'application/json');
var SomeObject = {};
SomeObject.Field1 = 'lalala';
SomeObject.Array1 = [
'lala1', 'lala2'
];
RequestObject.onreadystatechange = function() {
if (RequestObject.readyState == 4 && RequestObject.status == 200) {
document.getElementById("body").innerHTML = RequestObject.responseText;
}
};
//var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
var JsonStr = JSON.stringify(SomeObject);
RequestObject.send(JsonStr);
</script>
<body id="body"></body>
</html>
<?php
}
?>
Many thanks to all who answered.
var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
RequestObject.send(JsonStr);
Here you are:
Creating some JSON
Setting the JSON as the value of an object property
Implicitly converting the object to a string (which will be "[object Object]")
Sending that string as the request body
But since you are trying to post JSON you should skip steps 2 and 3 … just pass the JSON:
RequestObject.send(JSON.stringify(SomeObject));
Change in you Second variant this:
var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
RequestObject.send("JsonPost=" + JsonStr);
to
RequestObject.send("JsonPost=" + JSON.stringify(SomeObject));
Why:
var JsonStr = { creates an new real javascript object
but this object can not used with + to concate it
Your problem is this:
var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
that is still a javasript object, you have to stringifly the whole thing
so this should wok:
var JsonStr = JSON.stringify({JsonPost: SomeObject});
RequestObject.send(JsonStr);

Uploading files with XMLHttpRequest

I am new to XMLHttpRequest and I have been using it as a AJAX file uploader using JavaScript's FormData().
The problem I am having is that it seems to upload fine, although I think it is not sending it to the right PHP file or my PHP is wrong because nothing is displayed in the folder where pictures should be.
At the moment, I don't know how to view the returned html data
JavaScript:
$("#form").submit(function(event) {
event.preventDefault();
event.stopPropagation();
var form = $(this);
var file = document.getElementById("file");
var data = new FormData();
var onerror = function(event) {
alert("An error occoured!");
}
var onprogressupdate = function(event) {
if(event.lengthComputable) {
var percent = event.loaded / event.total * 100;
$("#progress").html(percent+"%");
}
}
var onreadystatechange = function(event) {
if(request.status == 200 && request.readyState == 4) {
alert("Uploaded!");
$("#progress").hide();
$("#progress").html("");
}
else {
alert("Alternative state and/or status");
console.log("state: " + request.state);
console.log("readyState: " + request.readyState);
}
}
for(var i = 0; i < file.files.length; i++)
data.append('file[]', file.files[i]);
$("#progress").show();
$("#progress").html("Uploading files...");
var request = new XMLHttpRequest();
request.upload.addEventListener("error", onerror);
request.upload.addEventListener("progress", onprogressupdate);
request.upload.addEventListener("readystatechange", onreadystatechange);
request.open("post", "upload.php");
request.setRequestHeader("Content-type", "multipart/form-data");
request.send(data);
});
Upload page
<?php
if(isset($_FILES["file"])) {
$f = $_FILES["file"];
$dir = "data";
if(!file_exists($dir))
mkdir($dir);
foreach($f["name"] as $k => $name) {
$file = $dir."/".$name;
if($f["error"][$k] == 0 && move_uploaded_file($f["tmp_name"][$k], $file)) {
$uploaded[] = $file;
}
}
die(json_encode($uploaded));
}
?>
Don't set the content type, its set automatically.
Create your FormData object with form element you want to send:
var data = new FormData(this);
instead of
var data = new FormData();
The syntax of the FormData is
new FormData (optional HTMLFormElement form)
without the argument, it is empty, see the reference.

how to track the ready state for each file with html5 xmlhttprequest object

below is my code for uploading files using XMLHttpRequest send method
function send_file_to_server(file,id)
{
console.log('send_file_to_server id received = ' + id);
var filename = file.name;
var container_name = $("#gs-file-upload-container").find(':selected').text();
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e)
{
console.log(' bytes loaded = '+e.loaded + ' remaining = ' + e.total);
}
xhr.onreadystatechange = function()
{
if(xhr.status == 200 && xhr.readyState == 4){
on_upload_complete( filename,id,xhr);
}
var queryString = 'http://upload_files?filename='+filename+'&cname='+container_name;
xhr.open("POST", queryString, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", encodeURIComponent(filename));
xhr.setRequestHeader("Content-Type", "application/octet-stream");
xhr.send(file);
}
With the above function i wait for on_upload_complete to get called and then pass the second file object and one by one i am uploading. Can someone suggest how can i make it upload simultaneously i tried doing this below as
var xhr = Array();
function send_file_to_server(file,id)
{
console.log('send_file_to_server id received = ' + id);
var filename = file.name;
var container_name = $("#gs-file-upload-container").find(':selected').text();
xhr[filename] = new XMLHttpRequest();
xhr[filename].upload.onprogress = function(e)
{
console.log(' bytes loaded = '+e.loaded + ' remaining = ' + e.total);
}
xhr[filename].onreadystatechange = function()
{
if(xhr[filename].status == 200 && xhr[filename].readyState == 4){
on_upload_complete( filename,id,xhr);
}
var queryString = 'http://upload_files?filename='+filename+'&cname='+container_name;
xhr[filename].open("POST", queryString, true);
xhr[filename].setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr[filename].setRequestHeader("X-File-Name", encodeURIComponent(filename));
xhr[filename].setRequestHeader("Content-Type", "application/octet-stream");
xhr[filename].send(file);
}
by doing this i xhr[filename] inside onreadystatechange is undefined because of loop and i want to keep track of every file upload progress and finish it . But as you can see the problem is only keeping track of onreadystatechange with a unique id and i am stuck here. Please can anyone throw light , suggestions and recommendations help is appreciated. thanks
You have deal with Javascript Closure. onreadystatechange see filename,id,xhr of the lastest invoke of send_file_to_server function. To change this rewrite your function like this:
var xhr = Array();
function send_file_to_server(file,id)
{
console.log('send_file_to_server id received = ' + id);
var filename = file.name;
var container_name = $("#gs-file-upload-container").find(':selected').text();
xhr[filename] = new XMLHttpRequest();
xhr[filename].upload.onprogress = function(e)
{
console.log(' bytes loaded = '+e.loaded + ' remaining = ' + e.total);
}
(function(localFilename, localId, localXhr){
localXhr[localFilename].onreadystatechange = function(){
if(localXhr[localFilename].status == 200 && localXhr[localFilename].readyState == 4){
on_upload_complete(localFilename, localId, localXhr);
}
}
})( filename,id,xhr)
var queryString = 'http://upload_files?filename='+filename+'&cname='+container_name;
xhr[filename].open("POST", queryString, true);
xhr[filename].setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr[filename].setRequestHeader("X-File-Name", encodeURIComponent(filename));
xhr[filename].setRequestHeader("Content-Type", "application/octet-stream");
xhr[filename].send(file);
}

XMLHttpRequest Dosen't complete

I'm calling a PHP file with XMLHttpRequest, but now the call doesn't complete and I
have no idea why. The req.readyState isn't 4, and I don't know why because the PHP file is okay and does exactly what supposed to (just echo a string).
Can anyone see what I can not see?
function processAjax(id, option) {
if (option == "lpath") url = "<?php echo $mosConfig_live_site;?>/administrator/components/com_joomlaquiz/getinfo.php?id=" + id;
else url = "<?php echo $mosConfig_live_site;?>/administrator/components/com_joomlaquiz/getinfo.php?cat=" + id;
//create AJAX request
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = targetDiv();
try {
req.open("GET", url, true);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = targetDiv();
req.open("GET", url, true);
req.send();
}
}
}
//this function handles the response from the ajax request
function targetDiv() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
//all of the code below doesn't happen because its not the option
if (option == "lpath") {
var response = req.responseText.split('##');
var articles = response[0].split(';');
var quizes = response[1].split(';');
document.getElementById("article_id").innerHTML = "";
document.getElementById("quiz_id").innerHTML = "";
for (var i = 0; i < articles.length; i = i + 2) {
if ((i + 1) <= articles.length) {
var option = new Option( /* Label */ articles[i + 1], /* Value */ articles[i]);
document.getElementById("article_id").options.add(option);
}
}
for (var i = 0; i < quizes.length; i = i + 2) {
if ((i + 1) <= quizes.length) {
var option = new Option( /* Label */ quizes[i + 1], /* Value */ quizes[i]);
document.getElementById("quiz_id").options.add(option);
}
}
delete req, articles, quizes;
} else {
document.getElementById("catdiv").innerHTML += req.responseText;
document.getElementById("allchildren").value = req.responseText;
}
} else { //failed to get response
alert("Problem: " + req.statusText);
}
}
document.getElementById("catdiv").innerHTML += "Y U NO COMPLETE?!";
}
req.onreadystatechange = targetDiv();
should be
req.onreadystatechange = targetDiv;
The original code calls targetDiv() immediately after that line of code is run, which is probably not what you wanted to do. The fixed code calls the function correctly, after the Ajax request is received.

Categories