I am working first time on php. I want to pass my parameters from angularJs to a php file then those parameters are supposed to be used in INSERT query. I have used XmlHttpRequest to call php file (addsubscriber.php?par1=val1&par2=val2) through AngularJs Function (vm.addSub). Now I dont know how to catch those parameters in my php file.
AngularJs
vm.addSub = function(){
var params = "name="+vm.selectedNameAdd+"&number="+vm.selectedPhoneAdd+"&status="+vm.selectedStatusAdd;
var oReq = new XMLHttpRequest();
oReq.onload = function(){
vm.msg = JSON.parse(this.responseText);
};
oReq.open("get", "addSubscriber.php?"+params, true);
console.log("addSubscriber.php?"+params);
oReq.send();
};
});
addSubscriber.php (What have I tried so far is commented in my php file)
<?php
include('connectionString.php');
$dbObj = new connectionString();
$conn = $dbObj->getdbconnect();
// $request = json_decode( file_get_contents('php://input') );
// $name -> name;
// $number -> number;
// $status -> status;
// $name = filter_input( INPUT_GET, 'name', FILTER_SANITIZE_URL ); // $_GET['name'];
// $number = filter_input( INPUT_GET, 'number', FILTER_SANITIZE_URL ); // $_GET['number'];
// $status = filter_input( INPUT_GET, 'status', FILTER_SANITIZE_URL ); // $_GET['status'];
// parse_str($_SERVER['QUERY_STRING']);
$date = date("Y-m-d");
$query = "INSERT INTO SUBSCRIBERS(subscriber_name,subscriber_number,created_on,is_active) VALUES($name,$number,$date,$status)";
if(mysqli_query($GLOBALS['conn'], $query)){
$msg = "Inserted Successfully";
}
else{
$msg = "Insertion Failed";
}
print json_encode($msg);
Actually the problem was with Query
$query = "INSERT INTO SUBSCRIBERS(subscriber_name,subscriber_number,created_on,is_active) VALUES('$name','$number','$date','$status')";
Note the single quotes in VALUES part.
After adding single quotes it worked as desired.
My code now is incomplete but I tested my xml request and I'm just returning undefined. I am trying to access a folder on a server that contains several folders each named after a book and each containing that books information (cover.jpg, general info txt, reviews txt, etc). Right now I'm just trying to create an XML in my php with the following format:
<books>
<book>
<title>whatever the title of the book is</title>
<folder>whateverthefoldersnameis</folder>
</book>
</books>
but it doesn't seem to be working because in my javascript on line 47 when I try and just get the textcontent of books so I can insert that into my HTML it just says it's undefined. A little lost here.
(function() {
var xml = null;
"use strict";
// sets up onclick handlers
window.onload = function() {
getRequest("books");
var home = document.getElementById("back");
home.onclick = getRequest("books");
};
// sends an ajax request to the passed in address.
// calls the passed in function when the request returns.
function ajax($adress, $function) {
var request = new XMLHttpRequest();
request.onload = $function;
request.open("GET", $adress, true);
request.send();
}
// makes a request for all books.
function getRequest(value) {
ajax("bestread.php?mode=" + value, displayXml("allbooks"));
}
function displayJson() {
$json = JSON.parse(this.responseText);
for($cat in $json.books) {
var book = document.createElement("div");
book.innerHTML = $cat;
book.onclick = choose;
document.getElementById("allbooks").appendChild(book);
}
}
function choose() {
var book = this.innerHTML;
document.getElementById("allbooks").innerHTML = "";
document.getElementById("singlebook").innerHTML = book;
getRequest("info", getInfo);
getRequest("reviews", displayXml("reviews"));
}
function displayXml(id) {
xml = this.responseXML;
document.getElementById(id).innerHTML = xml.querySelector("books").textContent;
}
})();
<?php
$mode = $_GET["mode"];
$book = $_GET["title"];
$url = "../../students/jck789/hw6/books/";
if($mode == "books") {
bookXml($url);
} else if ($mode == "info") {
outputJson($url, $book, "info");
} else if ($mode == "description") {
outputJson($url, $book, "description");
} else if ($mode == "reviews") {
reviewXml($url, $book, "reviews");
}
# outputs the list of available categories in JSON
function outputJson($url, $value) {
$files = glob($url . "*");
$json = array($value => array());
foreach($files as $file) {
$count = count(glob($file."/*"));
$json[$value][basename($file)] = $count;
}
header("Content-type: application/json");
print(json_encode($json));
}
function bookXml($url) {
$files = glob($url . "*");
$index = 0; //currently just trying to grab the first book
list($name, $fold) = file($files[$index]);
$dom = new DOMDocument();
$books = $dom->createElement("books");
$dom->appendChild($books);
$book = $dom->createElement("book");
$books->appendChild($book);
$title = $dom->createElement("title");
$title->appendChild($dom->createTextNode($name));
$folder = $dom->createElement("folder");
$folder->appendChild($dom->createTextNode($fold));
$book->appendChild($title);
$book->appendChild($folder);
header("Content-type: text/xml");
print($dom->saveXML());
}
function reviewXml($url, $book) {
$files = glob($url . "$book/*")
}
?>
i want to get the json format from my SQL database using PHP
here is a capture of mySql database
data.php
<?php include("include/connexion.php");
$requete = "SELECT * from statistika";
$resultat = mysql_query( $requete ) or die( mysql_error() );
$rows = array();
$total_vue = 0;
here is the php code to get the data
while( $data = mysql_fetch_assoc( $resultat ) ) {
$total_vue+=$data['temps'];
$rows[] = array(
"date" => strtotime( $data['date']) * 1000,
"value" => $data[ 'temps' ]
);
}
?>
json_encode.php
<?php
include("data.php");
echo json_encode($rows);
?>
The content of json_encode is valid and i get the json format successfully
[{"date":1439769600000,"value":"5"},{"date":1439787600000,"value":"12"},{"date":1439806631000,"value":"8"},{"date":1439821320000,"value":"18"},{"date":1439919642000,"value":"6"},{"date":1439889752000,"value":"2"},{"date":1439893260000,"value":"20"},{"date":1439906400000,"value":"9"},{"date":1429308000000,"value":"15"},{"date":1421535600000,"value":"12"},{"date":1413583200000,"value":"18"},{"date":1405634400000,"value":"6"},{"date":1439828640000,"value":"14"},{"date":1439935200000,"value":"19"},{"date":1439863200000,"value":"12"},{"date":1439884800000,"value":"18"},{"date":1439917200000,"value":"26"},{"date":1439920800000,"value":"4"},{"date":1439904320000,"value":"0"},{"date":1439907420000,"value":"1"},{"date":1439907428000,"value":"1"},{"date":1439907434000,"value":"3"},{"date":1439907437000,"value":"1"},{"date":1439907447000,"value":"8"},{"date":1439907452000,"value":"3"},{"date":1439907459000,"value":"5"},{"date":1439907469000,"value":"8"},{"date":1439907482000,"value":"10"},{"date":1439907507000,"value":"21"},{"date":1439907510000,"value":"1"},{"date":1439907519000,"value":"7"},{"date":1439907526000,"value":"5"},{"date":1439907547000,"value":"18"},{"date":1439907557000,"value":"8"},{"date":1439907560000,"value":"1"},{"date":1439907576000,"value":"3"},{"date":1439907581000,"value":"3"},{"date":1418857200000,"value":"300"},{"date":1426633200000,"value":"450"},{"date":1434578400000,"value":"500"},{"date":1424214000000,"value":"600"}]
Now i want to pass the JSON format to javascript , i am using this code
var foo = {};
foo.toString = function () { return <?php echo json_encode($rows);?> };
document.write(foo.toString);
the problem is that when printing foo.toString i get this
function () { return [{"date":1439769600000,"value":"5"},{"date":1439787600000,"value":"12"},{"date":1439806631000,"value":"8"},{"date":1439821320000,"value":"18"},{"date":1439919642000,"value":"6"},{"date":1439889752000,"value":"2"},{"date":1439893260000,"value":"20"},{"date":1439906400000,"value":"9"},{"date":1429308000000,"value":"15"},{"date":1421535600000,"value":"12"},{"date":1413583200000,"value":"18"},{"date":1405634400000,"value":"6"},{"date":1439828640000,"value":"14"},{"date":1439935200000,"value":"19"},{"date":1439863200000,"value":"12"},{"date":1439884800000,"value":"18"},{"date":1439917200000,"value":"26"},{"date":1439920800000,"value":"4"},{"date":1439904320000,"value":"0"},{"date":1439907420000,"value":"1"},{"date":1439907428000,"value":"1"},{"date":1439907434000,"value":"3"},{"date":1439907437000,"value":"1"},{"date":1439907447000,"value":"8"},{"date":1439907452000,"value":"3"},{"date":1439907459000,"value":"5"},{"date":1439907469000,"value":"8"},{"date":1439907482000,"value":"10"},{"date":1439907507000,"value":"21"},{"date":1439907510000,"value":"1"},{"date":1439907519000,"value":"7"},{"date":1439907526000,"value":"5"},{"date":1439907547000,"value":"18"},{"date":1439907557000,"value":"8"},{"date":1439907560000,"value":"1"},{"date":1439907576000,"value":"3"},{"date":1439907581000,"value":"3"},{"date":1418857200000,"value":"300"},{"date":1426633200000,"value":"450"},{"date":1434578400000,"value":"500"},{"date":1424214000000,"value":"600"}]
i don't want function () { return to appear in the output !!!
Any hints ?
thanks .
Change this line in your JS code
From
foo.toString = function () { return <?php echo json_encode($rows);?> };
To
foo.toString = '<?php echo json_encode($rows);?>';
var foo = {};
foo.toString = function () { return <?php echo json_encode($rows);?> };
document.write(foo());
You are creating foo as function so call like this you will get only json.
How can i add JSON Data into a Database? i have a script there is generating automatic updated JSON Data. i read in a book that i should use a methode called
JSON_decode
I Think i should have to do something like, put The value into The tables for each value. Then try to use The methode JSON_decode and then make a loop foreach. but i am not sure about this. what is the best way, and can you tell me what to do in my case or maby show a example?
Here is the data located:
http://csgo.nssgaming.com/api.php
The current script:
<?php
require_once ('simple_html_dom.php');
$html = #file_get_html('http://csgolounge.com/');
$output = array();
if(!$html) exit(json_encode(array("error" => "Unable to connect to CSGOLounge")));
// Source: http://php.net/manual/en/function.strip-tags.php#86964
function strip_tags_content($text, $tags = '', $invert = FALSE) {
preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags);
$tags = array_unique($tags[1]);
if(is_array($tags) AND count($tags) > 0) {
if($invert == FALSE)
return preg_replace('#<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>#si', '', $text);
else
return preg_replace('#<('. implode('|', $tags) .')\b.*?>.*?</\1>#si', '', $text);
} elseif($invert == FALSE) {
return preg_replace('#<(\w+)\b.*?>.*?</\1>#si', '', $text);
}
return $text;
}
foreach($html->find('.matchmain') as $match) {
$when = $match->find('.whenm')[0];
$status = trim($when->find('span')[0]->plaintext) == "LIVE" ? true : false;
$event = $match->find('.eventm')[0]->plaintext;
$time = trim(strip_tags_content($when->innertext));
$id = substr($match->find('a')[0]->href, 8);
$additional = substr(trim($when->find('span')[$status ? 1 : 0]->plaintext), 4);
$result;
$output[$id]["live"] = $status;
$output[$id]["time"] = $time;
$output[$id]["event"] = $event;
foreach($match->find('.teamtext') as $key => $team) {
$output[$id]["teams"][$key] = array(
"name" => $team->find('b')[0]->plaintext,
"percent" => $team->find('i')[0]->plaintext
);
if(#$team->parent()->find('img')[0])
$result = array("status" => "won", "team" => $key);
}
if($additional)
$result = $additional;
if(isset($result))
$output[$id]["result"] = $result;
}
echo json_encode($output);
I'm new to PDO and HTML. How do I trigger the php file to get this random image path as the 'brand' image path in to my javascript?
php:
$query = $db->prepare('SELECT img, subject FROM img_db WHERE availability = ? ORDER BY RAND() LIMIT 1');
$array = array('Y');
$query->execute($array);
$result = $query->fetchAll(PDO::FETCH_COLUMN, 0);
var_dump($result);
js:
(function() {
var image = {
'brand': { 'url':'img/bimg.jpg', 'img':null },
'item': { 'url':'img/fimg.jpg', 'img':null }
};
var canvas = {'temp':null, 'draw':null};
var mouseDown = false;
There are many attempts, but here's simplest one:
Prepare your array:
$arr = array();
forach($results as $result){
$arr[$result['subject']] = array('url' => $result['img']);
}
Convert your results to JSON
$json = json_encode($arr);
if you are using MVC framework, pass your $json to view.
Next, in JavaScript part of your page:
(function() {
var image = <?php echo $json; ?>;
var canvas = {'temp':null, 'draw':null};
var mouseDown = false;
You can also load this data using ajax.