Session Variable with ajax seems empty - javascript

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

Related

(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!

Multiple sets of data insert at one call into separate divs by unique id AJAX

Currently when asking the server for data, when one single set is sent back like so
{"num":1,"notification_id":"818","notification_content":
"Lucy Botham posted a status on your wall","notification_throughurl"}
the div is inserted.
But lets say there's two sets with different notification id's like so
{"num":1,"notification_id":"818","notification_content":
"Lucy Botham posted a status on your wall","notification_throughurl"}
{"num":1,"notification_id":"819","notification_content":
"Lucy Botham posted a status on your wall","notification_throughurl"}
Nothing happens
So I'll cut the code down as to show and example of what I have
success: function(response){
if(response.notification_id > notification_id){
$("#notif_ui"+ notification_id).prepend('
<div class="notif_text"><div id="notif_actual_text-'+response['notification_id']+'"
class="notif_actual_text"><img border=\"1\" src=\"userimages/cropped'+response
['notification_triggeredby']+'.jpg\"
onerror=this.src=\"userimages/no_profile_img.jpeg\"
width=\"40\" height=\"40\" ><br /></div></div>');
i = parseInt($("#mes").text()); $("#mes").text((i+response.num));
}
I was toying with the idea of maybe using
$.each(response, function (i, val)
But I'm still unsure.
EDIT
Exact response how it shows
{"num":1,"notification_id":"823","notification_content":"Lucy Botham posted a status on your wall","notification_throughurl"
:"singlepoststreamitem.php?streamitem_id=703","notification_triggeredby":"85","notification_status":"1"
,"notification_time":"2015-11-08 04:16:26"}{"num":1,"notification_id":"824","notification_content":"Lucy
Botham posted a status on your wall","notification_throughurl":"singlepoststreamitem.php?streamitem_id
=704","notification_triggeredby":"85","notification_status":"1","notification_time":"2015-11-08 04:16
:27"}
AND MY WHILE LOOP
while($row = mysqli_fetch_assoc($com)){
if($row['notification_status']==1){
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json['notification_id'] = $row['notification_id'];
$json['notification_content'] = $row['notification_content'];
$json['notification_throughurl'] = $row['notification_throughurl'];
$json['notification_triggeredby'] = $row['notification_triggeredby'];
$json['notification_status'] = $row['notification_status'];
$json['notification_time'] = $row['notification_time'];
echo json_encode($json);
}}
First you need to build an array of notifications, rather than a single one:
<?php
$json = array(
'notifications' => array()
);
while ($row = mysqli_fetch_assoc($com)) {
if ($row['notification_status'] == 1) {
$num = mysqli_num_rows($com);
$notification = array();
if ($num) {
$notification['num'] = 1;
} else {
$notification['num'] = 0;
}
$notification['notification_id'] = $row['notification_id'];
$notification['notification_content'] = $row['notification_content'];
$notification['notification_throughurl'] = $row['notification_throughurl'];
$notification['notification_triggeredby'] = $row['notification_triggeredby'];
$notification['notification_status'] = $row['notification_status'];
$notification['notification_time'] = $row['notification_time'];
$json['notifications'][] = $notification;
}
}
echo json_encode($json);
?>
Then you can access the notifications array from JavaScript:
success: function(response) {
$.each(response.notifications, function(i, notification) {
if (notification.notification_id > notification_id) {
$("#notif_ui" + notification_id).prepend('<div class="notif_text"><div id="notif_actual_text-' + notification['notification_id'] + '" class="notif_actual_text"><img border=\"1\" src=\"userimages/cropped' + notification['notification_triggeredby'] + '.jpg\" onerror=this.src=\"userimages/no_profile_img.jpeg\" width=\"40\" height=\"40\" ><br /></div></div>');
i = parseInt($("#mes").text());
$("#mes").text((i + response.num));
}
})
}
Note, completely untested, but hopefully you can see the difference!
Your php could be changed to
// you can just the the number of rows once outside the while loop
$num = mysqli_num_rows($com);
if($num){
$jsonNum = 1;
}else{
$jsonNum = 0;
}
while($row = mysqli_fetch_assoc($com)){
if($row['notification_status']==1){ // this would be unnecessary if you add it as a where conditional to your sql query
// add the num to the array to match your current data structure
$row['num'] = $jsonNum;
$json[] = $row;
}
}
echo json_encode($json);

How can i add a variable in AJAX URL

I have a function in php that need an id and i need to add a variable in my ajax url the id
PHP Code:
function get_json_selected($purpose)
{
//echo $this->input->post("ids");
$ids = explode(",", $this->input->post("ids"));
$site_url = site_url($this->router->class);
if ($purpose == "EQUIPEMENT"){
$this->db->select(
'a.id,
a.manufacturer,
a.description,
a.serial_no,
a.part_no,
a.status,
a.availability,
getReturnStatus(a.id) as return_status',
FALSE
);
$this->db->where_in('a.id', array_unique($ids));
$result = $this->db->get("equipments a")->result_array();
echo json_encode(array("spares" => $result));
} else {
$this->db->select(
'a.id,
a.manufacturer,
a.description,
a.serial_no,
a.part_no,
a.status,
a.availability,
getReturnStatus(a.id) as return_status',
FALSE
);
$this->db->where_in('a.id', array_unique($ids));
$result = $this->db->get($this->active_table." a")->result_array();
echo json_encode(array("spares" => $result));
}
}
Ajax Code:
this is just example of the variable of id.
$purpose = "EQUIPMENT"; // how can i add this php variable to ajax url
url: "<?=site_url('equip_request/get_json_selected');?>", // this is the current code how can i add id in this url
or is this code right?
url: "<?=site_url('equip_request/get_json_selected/'.$purpose);?>"
var purpose = '<?php echo json_encode($purpose); ?>';
url: 'example.php?=' + purpose;
+ is the concatenator in javascript. hope this helps. spend plenty of time and add plenty of security to echoing that var into javascript. else you could find yourself viction of xss.

Could someone clarify this code snippet for me?

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.

Counting clicks with jQuery and displaying with Ajax

I'm hacking away at some code in order to have it register a click on an invisible div element, which expands an article to reveal it's excerpt while adding a +1 to the number of time's it's been clicked by anyone. Afterwards it updates an element with ajax with the number of clicks it's received.
At least, that's the goal.
The following code ends up breaking Wordpress and gives me the white screen of doom. This is taken from a simple click counter with an Ajax callback to update the number.
Where my problem lies is hacking away at this for it to register clicks on a different element.
Without wasting too much of anyones time, here's my question:
Wouldn't I just need to rename all post_like to post_reader? Someone's been telling my in person that it should work so check your server but that is ridiculous... it seems.
Note, below where you see post_reader, it had said post_like previously.
// post click to expand button
$timebeforerevote = 1;
add_action('wp_ajax_nopriv_post-like', 'post_reader');
add_action('wp_ajax_post-like', 'post_reader');
wp_localize_script('like_post', 'ajax_var', array(
'url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('ajax-nonce')
));
function post_like()
{
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
die ( 'Busted!');
if(isset($_POST['post_reader']))
{
$ip = $_SERVER['REMOTE_ADDR'];
$post_id = $_POST['post_id'];
$meta_IP = get_post_meta($post_id, "voted_IP");
$voted_IP = $meta_IP[0];
if(!is_array($voted_IP))
$voted_IP = array();
$meta_count = get_post_meta($post_id, "votes_count", true);
if(!hasAlreadyVoted($post_id))
{
$voted_IP[$ip] = time();
update_post_meta($post_id, "voted_IP", $voted_IP);
update_post_meta($post_id, "votes_count", ++$meta_count);
echo $meta_count;
}
else
echo "already";
}
exit;
}
function hasAlreadyVoted($post_id)
{
global $timebeforerevote;
$meta_IP = get_post_meta($post_id, "voted_IP");
$voted_IP = $meta_IP[0];
if(!is_array($voted_IP))
$voted_IP = array();
$ip = $_SERVER['REMOTE_ADDR'];
if(in_array($ip, array_keys($voted_IP)))
{
$time = $voted_IP[$ip];
$now = time();
if(round(($now - $time) / 60) > $timebeforerevote)
return false;
return true;
}
return false;
}
function getPostReadLink($post_id)
{
$themename = "toolbox";
$vote_count = get_post_meta($post_id, "votes_count", true);
$output = '<div class="post-read">';
if(hasAlreadyVoted($post_id))
$output .= ' <span title="'.__('I like this article', $themename).'" class="qtip like alreadyvoted"></span>';
else
$output .= '<a href="#" data-post_id="'.$post_id.'">
<span title="'.__('I like this article', $themename).'"class="qtip like"></span>
</a>';
$output .= '<span class="count">'.$vote_count.'</span></div>';
return $output;
}
The function called when clicked:
jQuery(".expand").click(function(e){
e.preventDefault();
readers = jQuery(this);
// Retrieve post ID from data attribute
post_id = readers.data("post_id");
// Ajax call
jQuery.ajax({
type: "post",
url: ajax_var.url,
data: "action=post-reader&nonce="+ajax_var.nonce+"&post_reader=&post_id="+post_id,
success: function(count){
// If vote successful
if(count != "already")
{
heart.addClass("readered");
heart.siblings(".count").text(count);
}
}
});
return false;
})
Invoking it within the appropriate div.
<?php echo getPostReadLink(get_the_ID());?>

Categories