I have a small php class which i have edited a little to ask my question.
The class is a shown beloww
class Register
{
public $notification = null;
public function __construct()
{
create_connection();
$this->validate_register();
}
public function validate_register()
{
//edit: missing double quote close
$select_register = "SELECT * FROM `student_reg`";
if($select_register_run = mysql_query($select_register))
{
$rows_returned = mysql_num_rows($select_register_run);
if($rows_returned >= 1)
{
$this->notification = 'error';
}else if($rows_returned == 0){
$this->notification = 'success';
}
}else{
$this->notification = 'error';
}
if($this->notification != null)
{
echo 'not null';
}else{ echo 'null';}
}
}
$new_register = new Register();
?>
It is clear that from the class, at any possible level, there is a value assigned to $this->notification. But for some reason, the class 'echoes' null.
The creat_connection() i built functions works perfectly but i have ommited it for the purpose of this question.
Why is this the case?
Actually, if $rows_returned is less than 1 and not equal to 0, the code will echo 'null', so I suggest you echo $rows_returned.
Try like this...
$select_register_run = mysql_query($select_register);
if($select_register_run){
//rest code
instead of
if($select_register_run = mysql_query($select_register))
Related
(Sorry for my bad English)
I'm trying to change a quantity value inside an array after clicking a button
I tried searching for help on the web, but all topics I found don't use session and that bunch of things that I found in that code (I found that code on the internet)
if (isset($_POST["add_to_cart"])) {
if (isset($_SESSION["shopping_cart"])) {
$item_array_id = array_column($_SESSION["shopping_cart"], "item_id");
if (!in_array($_GET["id"], $item_array_id)) {
$count = count($_SESSION["shopping_cart"]);
$item_array = [
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"],
];
$_SESSION["shopping_cart"][$count] = $item_array;
} else {
echo '<script>alert("Item Already Added")</script>';
echo '<script>window.location="foodlist.php"</script>';
}
When I click submit, this "add_to_cart" is set and all information is sent to another page, but when I click it again to add 1 more item (the same item I clicked before) the code doesn't make a sum. I tried a lot of things in this else, but even my teacher couldn't help me :/
Here you have cart class sample:
<?php
class Cart
{
private $cart = array();
function __construct()
{
$this->cart = $_SESSION['cart'];
}
public function addProduct($id, $price)
{
$this->cart['products'][$id]['price'] = $price;
$this->cart['products'][$id]['quantity'] = $this->cart['products'][$id]['quantity'] + 1;
}
public function removeProduct($id)
{
$this->cart['products'][$id]['quantity'] = $this->cart['products'][$id]['quantity'] - 1;
if($this->cart['products'][$id]['quantity'] == 0){
unset($this->cart['products'][$id]);
}
}
public function delProduct($id)
{
unset($this->cart['products'][$id]);
}
public function showCart()
{
echo "<pre>";
print_r($this->cart);
echo "</pre>";
}
function sumCart(){
$sum = 0;
foreach ($this->cart['products'] as $k => $item) {
$sum = $sum + ((float) $item['price'] * (int) $item['quantity']);
}
return $sum;
}
// Save cart to session
public function saveCart()
{
$_SESSION['cart'] = $this->cart;
}
}
$cart = new Cart();
// Add products
$cart->addProduct(1,123.55);
$cart->addProduct(9,93.00);
$cart->addProduct(33,1.22);
// Save to session
$cart->saveCart();
// Show cart
$cart->showCart();
// Show sum
echo "Sum " . $cart->sumCart();
?>
Try like this.
What I am trying to do is get scripts from body tag but only scripts that have text not script links
eg. <script type="text/javascript">console.log("for a test run");</script>
not the scripts that have file src.
And I want to place those scripts to end of page before </body>.
So far I have
echo "<pre>";
echo "reaches 1 <br />";
//work for inpage scripts
$mainBody = #$dom->getElementsByTagName('body')->item(0);
foreach (#$dom->getElementsByTagName('body') as $head) {
echo "reaches 2";
foreach (#$head->childNodes as $node) {
echo "reaches 3";
var_dump($node);
if ($node instanceof DOMComment) {
if (preg_match('/<script/i', $node->nodeValue)){
$src = $node->nodeValue;
echo "its a node";
var_dump($node);
}
}
if ($node->nodeName == 'script' && $node->attributes->getNamedItem('type')->nodeValue == 'text/javascript') {
if (#$src = $node->attributes->getNamedItem('src')->nodeValue) {
// yay - $src was true, so we don't do anything here
} else {
$src = $node->nodeValue;
}
echo "its a node2";
var_dump($node);
}
if (isset($src)) {
$move = ($this->params->get('exclude')) ? true : false;
foreach ($omit as $omitit) {
if (preg_match($omitit, $src) == 1) {
$move = ($this->params->get('exclude')) ? false : true;
break;
}
}
if ($move)
$moveme[] = $node;
unset($src);
}
}
}
foreach ($moveme as $moveit) {
echo "Moving";
print_r($moveit);
$mainBody->appendChild($moveit->cloneNode(true));
if ($pretty) {
$mainBody->appendChild($newline->cloneNode(false));
}
$moveit->parentNode->removeChild($moveit);
}
$mainBody = $xhtml ? $dom->saveXML() : $dom->saveHTML();
JResponse::setBody($sanitize?preg_replace($this->sanitizews['search'],$this->sanitizews['replace'],$mainBody):$mainBody);
Update 1
The problem is <script type="text/javascript"> can also be in div or can be in nested divs. So as using foreach #$head->childNodes only gets the top html tags and do not scan the inner tags that may contain <script> tags. I don't understand how to get all required script tags.
And there is no error but there also has no script tags on top nodes.
Update 2
After an answer of xpath, thanks for the answer. There is some progress in task. But now after moving of scripts to footer, I can't delete/remove original script tags.
Here is the updated code I have so far:
echo "<pre>3";
// echo "reaches 1 <br />";
//work for inpage scripts
$xpath = new DOMXPath($dom);
$script_tags = $xpath->query('//body//script[not(#src)]');
foreach ($script_tags as $tag) {
// var_dump($tag->nodeValue);
$moveme[] = $tag;
}
$mainBody = #$dom->getElementsByTagName('body')->item(0);
foreach ($moveme as $moveItScript) {
print_r($moveItScript->cloneNode(true));
$mainBody->appendChild($moveItScript->cloneNode(true));
// var_dump($moveItScript->parentNode);
// $moveItScript->parentNode->removeChild($moveItScript);
/* try{
$mainBody->appendChild($moveit->cloneNode(true));
if ($pretty) {
$body->appendChild($newline->cloneNode(false));
}
$moveit->parentNode->removeChild($moveit);
}catch (Exception $ex){
var_dump($ex);
}*/
}
echo "</pre>";
Update 3
I was working for Joomla, was trying to move scripts to footer of the page. I had used the scriptsdown plugin, which moved the scripts from head tag to bottom. but the scripts with in the mid page were not moved to the bottom, so that what was causing the inpage scripts to not respond properly.
My problem is now solved. Posting my solution code so if it might help someone in future.
function onAfterRender() {
$app = JFactory::getApplication();
$doc = JFactory::getDocument();
/* test that the page is not administrator && test that the document is HTML output */
if ($app->isAdmin() || $doc->getType() != 'html')
return;
$pretty = (int)$this->params->get('pretty', 0);
$stripcomments = (int)$this->params->get('stripcomments', 0);
$sanitize = (int)$this->params->get('sanitize',0);
$debug = (int)$app->getCfg('debug',0);
if($debug) $pretty = true;
$omit = array();
/* now we know this is a frontend page and it is html - begin processing */
/* first - prepare the omit array */
if (strlen(trim($this->params->get('omit'))) > 0) {
foreach (explode("\n", $this->params->get('omit')) as $omitme) {
$omit[] = '/' . str_replace(array('/', '\''), array('\/', '\\\''), trim($omitme)) . '/i';
}
unset($omitme);
}
$moveme = array();
$dom = new DOMDocument();
$dom->recover = true;
$dom->substituteEntities = true;
if ($pretty) {
$dom->formatOutput = true;
} else {
$dom->preserveWhiteSpace = false;
}
$source = JResponse::getBody();
/* DOMDocument can get quite vocal when malformed HTML/XHTML is loaded.
* First we grab the current level, and set the error reporting level
* to zero, afterwards, we return it to the original value. This trickery
* is used to keep the logs clear of DOMDocument protests while loading the source.
* I promise to set the level back as soon as I'm done loading source...
*/
if(!$debug) $erlevel = error_reporting(0);
$xhtml = (preg_match('/XHTML/', $source)) ? true : false;
switch ($xhtml) {
case true:
$dom->loadXML($source);
break;
case false:
$dom->loadHTML($source);
break;
}
if(!$debug) error_reporting($erlevel); /* You see, error_reporting is back to normal - just like I promised */
if ($pretty) {
$newline = $dom->createTextNode("\n");
}
if($sanitize && !$debug && !$pretty) {
$this->_sanitizeCSS($dom->getElementsByTagName('style'));
}
if ($stripcomments && !$debug) {
$comments = $this->_domComments($dom);
foreach ($comments as $node)
if (!preg_match('/\[endif]/i', $node->nodeValue)) // we don't remove IE conditionals
if ($node->parentNode->nodeName != 'script') // we also don't remove comments in javascript because some developers write JS inside of a comment
$node->parentNode->removeChild($node);
}
$body = #$dom->getElementsByTagName('footer')->item(0);
foreach (#$dom->getElementsByTagName('head') as $head) {
foreach (#$head->childNodes as $node) {
if ($node instanceof DOMComment) {
if (preg_match('/<script/i', $node->nodeValue))
$src = $node->nodeValue;
}
if ($node->nodeName == 'script' && $node->attributes->getNamedItem('type')->nodeValue == 'text/javascript') {
if (#$src = $node->attributes->getNamedItem('src')->nodeValue) {
// yay - $src was true, so we don't do anything here
} else {
$src = $node->nodeValue;
}
}
if (isset($src)) {
$move = ($this->params->get('exclude')) ? true : false;
foreach ($omit as $omitit) {
if (preg_match($omitit, $src) == 1) {
$move = ($this->params->get('exclude')) ? false : true;
break;
}
}
if ($move)
$moveme[] = $node;
unset($src);
}
}
}
foreach ($moveme as $moveit) {
$body->appendChild($moveit->cloneNode(true));
if ($pretty) {
$body->appendChild($newline->cloneNode(false));
}
$moveit->parentNode->removeChild($moveit);
}
//work for inpage scripts
$xpath = new DOMXPath($dom);
$script_tags = $xpath->query('//body//script[not(#src)]');
$mainBody = #$dom->getElementsByTagName('body')->item(0);
foreach ($script_tags as $tag) {
$mainBody->appendChild($tag->cloneNode(true));
$tag->parentNode->removeChild($tag);
}
$body = $xhtml ? $dom->saveXML() : $dom->saveHTML();
JResponse::setBody($sanitize?preg_replace($this->sanitizews['search'],$this->sanitizews['replace'],$body):$body);
}
In order to get ONLY the <script> nodes that dont have the src attribute you better use the DOMXPath:
$xpath = new DOMXPath($dom);
$script_tags = $xpath->query('//body//script[not(#src)]');
The variable $script_tags is now a DOMNodeList object that contains all of your script tags.
You can now loop over the DOMNodeList to get all the nodes and do whatever you would like to do with them:
foreach ($script_tags as $tag) {
var_dump($tag->nodeValue);
$moveme[] = $tag;
}
I'm total beginner to ajax (don't know jquery at all) so i've been using simple ajax without jquery, what i want to do is simple to call codeigniter's controller method. Dont know what i'm wrong at. Here's my ajax function and controller:
function usernameOnChange() {
var username = document.getElementById("register_username").value;
if (username.length == 0) {
document.getElementById("usernameGlyph").className = "glyphicon glyphicon-remove";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("usernameGlyph").className = 'glyphicon glyphicon-ok';
}
};
var link = "<?php echo base_url("index.php/Test/checkUsername?username="); ?>" + username ;
xmlhttp.open("GET", link, true);
xmlhttp.send();
}
}
And here's my controller (it's still test controller just to see that my ajax-codeigniter php connection is working).
<?php
class Test extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper("url");
$this->load->library("form_validation");
$this->load->helper("security");
$this->load->helper("form");
}
public function checkUsername($username) {
echo "<script>alert('CODEIGNITER RESPONDED!');</scirpt>";
}
}
?>
Thanks in advance!
Before you start with ajax, need to understand that ajax required to have good output from the PHP to get perfect result of the call. In your codeigniter controller, you are echoing a script tag. Please dont do that when you use a ajax call.
Sample Codeigniter Controller function
<?php
class Test extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper("url");
$this->load->library("form_validation");
$this->load->helper("security");
$this->load->helper("form");
}
public function checkUsername($username) {
$output = array('status'=>200,"message"=>"Your Ajax is called");
header('Content-Type:application/json;');//Please do not forgot to set headers
echo json_encode($output);
}
}
Here the controller will give perfect output which javascript can read it easiliy
For jQuery
<script type="text/javascript">
$.get('<?php echo base_url("index.php/Test/checkUsername?username=xyz"); ?>',function(data){
alert(data['message']);
});
</script>
First of all your this line will produce error or unexpected result.
var link = "<?php echo base_url("index.php/Test/checkUsername?username="); ?>" + username ;
//double quote inside double quote
It should be like this
var link = "<?php echo base_url('index.php/Test/checkUsername?username='); ?>" + username ;
You also need to know how site_url and base_url function produce links
Finally I think your link should be like this.
var link = "<?php echo base_url('index.php/Test/checkUsername/'); ?>" + username ;
//you can remove index.php if you set your config file properly.
Okay, so here's solution that I've found out and it works fine. It changes icon-span of input field to tick if login username that is typed at the moment exists in database. Otherwise it changes icon to cross. Don't forget to add "&" when sending via "get" more than 1 parameter to controller's method.
$("#login_username").keyup(function() {
$.ajax({
type: 'GET',
url: '<?php echo base_url().'index.php/Test/checkLoginUsername'; ?>',
data: 'type=' + $('#logintype').is(':checked') + '&username=' + $("#login_username").val(),
success: function(newClassType) {
$("#usernameLoginGlyph").removeClass().addClass(newClassType);
}
})
});
Here's my controller method that echos result class type of icon.
public function checkLoginUsername() {
// type = true for customer; false for artist
$type = $this->input->get('type');
$username = $this->input->get('username');
if ($type === "true") {
if ($username === "" || $this->Customer_model->getCustomerByUsername($username)) {
echo "glyphicon glyphicon-ok";
} else {
echo "glyphicon glyphicon-remove";
}
} else {
if ($username === "" || $this->Artist_model->getArtistByUsername($username)) {
echo "glyphicon glyphicon-ok";
} else {
echo "glyphicon glyphicon-remove";
}
}
}
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.
I have a JavaScript function as follows:
function popup(username) {
var req = createAjaxObject();
var message = prompt("Message:","");
if(message != ""){
req.onreadystatechange = function() {
if (req.readyState == 4) {
alert(req.responseText);
}
}
req.open('POST','getmessage.php',true);
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.send("username=" + username +"&message="+message);
} else {
alert("Please enter a message");
}
}
When the Cancel button is hit, the form is still processed through getmessage.php. Any way to have the Cancel button do nothing?
EDIT:
Here is the way this function is called:
<?php
mysqlLogin();
$username = $_COOKIE['sqlusername'];
$sql = mysql_query("SELECT username FROM `users` WHERE username!='$username'");
if(mysql_num_rows($sql) != 0) {
echo "<table class='usertable' align='center'>";
while($row = mysql_fetch_array($sql)){
$username = $row['username'];
echo "<tr><td><center>" . $row['username'] . "</center></td><td> Send Message</td></tr>";
}
echo "</table>";
} else {
echo "<center>No users found!</center>";
}
?>
The PHP script its linked to:
<?php
$id = rand(1,1500);
$poster = $_POST['username'];
$message = $_POST['message'];
$to = $_COOKIE['sqlusername'];
require('functions.php');
mysqlLogin();
$sql = mysql_query("INSERT INTO `messages` VALUES ('$id','$message','$to','$poster','')");
if($sql){
echo "Message sent!";
} else {
echo "Woops! Something went wrong.";
}
?>
In the case of Cancel, the prompt result is null, and null != '' (as per ECMA-262 Section 11.9.3).
So, add an extra explicit check for null inequality:
if(message != "" && message !== null) {
However, since the message is either some string or null and you only want to pass when it's a string with length > 0, you can also do:
if(message) {
This means: if message is truthy (i.e. not null or an empty string, amongst other falsy values), then enter the if clause.
Are you using Safari by any chance? I have found that Safari seems to be returning empty string instead of null when the user clicks Cancel.
See here: Safari 5.1 prompt() function and cancel.
Yeah, my suggested comment does work
var message = prompt("Message:","");
if(message){
alert("Not working!");
} else {
alert("Working!");
}
JSFiddle
var message = prompt("Message:","");
if(message){
alert("Message accepted, now i can process my php or script and blablabla!");
} else {
alert("Cancel Press or Empty Message, do nothing!");
}
var message = prompt('type any...', '');
if(message+'.' == 'null.')
{
alert("you've canceled");
}
else
{
alert("type ok");
}
$.messager.prompt('Save To File', 'FileName:', function(e){
if (e.response!='undefined'){
if (r!="")
{
alert('Your FileName is:' + r);
}
else
{
$.messager.alert('Err...','FileName cannot empty!!!');
}
}
});