Get json encode data from another ajax function - javascript

I'm using prestashop 1.6, I have an ajax function where I encode some data which I successfully retrieved on console withecho. Now I have to decode this json data in another ajax function to get a value for a specific variable. Sorry I'm a newbie with prestashop 1.6.
My first ajax function :
public function ajaxProcessAddQrVideo(){
$target_dir = _PS_IMG_DIR_.DS.'video_qr';
$id_product = Tools::getValue('id_product');
$stamp = strtotime('now');
$filename = 'video_qr_'.$id_product.'_'.$stamp.'.jpg';
$target_file = $target_dir.DS.$filename;
$upload = $_FILES['video_qr_attachment_file'];
$err = array();
$uploaded = false;
if($upload['type'] !='image/jpeg'){
array_push($err,"Veuillez entrer un fichier JPG");
}
if(empty($err)){
$uploaded = #move_uploaded_file($upload['tmp_name'], $target_file);
$this->context->smarty->assign('uploaded', $uploaded);
$this->context->smarty->assign('filename', $filename);
}
$this->json =array(
'uploaded'=>$uploaded,
'err'=>$err,
'id_product'=>$id_product,
'stamp'=>$stamp,
'file_name'=>$filename,
);
echo json_encode($this->json);
exit;
}
And I want to get the value of 'file_name' in my second ajax function:
public function ajaxProcessAddVideo(){
$img_path = json_decode($this->json,true);
$filename = $img_path['file_name'];
$id_lang = Context::getContext()->language->id;
$script = Tools::getValue('script');
$id_product = Tools::getValue('id_product');
$id_group_vid = Tools::getValue('cust_group');
//add qr_code video
$qr_code =$filename;
$err = true;
$insert = false;
$videos = array();
$vid = new MpsVideo();
$vid->id_product = $id_product;
$vid->url = $script;
$vid->cust_group = $id_group_vid;
$vid->date_add = date('Y-m-d H:i:s');
$vid->active = 1;
$vid->qrcode = $qr_code;
$is_existing = Db::getInstance()->getValue("SELECT COUNT(id_mps_video) FROM `ps_mps_video` WHERE id_product=$id_product AND url = '$script'");
if($is_existing==0){
$insert = $vid->save();
$id_group = explode(',',$id_group_vid);
$group_name = array();
foreach($id_group as $k){
$group = new Group($k);
$group_name[] = $group->name[$id_lang];
}
$vid->group_names = implode('<br/>',$group_name);
}
echo json_encode(array(
'err'=>$err,
'video_exists'=>$is_existing,
'insert'=>$insert,
'vid'=>$vid,
));
exit;
}
I don't know how to achieve this but I know its possible. If someone can help understand this, I would be very grateful.

the result of the first function is a json, that result must be read from another file and then passed to your second function. Or else the same function should read that json:
$data = file_get_contents("file/file_json_result.php");
$img_path = json_decode($data, true);

Related

Catch values of parameters in Php sent from angularJs

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.

why is my xml request is coming back undefined

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/*")
}
?>

Get JSON format from MySql to javascript using PHP

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 Dynamic Json data into a Mysql Database.

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);

Trigger php - get path - add img

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.

Categories