In this html page at the begin of the script i send the value of variable fin at the php page (http://sat3.altervista.org/index.php?valore="+ fin). In this php page i tried to take the value of variable but i didn't have success. Someone can help me?
<!doctype html>
<html>
<head>
<title>Parsing</title>
<script type="text/javascript" src="jquery-2.1.0.min.js"></script>
</head>
<script>
var fin = "SAT000000002575";
url = "http://sat3.altervista.org/index.php?valore="+ fin,
data = {
get_param: 'value'
};
$.getJSON(url, data, function (data) {
for (var i = 0; i < data.length; i++) {
var lin = data[i]["Nr SAT"];
$('body').append($('<p>').html('Numero Sat: ' + data[i]["Nr SAT"] + ''));
$('body').append($('<p>').html('Data Apertura: ' + data[i]["Data Apertura"]));
}
});
</script>
<body>
<header>
</header>
</body>
</html>
This is the php page:
<?php
// Sopprimo gli errori del php
error_reporting(0);
// Includo la libreria
require_once 'excel_reader2.php';
$file_handle = fopen("leggimi2.csv", "r");
//EDIT: Define an array to hold individual lines
$data = array();
while (!feof($file_handle) ) {
//HERE I TAKE THE VALUE BUT IT DON'T CONTAIN NOTHING
$myValue = $_GET["valore"];
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[0] == $myValue)
{
$arr = array('Nr SAT' => $line_of_text[0],'Data Apertura' => $line_of_text[13], 'Tipo Servizio' => $line_of_text[1], 'Stato SAT' => $line_of_text[2],'Marca Terminale' => $line_of_text[4], 'Modello Terminale' => $line_of_text[5], 'IMEI guasto' => $line_of_text[6],'IMEI consegnato' => $line_of_text[7],'Famiglia guasto' => $line_of_text[8],'Descrizione guasto' => $line_of_text[9] );
//EDIT: Add the line to the array
$data[] = $arr;
}
}
//EDIT: Encode the array as a JSON array of line objects
echo json_encode($data);
//$myValue = isset($_GET['myValue']) ? $_GET['myValue'] : '';
fclose($file_handle);
?>
jQuery reference here http://api.jquery.com/jQuery.getJSON/ says that
second argument is "A plain object or string that is sent to the server with the request."
Try this:
<script type="text/javascript">
var fin = "SAT000000002575",
url = "http://sat3.altervista.org/index.php",
getVars = {
valore : fin
};
$.getJSON(url, getVars, function(data) {
// rest of your code
});
</script>
And let us know :)
EDIT
Regarding your PHP code, you have to put this $myValue = $_GET["valore"]; before your while begins.
Related
I'm trying to dynamically update text on a PHP page via AJAX. But, instead of the text coming through at different intervals, it all comes at once. Maybe this is the wrong approach.
index.html
<html>
<head>
<title>Please Update!</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$.post("hello.php", function(data){
var success = $("#update");
success.css("color", "green");
success.html("> \r " + data + ".");
});
});
</script>
</head>
<body>
<div id="update"></div>
</body>
</html>
hello.php
<?php
echo "Hello World\n";
sleep(1);
echo "\rFoobar\n";
sleep(1);
echo "\rBazboo\n";
?>
I'd like the text to overwrite itself after one second but it comes barreling down the pipe all at once. ;_;
Not sure about this, but it might help you to do...
in PHP
<?php
$result[] = "Hello World\n";
$result[] = "\rFoobar\n";
$result[] = "\rBazboo\n";
print_r($result);
?>
in Ajax result
$.post("hello.php", function(data){
for(let i = 0; i < data.length; i++) {
setTimeout(() => {
// your stuff to do is here by 1 second interval...
var success = $("#update");
success.css("color", "green");
success.html("> \r " + data[i] + ".");
}, 1000*i);
}
});
Simple Representation
var data = ["Hello World\n","\rFoobar\n","\rBazboo\n"];
for(let i = 0; i < data.length; i++) {
setTimeout(() => {
console.log(data[i]);
}, 1000*i);
}
Like Antony suggested. You could create an array in php and encode it as Json
and then create a settimeout().
php
$data = array("Hello World","Foobar","BazBoo");
echo json_encode($data);
jQuery ~ JavaScript
$.ajax({
method: "GET",
url: "hello.php",
success: (res) => {
for (let i = 0; i < res.length; i++) {
setTimeout(() => {
// or use .html(res[i])
$("#update").text(res[i] + "<br>");
}, 1000 * i);
}
}
})
I'm trying to make my own api using a JSON and PHP script, which is successfully working (api.mystem.tk/product), however I want to convert that data to an html table with the columns: id, name and date.
My question, how? I've got my code included and you can watch the JSON output in the console of api.mystem.tk/product. I've deleted all the private details in the scripts and replaced them with #______.
api.php:
<?php
$connect = mysqli_connect('#host', '#user', '#password', '#db');
if(!isset($_GET['function'])) {
die('Some error occurred!');
}
function GetProducts($db) {
$sql = mysqli_query($db, 'SELECT * FROM php_test ORDER BY Id ASC LIMIT
0, 10');
$data = array();
if (mysqli_num_rows($sql) > 0) {
while ($row = mysqli_fetch_array($sql)) {
$data[] = $row["Id"];
$data[] = $row["Name"];
$data[] = $row["Date"];
}
}
$data = json_encode($data);
echo $_GET['jsonCallback'].'('.$data.')';
}
if (function_exists($_GET['function'])) {
$_GET['function']($connect);
}
echo $data;
?>
function.js:
$(function(){
var functionName = 'GetProducts';
function LoadData() {
$.getJSON("http://api.mystem.tk/product/api.php?
function="+functionName+"&jsonCallback=?", function(data) {
var all_data = [];
$.each(data, function(k, name){
var array_data = '<div class="names">'+name+'</div>';
all_data.push(array_data);
});
$('#data').append(all_data);
console.log(data);
});
}
LoadData();
});
index.php:
<!DOCTYPE html>
<html lang="en">
<head>
<title> API TEST </title>
<meta name="viewport" content="width=device-width,initial-
scale=1,maximum-scale=1,user-scalable=0">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
</head>
<body>
<div id="data"></div>
<script type="text/javascript" src="function.js"></script>
</body>
</html>
so i've tried using $.parseJSON instead of $getJSON, but without succes
console:
Uncaught SyntaxError: Unexpected token <
at m (jquery-3.3.1.min.js:2)
at Function.globalEval (jquery-3.3.1.min.js:2)
at text script (jquery-3.3.1.min.js:2)
at Ut (jquery-3.3.1.min.js:2)
at k (jquery-3.3.1.min.js:2)
at XMLHttpRequest.<anonymous> (jquery-3.3.1.min.js:2)
and i've changed this:
$data[] = $row["Id"];
$data[] = $row["Name"];
$data[] = $row["Date"];
to this:
$data[] = array(
'id' => $row["Id"],
'name'=> $row["Name"],
'date'=> $row["Date"]
)
to be a little bit more specified...
You'll need to parse JSON data in your function.js using jQuery.parseJSON() jQuery function.
You can read brief documentation from: jQuery.parseJSON()
Added code:
<script>
var obj = JSON.stringify([
{
"id":'1',
"name":'Jhon Doe',
"date":'April 14,2018'
},
{
"id":'2',
"name":'Coder',
"date":'April 23, 2018'
}
]);
var jsontoparse = JSON.parse(obj);
var i = obj.length;
var j=0;
while(j<=i){
console.log(jsontoparse[j].id);
j = j+1;
}
</script>
Morning! Please i will like to get some data from mySQL(like getting the number of rows of a mySQL table using ajax). Please how can i do it? Here are my 2 pages. The first one send a number to the php page and the second one do a request to the database and send the result to the page in ajax(the first one). The table voisin_par_distance has 3 columns: cel_id, cel_id_1 and cel_id_2 Thanks.
<!DOCTYPE html>
<html>
<body>
<script>
var xhr1 = new XMLHttpRequest();
var i=1;
var j=4;
xhr1.onreadystatechange = function() {
if (xhr1.status == 200 && xhr1.readyState == 4) {
document.getElementById('content').innerHTML = xhr1.responseText;
}
};
xhr1.open('GET', 'test.php?i='+i+'&j='+j, false);
xhr1.send('');
</script>
<?php
// I would line to get for example the number of rows of table voisin_par_distance which is returned by test.php
$m = (int) $_GET['n'];
echo $m;
?>
</body>
</html>
and this is the php page which is in the same directory.
<?php
$dbname='BD';
try {
$bdd = new PDO( 'mysql:host=localhost;dbname=BD', 'root', '' );
}
catch ( PDOException $e ) {
die("Could not connect to the database $dbname :" . $e->getMessage() );
}
$i = (int) $_GET['i'];
$j = (int) $_GET['j'];
//to select the number of rows of my table
$req = $bdd->prepare("SELECT serveur FROM voisin_par_distance WHERE cel_id_1=':cel_id_1' AND cel_id_2=':cel_id_2'");
$req->execute( array(
'cel_id_1' => $i,
'cel_id_2' => $j
) );
$nbre_ligne = count( $req );
?>
<!DOCTYPE html>
<html>
<body>
<script>
var nbre_ligne = <?php echo $nbre_ligne; ?>
var xhr = new XMLHttpRequest();
var a = 2;
xhr.onreadystatechange = function() {
if (xhr.status == 200 && xhr.readyState == 4) {
document.getElementById('content').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'show_map.php?n='+nbre_ligne);
xhr.send('');
</script>
</body>
</html>
Best and Easy way to use ajax:
$.ajax({// on an event
type: "GET",
url: "test.php", #with valid path
data: {col1: "value1", col2: "value2"},
cache: false,
success: function (responce) {
// alert your response to check data
if (responce.length > 0) {
var data = JSON.parse(responce); // Parse JSON
//Your logic here
}
}
});
In Your PHP file, return data in json format. e.g.
echo json_encode(array('col1' => $val, 'col2' => $val2));
exit;
I hope this will help you.
My autocomplete plugin from jQuery is not working first time with one character in the textbox.If I continue to type more than one character then the autocomplete kicks in...
So I'm expecting result from the first character but is not getting anything..
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$( "#names" ).keyup(function() {
autocompleteNames();
});
});
function loadNames(){
//Gets the name
var nameSelected = $("#names").val();
var namesList = "";
$.ajax({
url: 'names.php',
type: "POST",
async: false,
data: { sport: nameSelected}
}).done(function(names){
namesList = names.split(',');
});
//Returns the javascript array of names.
return namesList;
}
function autocompleteNames(){
var names = loadNames();
$("#names").autocomplete({
source: names,
minLength: 1
});
}
</script>
</head>
<body>
Namn: <input type="text" id="names" name="names" />
</body>
</html>
And here's my names.php file that's very simple
<?php
$sport = $_POST["sport"];
//Defines the name array.
$names[0] = "Sam";
$names[1] = "Anna";
$names[2] = "Jens";
$names[3] = "Johanna";
$names[4] = "Emma";
$names[5] = "Mikael";
$names[6] = "Mattias";
$names[7] = "Sebastian";
$names[8] = "Johan";
$names[9] = "Mona";
$names[10] = "Lina";
$names[11] = "Linda";
$names[12] = "Ebba";
$names[13] = "Andreas";
$names[14] = "Marcus";
$names[15] = "Markus";
$names[16] = "Anders";
$names[17] = "Maria";
$names[18] = "Sandra";
$names[19] = "Jonatan";
$names[20] = "Jacob";
$names[21] = "Carolina";
$names[22] = "Tom";
$names[23] = "Tim";
$names[24] = "Zlatan";
$names[25] = "Emelie";
//Defines an empty variable that will return the javascript array.
$teams = generateAutocompleteArray($names);
//Returns the teams in the appropriate javascript array format.
echo $teams;
//Function converts PHP array a string where it can be split into an array easily.
function generateAutocompleteArray($namesArray){
$jsNamesArray = "";
$teamCount = count($namesArray);
for($i=0; $i<$teamCount; $i++){
$jsNamesArray.= $namesArray[$i].',';
}
//Removes the remaining comma so you don't get a blank autocomplete option.
$jsNamesArray = substr($jsNamesArray, 0, -1);
return $jsNamesArray;
}
?>
I don't think you should bind your autocomplete constructor to the keyup event of the input text. If so, you are recreating the object every time the user types something. Also, you are returning the namesList and maybe it is still loading from the ajax request. You have to wait for the request to complete in order to have the namesList, remember that javascript is asynchronous.
So basically, you have to construct the autocomplte just once, and look for the autocomplete parameters (source) to specify that your data is loaded via ajax. Take a look at this: jQuery autocomplete with callback ajax json
Im trying to convert 5 PHP arrays to 5 js arrays.
I used to transfer php variables to js variables with json like this:
$return['variable'] = $variable;
echo json_encode($return);
And then fetch it as json object on the js side like this:
success : function(data) {
alert(data.variable);
}
now things are a bit more complicated, i need to transfer these 5 php arrays from a php script to my js script as 5 js arrays:
PHP arrays:
$i = 0;
while ($location = mysql_fetch_array($get_locations)) {
$location_full_name[$i] = $location['loc_full_name'];
$location_main_name[$i] = $location['loc_main_name'];
$location_sub_name[$i] = $location['loc_sub_name'];
$location_anchor_id[$i] = $location['loc_anchor_id'];
$location_type[$i] = $location['loc_type'];
$i++;
}
and fill these corresponding arrays:
var location_full_name = new Array();
var location_main_name = new Array();
var location_sub_name = new Array();
var location_anchor_id = new Array();
var location_type = new Array();
i dont know how to do this. hope i can get some help :)
regards,
alexander
Maybe if you post what returns in "data" so we can help you more (i think). hehe.
I suggest, for your php code, where you set the data into the arrays:
$i = 0;
$rsl = array();
while ($location = mysql_fetch_array($get_locations)) {
$rsl[$i]['full_name'] = $location['loc_full_name'];
$rsl[$i]['main_name'] = $location['loc_main_name'];
$rsl[$i]['sub_name'] = $location['loc_sub_name'];
$rsl[$i]['anchor_id'] = $location['loc_anchor_id'];
$rsl[$i]['type'] = $location['loc_type'];
$i++;
}
echo json_encode($rsl);
So to get this on the javascript
// You could do the same... var location = []...
var location_full_name = new Array();
var location_main_name = new Array();
var location_sub_name = new Array();
var location_anchor_id = new Array();
var location_type = new Array();
...
dataType: "json",
success : function(data) {
$.each(data, function(index, arr){
location_full_name[index] = arr['full_name'];
...
});
}
For each of your arrays, store the value returned from json_encode. And/or make them one array/object and do the same.
You can utilize the PHP array that is actually an ordered map. Below is an example:
PHP:
<?php
$location_full_name = array("Google, Inc.", "Siku-Siku.com");
$location_type = array("Google headquarter", "Virtual address");
$ret = array("full_name" => $location_full_name, "type" => $location_type);
echo json_encode($ret);
?>
JavaScript (jQuery):
<script type="text/javascript">
$(function() {
$.get("test.php", function(data) {
console.log(data.full_name[1]); // Prints "Siku-Siku.com".
}, "json");
});
</script>