I wrote an user action analysis but I can't execute my insert into statement. I tried all suggestion on stack can't but figure out my mistake, I don't even get an error: it is running through without executing the statement. I have also an connection php - this works fine so the fault is not there. I would like to insert the action var later but at first I have to call the function. So whats wrong with my request or php function?
jQuery
$( document ).ready(function() {
var action = '';
document.addEventListener('click', function(e) {
e = e || window.event;
e = e.target || e.srcElement;
if (e.nodeName === 'SECTION') {
action = e.id;
updateAction();
}
}, false);
function updateAction() {
$.ajax({
type: "POST",
url: '../actions/userAction.php',
data: {action: 'test'},
success: function(){
console.log(action);
}
});
}
});
PHP
<?php
class userAction
{
/* User Action */
public function updateAction(){
if(isset($_POST['action']) && !empty($_POST['action'])) {
$db = getDB();
$st = $db->prepare("INSERT INTO user_analysis (action) VALUES ('bla') where userID = 1945");
$st->execute();
$db = null;
$_SESSION['uid']=$uid;
return true;
} else
{
return false;
}
}
}
?>
Where do you call updateAction() method? I assume you don't. Then why do you expect that it will execute? You have at least 3 ways to deal with it.
1. Make the method static and call it without instantiating a class
If you don't have any reason to construct an object of your class then you can call your method without doing it. Just add this line of code after your class definition:
userAction::updateAction()
This way you call the method which handles your POST request.
2. Instantiate your class and then call your method
The same story as above. The difference here is to construct an object first:
$ua = new userAction();
$ua->updateAction();
3. (the easiest) Get rid of the class and method
As the title suggest. Remove whole code of a class and leave only the body of your method. Like this:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$db = getDB();
$st = $db->prepare("INSERT INTO user_analysis (action) VALUES ('bla') where userID = 1945");
$st->execute();
$db = null;
$_SESSION['uid']=$uid;
return true;
} else {
return false;
}
This should be the whole content of your file: a condition.
BTW
1. Your query is not valid. If you want to UPDATE a row you need to use UPDATE statement, not INSERT
2. I would suggest you call your class UserAction (uppercase). Just to make it standardised and more intuitive
3. Why do you mix jQuery with VanillaJS? You use jQuery and bind an event using clear JS. Make it semantic and decide if you use jQuery or not.
jQuery way:
var action = '';
$(document).on('click', function(e) {
e = e || window.event;
e = e.target || e.srcElement;
if (e.nodeName === 'SECTION') {
action = e.id;
updateAction();
}
});
That's all. I hope I could help
You need to use UPDATE instead of INSERT. Try this below code:
UPDATE user_analysis SET action = 'bla' WHERE id = 1945
if(isset($_POST['action']) && !empty($_POST['action'])) {
echo $_POST['action'];
}
echo the value of $_POST['action'] inside your if loop...If not getting try to change the - type: "POST", to "GET",
Related
I've inherited a website with an obscure PHP framework called syndrome for which I can't find any documentation, but the problem I'm trying to solve should be fairly simple for a good PHP developer.
I am trying to make ajax requests from javascript to a php file to execute a particular function. The ajax request is simply:
loadNewImage = function(){
$.ajax({ url: '/app/library/Controller/Reel.php',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
}
The current PHP file is structured like this:
<?php
class Controller_Reel extends BaseController_Web {
protected function defaultAction() {
parent::getPage($this->template, 'home');
$homepage = Homepage::getInstance()->getHomepage();
$this->template->title = 'Homepage';
$this->template->image = $homepage['asset_image'];
$this->template->center = array('reel');
$this->setResponse($this->template);
}
}
What I want to do is add to the file a check for post data. I'm not good with PHP, but I tried:
<?php
if(isset($_POST['action']) && !empty($_POST['action'])) {
echo 'TEST POST';
}
class Controller_Reel extends BaseController_Web {
protected function defaultAction() {
parent::getPage($this->template, 'home');
$homepage = Homepage::getInstance()->getHomepage();
$this->template->title = 'Homepage';
$this->template->image = $homepage['asset_image'];
$this->template->center = array('reel');
$this->setResponse($this->template);
}
}
I'm assuming that's maybe because the check for post data is not happening within the class itself, but I'm not exactly sure how to structure the code. Can anybody help straighten me out?
UPDATE: I found this inside a file called ControllerSite.php -> (of which baseController_Web is extended:
protected function respond() {
switch($this->response_type) {
case self::RESPONSE_PAGE:
// always try to make ie use the latest rendering engine
case self::RESPONSE_TEXT:
Helper_Request::respond($this->processed_response, Helper_Request::RESPONSE_PRINT, Config::$platform);
break;
case self::RESPONSE_JSON:
Helper_Request::respond($this->processed_response, Helper_Request::RESPONSE_JSON, Config::$platform);
break;
case self::RESPONSE_REDIR:
Helper_Request::respond($this->processed_response, Helper_Request::RESPONSE_REDIR, Config::$platform);
break;
case self::RESPONSE_CONTENT:
// TODO: we'll need to figure the out, but don't need to worry about it for now
break;
}
return $this;
}
and then in Controller.php (of which ControllerSite.php is extended), this:
final private function execute() {
$action = $this->getMethodName();
$is_ajax = Helper_Request::isAjax();
$data_type = strtolower(Helper_Request::setDefault($_SERVER['HTTP_ACCEPT'], ''));
if($is_ajax && preg_match('/\w+\/json|\w+\/javascript/i', $data_type) && method_exists($this, $action . 'JsonAction')) {
// it there was a ajax json request and the ajax json specific method exists, execute it
return $this->{$action . 'JsonAction'}();
}
return $this;
}
Try this:
class Controller_Reel extends BaseController_Web {
protected function defaultAction() {
parent::getPage($this->template, 'home');
$homepage = Homepage::getInstance()->getHomepage();
$this->template->title = 'Homepage';
$this->template->image = $homepage['asset_image'];
$this->template->center = array('reel');
if(isset($_POST['action']) && !empty($_POST['action'])) {
$reponse['success'] = true;
$response['responseVal'] = 'This is a test';
$this->setResponse($response);
} else {
$this->setResponse($this->template);
}
}
}
Try to make a class method named testAction:
protected function testAction() {
parent::getPage($this->template, 'home');
$homepage = Homepage::getInstance()->getHomepage();
$this->template->title = 'Homepage';
$this->template->image = $homepage['asset_image'];
$this->template->center = array('reel');
$this->setResponse($this->template);
}
In ajax request you are trying to send action parameter with test value and i suppose it is the framework's duty to call the related method named with 'test' .
This may hep.
I am trying to modify a Cookie through an Ajax petition but it doesn't work. It modifies the Session but not the cookie. Here is my code:
HTML:
<li class="en_GB" id="1" onclick="changeLanguage('en_GB;1')"><span></span>ENGLISH</li>
Javascript:
function changeLanguage(lang){
$.ajax({
url: 'lib/loadLanguageList.php',
data: {lan: lang},
type: 'POST',
success: function(data){
location.reload();
}
});
}
PHP (loadLanguageList.php) / Action:
if(isset($_POST['lan']) && preg_match("/([a-z]+_[A-Z]+;[0-9]+)/", $_POST['lan'])){
setUserLanguage($_POST['lan']);
}
PHP (loadLanguageList.php) / function EDITED*:
(Following the suggestion of #MikeBrant, I've edited the function)
function setUserLanguage($lan){
$locale['value'] = "";
$locale['id'] = "";
if(isset($lan)){
$lan = explode(";", $lan);
$locale['value'] = $lan[0];
$locale['id'] = $lan[1];
} else if (!isset($_COOKIE["locale"])){
$lan = $this->getUserLanguage();
$locale['value'] = $lan[0]['value'];
$locale['id'] = $lan[0]['id'];
}
setcookie("locale","",time()-2592000);
setcookie("locale_id","",time()-2592000);
setcookie("locale",$locale['value'],time()+60*60*24*30);
setcookie("locale_id",$locale['id'],time()+60*60*24*30);
print_r($locale);
$_SESSION['locale'] = $locale['value'];
$_SESSION['locale_id'] = $locale['id'];
require_once(ROOT."/lib/utils/localization.php");
}
But the cookie is not being deleted and the print_r print $locale variable as it should be. I don't understand why the setcookie function didn't work.
First, let's rewrite your function to where it makes better logic sense in terms of the code path flow (i.e. we have simplified the conditionals).
function setUserLanguage($lan){
$locale['value'] = "";
$locale['id'] = "";
if(isset($lan)){
$lan = explode(";", $lan);
$locale['value'] = $lan[0];
$locale['id'] = $lan[1];
if(!isset($_COOKIE["locale"])){
setcookie("locale",$locale['value'],time()+60*60*24*30);
setcookie("locale_id",$locale['id'],time()+60*60*24*30);
} else {
$_COOKIE["locale"] = $locale['value'];
$_COOKIE["locale_id"] = $locale['id'];
}
} else if (!isset($_COOKIE["locale"])){
$lan = $this->getUserLanguage();
$locale['value'] = $lan[0]['value'];
$locale['id'] = $lan[0]['id'];
setcookie("locale",$locale['value'],time()+60*60*24*30);
setcookie("locale_id",$locale['id'],time()+60*60*24*30);
}
$_SESSION['locale'] = $locale['value'];
$_SESSION['locale_id'] = $locale['id'];
require_once(ROOT."/lib/utils/localization.php");
}
Now let's walk through the use cases here. Let's say the user already has a locale cookie set and they are trying to change it.
This user would pass this conditional:
if(isset($lan))
And should fail this conditional
if(!isset($_COOKIE["locale"]))
This means this code block would be executed:
$_COOKIE["locale"] = $locale['value'];
$_COOKIE["locale_id"] = $locale['id'];
This would change the cookie value for the duration of the script execution only, as nothing in the response to the browser would trigger a change in cookie value.
My guess is that you want to ALWAYS call setcookie().
Also I would think the whole (!isset($lan)) section of code could be removed in favor for throwing some kind of error, as having a "set" function without passing it a value doesn't seem to make much sense.
I have a page where I use jQuery load() method to display a table of results based on a post request of some fields. But I need this load() to display the table and also inform javascript if a condition is met in the PHP script, so probably I need a json response. I don't know if it's possible to use the complete() callback to achieve that. I only need a single variable to pass from my PHP script to javascript.
I'm using load() because I believe other ajax methods need to do the HTML template part from javascript, am I right?
Hope I made myself clear, thanks
UPDATE1:
Here is my js code:
$("#listaNegraView").load('procesos/funcionesAjax.php',
{accion: 'listaNegra',
nombres: $("#nombres").val(),
apellidoP: $("#apellidoP").val(),
apellidoM: $("#apellidoM").val(),
nacimiento: $("#nacimiento").val()},
function(data){console.log(data);}
);
And here is PHP script:
case 'listaNegra':
$_POST['nombres'] = mb_convert_encoding($_POST['nombres'], 'Windows-1252', 'UTF-8');
$_POST['apellidoP'] = mb_convert_encoding($_POST['apellidoP'], 'Windows-1252', 'UTF-8');
$_POST['apellidoM'] = mb_convert_encoding($_POST['apellidoM'], 'Windows-1252', 'UTF-8');
$listaNegra = $personaDB->existsPersonaListaNegra($_POST);
$pct100 = false;
if(!empty($listaNegra) && is_array($listaNegra)){
foreach($listaNegra as &$persona){
$persona['match'] = '';
$porcentaje = 80;
if(strtolower($persona['nombres']) == strtolower($_POST['nombres'])){
$persona['match'] .= 'name';
$porcentaje += 10;
}
if($_POST['nacimiento'] == $persona['fecha_nacimiento']){
$persona['match'] .= 'date';
$porcentaje += 10;
}
$persona['porcentaje'] = $porcentaje;
if($porcentaje == 100)
$pct100 = true;
}
unset($persona);
}
include(ROOT.RUTA_TPL.'ventas/listanegra.tpl.php');
break;
UPDATE 2:
Specifically the condition I want to pass to jasvascript is variable $pct100
You are "directly" outputting HTML code so I think, as a quick workaround, you should write the $pct100 in a hidden field/dom element and then access it with the complete callback in your javascript code.
This is an example of what I am suggesting
$("#listaNegraView").load(
'procesos/funcionesAjax.php',
{accion: 'listaNegra',
nombres: $("#nombres").val(),
apellidoP: $("#apellidoP").val(),
apellidoM: $("#apellidoM").val(),
nacimiento: $("#nacimiento").val()
},
function(data){
$('#where-to-put-html-code').html(data);
var pct100 = $('#where-to-put-html-code #hidden-field-id').val() == '1' ? true : false;
}
);
Answer added by the suggestion of the asker.
I'm using PHP, Smarty, jQuery, AJAX, Colorbox - a jQuery lightbox, etc. for my website. There is some old code done using jQuery AJAX method to display the message in popup using standard jQuery library functions. Now I want to replace that typical popup using Colorbox popup. In short Iwant to change the design part only the message part is as it is. I tried to do this but couldn't succeeded yet. Can you help me in doing the necessary changes to the existing old code in order to show the messages in Colorbox popup instead of typical popup? For your reference I'm putting the old code below:
Code from smarty template to give a call to the jQuery AJAX function is as follows:
<span class="submit edit_user_transaction_status" value="{$control_url}{$query_path}?op=edit_user_transaction&page={$page}&txn_no={$user_transaction_details.transaction_no}&transaction_data_assign={$user_transaction_details.transaction_data_assign}&user_id={$user_id}{if $user_name!=''}&user_name={$user_name}{/if}{if $user_email_id!=''}&user_email_id={$user_email_id}{/if}{if $user_group!=''}&user_group={$user_group}&{/if}{if $user_sub_group!=''}&user_sub_group={$user_sub_group}{/if}{if $from_date!=''}&from_date={$from_date}{/if}{if $to_date!=''}&to_date={$to_date}{/if}{if $transaction_status!=''}&transaction_status={$transaction_status}{/if}{if $transaction_no!=''}&transaction_no={$transaction_no}{/if}">Update</span>
The code from js file which contains the existing AJAX code is as follows:
$(document).ready(function() {
//This function is use for edit transaction status
$(document).on('click', '.edit_user_transaction_status', function (e) {
e.preventDefault();
$.colorbox.close();
//for confirmation that status change
var ans=confirm("Are you sure to change status?");
if(!ans) {
return false;
}
var post_url = $(this).attr('value');
var transaction_status_update = $('#transaction_status_update').val();
$.ajax({
type: "POST",
url: post_url+"&transaction_status_update="+transaction_status_update,
data:$('#transaction_form').serialize(),
dataType: 'json',
success: function(data) {
var error = data.login_error;
$(".ui-widget-content").dialog("close");
//This variables use for display title and success massage of transaction update
var dialog_title = data.title;
var dialog_message = data.success_massage;
//This get link where want to rerdirect
var redirect_link = data.href;
var $dialog = $("<div class='ui-state-success'></div>")
.html("<p class='ui-state-error-success'>"+dialog_message+"</p>")
.dialog({
autoOpen: false,
modal:true,
title: dialog_title,
width: 500,
height: 80,
close: function(){
document.location.href =redirect_link;
}
});
$dialog.dialog('open');
}
});
});
});
Now the code snippet from PHP file which contains the PHP code and success message is as follows:
case "edit_user_transaction":
$transaction_no = $request['txn_no'];
$transaction_status_update = $request['transaction_status_update'];
$transaction_data_assign = $request['transaction_data_assign'];
$user_id = $request['user_id'];
$from_date = $request['from_date'];
$to_date = $request['to_date'];
$page = $request['page'];
if($request['transaction_no']!=''){
$query = "&transaction_no=".$request['transaction_no'];
}
// If public transaction status is entered
if($request['transaction_status']!='') {
$query .= "&transaction_status=".$request['transaction_status'];
}
// For checking transaction no is empty, blank, and numeric
if($transaction_no!='' && !empty($transaction_no)) {
$objUserTransactions = new UserTransactions();
$objUserPackages = new UserPackages();
//if transaction status update to success and transaction data not yet assign
if(empty($transaction_data_assign) && $transaction_data_assign == 0 && $transaction_status_update == "success") {
$user_transactions = $objUserTransactions->GetUserTransactionsDetailsByTransactionNo($transaction_no, $user_id);
$i = 0 ;
$j = 0 ;
//Create array related study and test
foreach($user_transactions['transaction_details'] as $my_cart) {
if(!empty($my_cart['pack_id'])) {
if($my_cart['pack_type'] == 'study') {
$data['study'][$i] = $my_cart['pack_id'];
$i++;
}
if($my_cart['pack_type'] == 'test') {
$data['test'][$j]['pack_id'] = $my_cart['pack_id'];
$data['test'][$j]['pack_expiry_date'] = $my_cart['pack_expiry_date'];
$data['test_pack_ids'][$j] = $my_cart['pack_id'];
$j++;
}
}
}
if(!empty($data['study'])) {
$objUserStudyPackage = new UserStudyPackages();
//Update packages sold count & purchase date in package table
$objUserStudyPackage->UpdateStudyPackagePurchaseData($data['study']);
//For insert packages related data to package_user table
foreach($data['study'] as $study_pack_id) {
$objUserPackages->InsertStudyPackagesToPackageUser($study_pack_id, $user_id);
}
}
if(!empty($data['test'])) {
$objUserTestPackage = new UserTestPackages();
//Update packages sold count & purchase date in test package table
$objUserTestPackage->UpdateTestPackagePurchaseData($data['test_pack_ids']);
//For insert test related data to test_user table
foreach($data['test'] as $test_pack_data) {
$objUserPackages->InsertTestPackagesToTestUser($test_pack_data['pack_id'], $test_pack_data['pack_expiry_date'], $user_id);
}
}
//This function is use for update status inprocess to success and transaction_data_assign flag 1
$user_transactions = $objUserTransactions->UpdateTransactionStatusByTransactionNo($transaction_no, $user_id, $transaction_status_update, '1');
} else {
// This function is use for update status
$user_transaction_details = $obj_user_transactions->UpdateTransactionStatusByTransactionNo($transaction_no, $user_id, $transaction_status_update);
}
//Email functionality when status update
include_once("transaction_status_update_email.php");
**$reponse_data['success_massage'] = "Transaction status updated successfully";
$reponse_data['title'] = "Transaction";
$reponse_data['href'] = "view_transactions.php?page=".$page."&from_date=".$from_date."&to_date=".$to_date.$query;
$reponse_data['login_error'] = 'no';
$reponse_data = json_encode($reponse_data);
echo $reponse_data;
die();**
}
break;
The code shown in bold font is the success response message. Can you help me in this regard, please? Thanks in advance.
Yo, you asked for help in PHP chat. Hopefully this helps:
So the dialog portion at the bottom needs to change to support colorbox. Firstly, load all your colorbox stuff. Second, you'll need to create your colorbox content dynamically by either grabbing content from an element on the page or building it on the fly.
You might need to debug some of this but here's generally how you do this...
Delete the entire $dialog variable
var $dialog = .....
And change that to something that will look similar to:
var $dialog = $('<div>').addClass('ui-state-success').append($('<p>').addClass('ui-state-error-success').html(dialog_message));
Then you'll need to do something like this:
$.colorbox({html: $dialog});
If you're having trouble seeing the content that is dynamically built inside your colorbox try calling $.colorbox.resize() on the opened callback:
opened: function(){
$.colorbox.resize();
}
If that doesn't work you may also need to pass a innerWidth/innerHeight or width/height property inside the resize method.
I have used this function to submit to any url or 'self',
with or without a querystring, many times without any problems.
function submitu(url, q) {
var frm = document.<?php echo $formname ?>;
if (url == '') {url = '<?php echo $thispage?>'; }
frm.action = url+q; frm.submit(); }
If I try to move the PHP vars outside the function, as below, it stops working (frm undefined error)
var thispage = '<?php echo $thispage?>';
var frm = document.<?php echo $formname?>;
function submitu(url, q) {
if (url == '') {url = thispage;}
frm.action = url+q; frm.submit();}
I also tried var frm = document.forms[''];
I don't have any other conflicting javascript,
(1). Can anyone tell me why this is not working?
(2). And why the first method also fails if the function is placed
inside and at the top of the jquery $(function() {.....} ready function?
Many thanks
It fails because when outside the function, var frm = document.formname;
will be run immediately when the page loads, i.e. before the form element has actually been constructed, so you get 'undefined'. When inside the function, it is only run when the function is run, by which time the DOM is complete and it can find it.