Could someone clarify this code snippet for me? - javascript

This piece should create a csv file. The method that is calling to the nonAjaxPost is:
function exportCSV()
{
nonAjaxPost('getExport', 'post', {action: '/getView', 'view': current_pi, 'parameters': encodeURIComponent(JSON.stringify(current_parameters))});
}
function nonAjaxPost(action, method, input) {
"use strict";
var form;
form = $('<form />', {
action: action,
method: method,
style: 'display: none;'
});
if (typeof input !== 'undefined') {
$.each(input, function (name, value) {
$('<input />', {
type: 'hidden',
name: name,
value: value
}).appendTo(form);
});
}
form.appendTo('body').submit();
}
My problem is that i just can't seem to understand how this is going to create a csv file for me. I'm probaly missing out on something that i just can't see.
I really hope someone could help me out.
Update:
This is the getExport function:
$databundle = $this->_getData();
$data = $databundle['rows'];
$columns_all = $databundle['columns'];
$columns = array("Id");
foreach($data[0] as $key => $column) {
$column = "";
$found = false;
foreach($columns_all as $col_search) {
if($col_search['key'] == #$key) {
$found = true;
$column = $col_search['title'];
break;
}
}
if($found) {
//echo $key . ",";
$columns[] = $column;
}
}
$contents = putcsv($columns, ';', '"');
foreach($data as $key => $vals) {
if(isset($vals['expand'])) {
unset($vals['expand']);
}
array_walk($vals, '__decode');
$contents .= putcsv($vals,';', '"');
}
$response = Response::make($contents, 200);
$response->header("Last-Modified",gmdate("D, d M Y H:i:s") . " GMT");
$response->header("Content-type","text/x-csv");
$response->header("Content-Disposition","attachment; filename=".str_replace(" ","_",$databundle['title'])."_".date("Y-m-d_H:i").".csv");
return $response;
It also calls the getData function which is this:
$viewClass = str_replace('/', '', (isset($_POST['view']) ? $_POST['view'] : $_GET['view']));
$fileView = '../app/classes/view.'.$viewClass.'.php';
if(file_exists($fileView))
{
require_once($fileView);
$className = 'view_'.$viewClass;
if(class_exists($className))
{
$view = new $className();
//Seek for parameters
if(isset($_REQUEST['parameters']))
{
//Decode parameters into array
$parameters = json_decode(urldecode((isset($_POST['parameters']) ? $_POST['parameters'] : $_GET['parameters'])),true);
//Get supported parameters
$parameterTypes = $view->getVars();
$vars = array();
foreach($parameterTypes as $key => $type)
{
//If a value is found for a supported parameter in $_GET
if(isset($parameters[$key]))
{
switch($type)
{
case 'int':
$vars[$key] = intval($parameters[$key]);
break;
case 'float':
$vars[$key] = floatval($parameters[$key]);
break;
case 'filterdata':
// todo: date validation
$vars[$key] = $parameters[$key];
break;
}
}
}
$view->setVars($vars);
}
return $view->getData();
}
else {
/*
header('HTTP/1.1 500 Internal Server Error');
echo 'Class ' . $className . ' does not exist.';
*/
return false;
}
}
else {
/*
header('HTTP/1.0 404 Not Found');
die('Cannot locate view (' . $fileView . ').');
*/
return false;
I hope this is sufficient.
In short what i am trying to find out is that the csv that it produces has more columns than columns headers and where the difference comes from

My guess would be that the page you are calling (on the server) is generating the CSV file.
You would need to write code on the server to do the conversion.

This method is making a post request to getView page. Your csv create code would be present on getView page.

This is the front end code that creates an invisible form with your data: current_parameters.
See the content of current_parameters in the the current file.
Review back-end code and look for the "getExport" function (it should be the current php file loaded)
If you just copied this function from some example... you have to add also the back-end code on your own.
Update:
look at the getExport code:
$contents = putcsv($columns, ';', '"');
$contents .= putcsv($vals,';', '"');;
First row insert the titles , and the second loops the data and insert the other rows.
Print the content of $columns and $vals and see what is happening.
There are some strange conditions for filtering the columns... but can help you if you don't show the data you try to parse.

Related

How to get the value of title image and content in ajax php

How to display the data title, image and content?
Here's the code:
view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$dataArr = array();
$responseArr = array();
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
array_push($dataArr, $data);
}
echo json_encode($dataArr);
}
mysqli_free_result($result);
} else {
echo "No Record";
}
}
index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
alert(data)
}
});
});
});
What I'm trying to do is to get the title, image and content.
How to get the value of title, image and content?
How to call the "title", "name" and "content" from the php?
console.log('DATA: ' + data);
No need to use while loop for result. Also remove extra $dataArr and $responseArr
Update your code to:
in view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
echo json_encode($data); exit;
}
mysqli_free_result($result);
}
}
$data['error'] = "No Record";
echo json_encode($data); exit;
Index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
var response = jQuery.parseJSON(data);
var title = response.title;
var name = response.name;
var content = response.content;
alert(title);
alert(name);
alert(content);
}
});
});
});
After taking data from jQuery side, you can set value in html side using id or class attribute in jQuery.
How your ajax receiving .php file should look:
$validLiteratureIds = ['yourTable1', 'yourTable2'];
if (!isset($_GET['edit_literature_id'], $_GET['literatureID']) || !in_array($_GET['literatureID'], $validLiteratureIds)) {
$response = ['error' => 'Missing/Invalid Data Submitted'];
} else {
$conn = new mysqli('localhost', 'root', '', 'dbname');
$sql = "SELECT title, name, content
FROM `{$_GET['literatureID']}`
WHERE `id` = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_GET['edit_literature_id']);
$stmt->execute();
$stmt->bind_result($title, $name, $content);
if (!$stmt->fetch()) {
$response = ['error' => 'No Record'];
} else {
$response = [
'title'=> $title,
'name' => 'data:image/jpeg;base64,' . base64_encode($name),
'content' => $content
];
}
}
echo json_encode($response);
Important practices:
Validate the user input so that only qualifying submissions have the privilege of accessing your database.
Write the failure outcomes before success outcomes consistently throughout your project, this will make your scripts easier to read/follow.
Always use prepared statements and bind user-supplied data to placeholders into your query for stability/security.
The tablename cannot be bound like the id value; it must be written directly into your sql string -- this is why it is critical that you validate the value against a whitelist array of literature ids.
There is no need to declare new variables to receive the $_GET values; just access the values directly from the superglobal array.
I am going to assume that your id is a primary/unique key in your table(s), so you don't need to loop over your result set. Attempt to fetch one row -- it will either contain data or the result set was empty.
Call json_encode() only once and at the end of your script.
It is not worth clearing any results or closing a prepared statement or a connection, because those tasks are automatically done when the script execution is finished anyhow -- avoid the script bloat.
As for your jquery script:
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (response) {
if (response.hasOwnProperty('error')) {
console.log(response.error);
} else {
console.log(response.title, response.name, response.content);
}
}
});
});
});
I've trim away all of the irrelevant lines
changed POST to GET -- because you are merely reading data from the database, not writing
parseJSON() is not necessary -- response is a ready-to-use object.
I am checking for an error property in the response object so that the appropriate data is accessed.
Both scripts above are untested (and completely written from my phone). If I have made any typos, please leave me a comment and I'll fix it up.

(populate dropdown in contact form 7 getting this error - Warning: array_keys() expects parameter 1 to be array, null given in

Ok where to start, I will try and explain as much as I can.
I am using wordpress with contact form 7 and I am trying to populate 3 dropdown items on the contact form, I found some code that I was able to use with no problem but the problem with this was that it was getting the information from a excel file, the file is now to big and will not run on my website anymore so I would like to get the information from my database now.
I have made a table in my database "vehicle_information" with 3 columns "vehicle_type", "vehicle_make", vehicle_model"
I have code in my functions.php and code in my footer to be able to use the cf7 shortcodes.
Code from funtions.php
function ajax_cf7_populate_values() {
//MySQLi information
$db_host = '***';
$db_username = '***';
$db_password = '***';
$vehicles_makes_models = array();
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die('Error ' . mysqli_error());
//select MySQLi dabatase table
$vehicles_makes_models = mysqli_select_db($connection, 'vehicle_information') or die('Error ' . mysqli_error());
$sql = mysqli_query($connection, 'SELECT * FROM vehicle_type');
while($row = mysqli_fetch_array($sql)) {
$vehicles_makes_models[$row[0]][$row[1]][] = $row[2]; }
}
// setup the initial array that will be returned to the the client side script as a JSON object.
$return_array = array(
'vehicles' => array_keys($vehicles_makes_models),
'makes' => array(),
'models' => array(),
'current_vehicle' => false,
'current_make' => false
);
// collect the posted values from the submitted form
$vehicle = key_exists('vehicle', $_POST) ? $_POST['vehicle'] : false;
$make = key_exists('make', $_POST) ? $_POST['make'] : false;
$model = key_exists('model', $_POST) ? $_POST['model'] : false;
// populate the $return_array with the necessary values
if ($vehicle) {
$return_array['current_vehicle'] = $vehicle;
$return_array['makes'] = array_keys($vehicles_makes_models[$vehicle]);
if ($make) {
$return_array['current_make'] = $make;
$return_array['models'] = $vehicles_makes_models[$vehicle][$make];
if ($model) {
$return_array['current_model'] = $model;
}
}
}
// encode the $return_array as a JSON object and echo it
echo json_encode($return_array);
wp_die();
// These action hooks are needed to tell WordPress that the cf7_populate_values() function needs to be called
// if a script is POSTing the action : 'cf7_populate_values'
add_action( 'wp_ajax_cf7_populate_values', 'ajax_cf7_populate_values' );
add_action( 'wp_ajax_nopriv_cf7_populate_values', 'ajax_cf7_populate_values' );
Code from my footer
<script>
(function($) {
// create references to the 3 dropdown fields for later use.
var $vehicles_dd = $('[name="vehicles"]');
var $makes_dd = $('[name="makes"]');
var $models_dd = $('[name="models"]');
// run the populate_fields function, and additionally run it every time a value changes
populate_fields();
$('select').change(function() {
populate_fields();
});
function populate_fields() {
var data = {
// action needs to match the action hook part after wp_ajax_nopriv_ and wp_ajax_ in the server side script.
'action' : 'cf7_populate_values',
// pass all the currently selected values to the server side script.
'vehicle' : $vehicles_dd.val(),
'make' : $makes_dd.val(),
'model' : $models_dd.val()
};
// call the server side script, and on completion, update all dropdown lists with the received values.
$.post('<?php echo admin_url( 'admin-ajax.php' ) ?>', data, function(response) {
all_values = response;
$vehicles_dd.html('').append($('<option>').text(' -- choose vehicle -- '));
$makes_dd.html('').append($('<option>').text(' -- choose make -- '));
$models_dd.html('').append($('<option>').text(' -- choose model -- '));
$.each(all_values.vehicles, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_vehicle == this) {
$option.attr('selected','selected');
}
$vehicles_dd.append($option);
});
$.each(all_values.makes, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_make == this) {
$option.attr('selected','selected');
}
$makes_dd.append($option);
});
$.each(all_values.models, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_model == this) {
$option.attr('selected','selected');
}
$models_dd.append($option);
});
},'json');
}
})( jQuery );
The problem is I am still learning and this is the first time I have had to use this funtion.
and I am getting an error on my website
Warning: array_keys() expects parameter 1 to be array, null given in /customers/4/0/0/motobid.co.uk/httpd.www/wp-content/themes/storevilla-child/functions.php on line 38 {"vehicles":null,"makes":[],"models":[],"current_vehicle":false,"current_make":false}
any help would be very greatful.
Just like to say code was supplied by BDMW.
Where you use the method array_keys(), instead of:
$return_array['makes'] = array_keys($vehicles_makes_models[$vehicle]);
Try this:
$return_array['makes'] = ! empty($vehicles_makes_models[$vehicle]) ? array_keys($vehicles_makes_models[$vehicle]) : [];
From what I've read, the array_keys() has been an issue depending on php versions. Hope this helps!

Change & into & when show on json

So i have problem whit symbols "&", here my code on javascript
$("#shipCurr").change(function(){
var curr = $(this).val();
$("#shipPO").empty();
if(curr != "")
{
$("#shipPO").prop('disabled',false);
$.ajax
({
type: "POST",
url: host+"buypo/ListPOShippDoc",
data:{
'curr':curr
},
cache: false,
success:function(data)
{
console.log($("#shipPO").html(data));
}
});
}
else
{
$("#shipPO").prop('disabled',true);
}
// console.log("test");
});
and on php code
public function ListPOShippDoc()
{
$currency = $_POST['curr'];
$fullName = $_SESSION['fullName'];
$PONo = $this->shippDoc->ListPO($fullName,$currency)['items'];
$option .= '<option value=""></option>';
while ($val = $PONo->fetch_assoc()) {
$option .= '<option value="'.utf8_decode($val['PONo']).'">'.utf8_decode($val['PONo']).'</option>';
}
echo $option;
}
My problem is,if the PONo value like H&M-000762-001 it show on my html into H&M-000762-001.
How do i get wrong in here? Wy it show H&M-000762-001 not H&M-000762-001? Any idea?
I try utf8_decode() utf8_encode() is still same result H&M-000762-001.
function convertSymbol($value)
{
$value = mb_convert_encoding($value, "ISO-8859-1", "UTF-8");
$ampersandval = str_replace("&", "&", $value);
return $ampersandval;
}
?>
/* mb_convert_encoding this function is used to Convert ISO to UTF-8 */
Using str_replace function we can convert &amp to &

How to format JSON response using PHP

I'm using PHP and trying to get values from a MySQL database using jQuery/AJAX.
My mysql table has four columns: id, tail, cg and cw
My php code looks like this:
<?php
$inputvalue = $_POST;
$errors = false;
$result = false;
$mysqli = new mysqli('localhost', "root", "", "tp");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
foreach ($inputvalues as $key => $value) {
if(isset($value) && !empty($value)) {
$inputvalues[$key] = $mysqli->real_escape_string( $value );
} else {
$errors[$key] = 'The field '.$key.' is empty';
}
}
if( !$errors ) {
$addresult = "
SELECT *
FROM `air_cg`
WHERE `tail` = '" . $inputvalue['tail'] . "'
ORDER BY `id` DESC
";
if( $result = $mysqli->query($addresult) ) {
// collect results
while($row = $result->fetch_all())
{
$returnResult = $row;
}
}
}
mysqli_close($mysqli);
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
exit;
?>
The resulting JSON has this format:
{"result":[["255","Lapdogie","1","2"],["254","Lapdogie","23","234"],["253","Lapdogie","132","454"]],"errors":false}
My javascript code that im using for the ajax function and to parse the resulting JSON looks like this:
function getcgdata(aa){
$.ajax({
type: "POST",
url: "drawchart.php",
data: {tailnumber:taildata},
dataType: 'json',
cache: false,
})
.success(function(response) {
$('input').removeClass('error').next('.errormessage').html('');
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
var chartdata=(value);
var cgdata =(cg.value);
console.log(chartdata);
console.log(cgdata);
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
The console log for chartdata shows this:
["256", "Lapdogie", "232", "333"]
["239", "Lapdogie", "23", "12"]
["238", "Lapdogie", "1232", "1232"]
The console log for cgdata only shows one value many times:
232
232
232
I am not sure if the issue is with my PHP code or with the way im trying to parse the JSON.
i dont see that you define cg.value..
you use
var cgdata =(cg.value);
but cg is where defined?
it should be probably something like chartdata[3] .. ?
Rajdeep Paul's suggestion below worked for me for this particular situation:
Change
var cgdata =(cg.value);
to
var cgdata = value[2];
I'm aware that there are many issues with my code as pointed out by Ludovit Scholtz and Magnus Eriksson and I shall refine it at a later stage.
Thank you all!

Session Variable with ajax seems empty

I have a piece of code which is giving me trouble.
I am trying to get order values from a php class function :
public function generalSettings(){
$totalprijs = 0;
foreach($_SESSION['items'] as $key => $value){
$products->setProduct($key);
$totalprijs = $totalprijs + ($products->prijs_exBTW * $value);
}
$inclbtw = ($totalprijs * ('1.'.$this->BTWPercnt));
if($totalprijs > $this->franco_vanaf){
$verzendkosten = 0;
}else{
$verzendkosten = $this->verzendkosten;
}
$btw = ($totalprijs + $verzendkosten) * ('0.'.$this->BTWPercnt);
if($totalprijs > $this->franco_vanaf){
$totaalInc = ($totalprijs + $btw);
}else{
$totaalInc = ($totalprijs + $btw + $this->verzendkosten);
}
$return = array(
"subtotaal" => $totalprijs,
"btw" => $btw,
"inclbtw" => $inclbtw,
"verzendkosten" => $verzendkosten,
"totaalInc" => $totaalInc
);
return($return);
}
When I access this function from within the class it works.
And when I call other function that uses this function in my checkout it works.
But when I try to access it in my AJAX-handling file it says:
Warning: Invalid argument supplied for foreach()
The code,when I call the function in the ajax file is as below:
if($isValid == true){
unset($notneeded);
$notneeded = array("ww1","ww2","huisnr","vhuis","companyvat","companyname","tel","firstname","lastname");
foreach($_POST['gegevens'] as $key => $value){
if(in_array($key,$verplichtArray) && (!in_array($key,$notneeded))){
$fields .= "`".$key."`,";
$values .= "'".$value."',";
}
}
$shoppingcar = new Winkelwagen;
$order = $shoppingcar->generalSettings();
$fields .= '`timestamp`,`klant`,`totaal`,`totaalInc`,`verzendkosten`,`status`,`betaalmethode`';
$values .= "now(),'".$acc->id."','".$order['subtotaal']."','".$order['totaalInc']."','".$order['verzendkosten']."','3','".mysql_real_escape_string($_POST['betaalwijze'])."'";
if(isset($_POST['gegevens']['V'])){
$fields .= ',`V`';
$values .= ",'X'";
}
$message = "INSERT INTO order (".$fields.") VALUES (".$values.")";
}
It seems like when I call the function from the ajax file the session's empty
but when I call the function from the file where I call to the ajax file it works just fine.
Could anyone explain what I'm doing wrong???
EDIT
The piece of jquery i use to call the ajax file as requested:
$('#afrekenen').click(function(){
clearInterval(myInterval);
var fields = $('.addressform :input');
$.each(fields, function(field,val){
$(val).removeClass('errorInput');
})
var gegevens = {};
var adresform = $('.addressform').serializeArray();
$.each(adresform, function(index, val){
gegevens[this.name] = this.value;
});
if(!$('input[name=payment]:checked').val()){
var betaalwijze = 0;
}else{
var betaalwijze = $('.betaalwijze').val();
}
var voorwaarden = $('input[name=voorwaarden]:checked').val();
$.ajax({
type: 'post',
url: '/inc/afrekenen.php',
data: {"gegevens":gegevens ,"betaalwijze":betaalwijze,"voorwaarden":voorwaarden},
success: function(data) {
response = jQuery.parseJSON(data)
if(response.isValid == false){
$('#errormsg').html('<div class="alert alert-danger">'+
'<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'
+response.message+'</div>');
$.each(response.fouteVelden, function(index, object){
$('#'+object+'').addClass('errorInput');
});
}else{
$('#errormsg').html('<div class="alert alert-success">'+
'<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'
+response.message+'</div>');
}
}
});
});
if have the
ob_start(); tag and the session_start(); tag
also only the sessions that are somehow linked to my class are returning 1 when i try to print_r them the rest of my sessions still remain
the foreach through the $_SESSION['item'] in the first part of my code isn't working
all the other parts of code work
EDIT
A good nights sleep seems to have solved the conflict...
don't know what the error was and don't know how i fixed it but it works!
Thank you for the suggestions :)
if /inc/afrekenen.php is in the same domain as your class then session is shared
and phpsid cookie is passed along your ajax request.
In this case, the only problem would your session not being started in /inc/afrekenen.php.
Verify that session is started in /inc/afrekenen.php.
// print $_POST['gegevens'] if it is returning you a json string so
// do this
$postDataGegevens = json_decode($_POST['gegevens']);
// if $postDataGegevens in current format
// then pass in foreach
foreach($postDataGegevens as $key => $value){
// your code here ...
}
I noticed that my sessions where saved in
session_save_path('../tmp');
added this to the top of my ajax file and it worked it's magic
Thank you for the suggestions

Categories