Codeigniter 2.1, jquery - ajax(post) disallowed key characters - javascript

Jquery function (it is working):
del_selected.on('click', function(e){
box.filter(':checked').each(function(){
selektovane_slike.push($(this).val());
$(this).parent().slideUp('fast');
});
data = JSON.stringify(box.serialize(), null, 2);
console.log(data);
$.post(del_url, data, function(){
}, JSON);
e.preventDefault();
});
This function gives this result:
"slike=apples.jpg&slike=50BestBandLogos.jpg&slike=Great-Logos-200x200.jpg"
And in PHP we have this:
function ypg_delete_img_selected()
{
print_r($_POST);
}
Response which I get is:
Disallowed Key Characters.
What is the problem?
HTML:
<div class="zuta_strana_trenutne_slike">
<p>All Images</p>
<?php $imgs = explode(',', $zts['image']);
foreach($imgs as $img) : ?>
<div class="zuta_strana_izmena_slika">
<img src="<?php echo IMG ?>zute_strane/thumbs/<?php echo $img ?>" title="<?php echo $zts['name'] ?>" />
<input type="checkbox" name="slike" value="<?php echo $img ?>" />
Obriši Sliku
</div>
<?php endforeach; ?>
<a class="zute_strane_izmena_selektuj_sve">Select All</a>
Delete Selected
</div>

You need to update your allowed characters in application/config/config.php:
$config['permitted_uri_chars'] = 'a-z 0-9~%\.\:_\+-,?&=';
obviously modify that to suit your needs.

Relate an id to each image on the server and deal with ids instead of arbitrary file names. The way you are currently doing this is going to lead to a lot of headaches.

Related

How to get the value of the image when clickin

How to get the value of the image for us it on $_POST
$url_f = $crawler->filter('#content .galleries_overview .item')->each(function(crawler $node, $i) {
//echo $node->html();
$image = $node->filter('img')->attr('src');
$src = $node->filter('a')->attr('href');
$href = 'https://example.com/'. $src;
?>
<input type="image" name="submit_blue" value="<?php echo $href ?>" src="<?php echo $image ?>">
<?php
});
?>
you may use onclick
<input type="image" onclick="sendme('<?php echo $href ?>')" src="<?php echo $image ?>">
and add this to your page :
<form method="post" id="myform">
<input type="hidden" name="submit_blue" id="submit_blue" value="" >
</form>
<script>
function sendme(x) {
document.getElementById("submit_blue").value = x;
document.getElementById("myform").submit();
}
</script>
that is a javascript solution i use if i do not want to use jquery or something
By the way I don't like using URL as a value

Unset a single item form a php array embedded in a html site with JS button

My question is. I want to press that remove button at the end and remove my item form the session.
how can i do this?
js:
$('.remove button') .click (function() {
removeItem(This);
});
PHP and HTML:
<?php
foreach($_SESSION["cart"] as $item) {
$data = getProducts($pdo, $item);
if ($data["ColorName"] == NULL) {
$color = "";
} else {
$color = "Color: ".$data["ColorName"]."<br>";
}
if ($data["Size"] == "") {
$size = "";
} else {
$size = "Size: ".$data["Size"]."<br>";
}
print("<div class=\"basket-product\">
<div class=\"item\">
<div class=\"product-image\">
<img src=\"http://placehold.it/120x166\" alt=\"Placholder Image 2\" class=\"product-frame\">
</div>
<div class=\"product-details\">
<h1><strong><span class=\"item-quantity\">1</span> x ".$data["StockItemName"]."</strong></h1>
<p><strong>".$color." ".$size."</strong></p>
<p>Product Code - ".$data["StockItemID"]."</p>
</div>
</div>
<div class=\"price\">".$data["RecommendedRetailPrice"]."</div>
<div class=\"quantity\">
<input type=\"number\" value=\"1\" min=\"1\" class=\"quantity-field\">
</div>
<div class=\"subtotal\">". $data["RecommendedRetailPrice"] * 1 ."</div>
<div class=\"remove\">
<button>Remove</button>
</div>
</div>");
}
I tried using Unset in allot of places, but that doesn't seem to get working :')
:)
The solution is rather easy, but requires some explanation in order to be understood.
What you need here is to:
Create a new php file, which would fetch the post data (in this case ID of an element) and then simply unset the key (sub-array), which contains the cart item you want to remove.
You can use $key_to_remove = array_search($_POST['stock_item_id'], array_column($_SESSION["cart"], 'StockItemID')); and then simply unset it unset($_SESSION["cart"][$key_to_remove]);
Assign id="remove_<?php echo $data["StockItemID"]; ?>" to the <div class="basket-product"> and data-product-id="<?php echo $data["StockItemID"]; ?>" to the button, so you can identify it for item removal via javascript/jquery and you need that value extracted later for the item you want to remove from the corresponding session array (which is, in this case, $_SESSION["cart"]).
Create a callback function for removal on('click', function(){});
Inside that function extract that value data-product-id from the button you just clicked var stock_item_id=$(this).attr('data-product-id');
Inside the same function, after step 4, create an ajax call to the file from step 1 with the post data from step 4
On successful execution of an ajax call, delete the corresponding product row you have marked with id="remove_<?php echo $data["StockItemID"]; ?>" in step 2 with the following code $("#remove_"+stock_item_id).remove();
In the end, your code would look like this
YOUR INITIAL PHP AND HTML (With small corrections)
<?php
foreach($_SESSION["cart"] as $item) {
$data = getProducts($pdo, $item);
if ($data["ColorName"] == NULL) {
$color = "";
} else {
$color = "Color: ".$data["ColorName"]."<br>";
}
if ($data["Size"] == "") {
$size = "";
} else {
$size = "Size: ".$data["Size"]."<br>";
}
?>
<div class="basket-product">
<div class="item">
<div class="product-image">
<img src="http://placehold.it/120x166" alt="Placholder Image 2" class="product-frame">
</div>
<div class="product-details">
<h1>
<strong>
<span class="item-quantity">
1
</span>
x <?php echo $data["StockItemName"]; ?>
</strong>
</h1>
<p>
<strong>
<?php echo $color." ".$size; ?>
</strong>
</p>
<p>
Product Code - <?php echo $data["StockItemID"]; ?>
</p>
</div>
</div>
<div class="price">
<?php echo $data["RecommendedRetailPrice"]; ?>
</div>
<div class="quantity">
<input type="number" value="1" min="1" class="quantity-field">
</div>
<div class="subtotal">
<?php echo $data["RecommendedRetailPrice"]; ?> * 1
</div>
<div class="remove">
<button data-product-id="<?php echo $data["StockItemID"]; ?>">
Remove
</button>
</div>
</div>
<?php
}
?>
JS
$(document).ready(function(){
$('.remove button').on('click', function() {
var stock_item_id=$(this).attr('data-product-id');
$.ajax({
url: "new_php_file_created_to_remove_item_from_session_via_ajax.php",
data:
{stock_item_id : stock_item_id}
}).done(function() {
$("#remove_"+stock_item_id).remove();
});
});
});
NEW PHP FILE (new_php_file_created_to_remove_item_from_session_via_ajax.php)
<?php
$stock_item_id = $_POST['stock_item_id'];
$key_to_remove = array_search($_POST['stock_item_id'], array_column($_SESSION["cart"], 'StockItemID'));
unset($_SESSION["cart"][$key_to_remove]);
if(isset($_SESSION["cart"][$key_to_remove])) {
return false;
}
return true;
For the sake of readability and further maintenance and possible additions, I would strongly recommend you to separate php, html and js code into separate files, but that's only a suggestion. :)

On Click not working with JS

The code shown here is meant to take me to the next part of checkout process however I encounter the error that billing is not defined? I've tried to put a function and call that function via the onclick but this has no effect.
The code that isn't working shall be the bottom section of the code which is the JS along with the button just above
Below is the where you can see the button and the onclick callout
<div class="buttons-set form-buttons btn-only" id="billing-buttons-container">
<button type="button" class="btn" onclick="billing.save()"><span><span><?php echo $this->__('Continue') ?></span></span></button>
<span id="billing-please-wait" class="please-wait" style="display:none;">
<img src="<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif') ?>" alt="" class="v-middle" /> <?php echo $this->__('Loading next step...') ?>
</span>
</div>
<p class="required"><?php echo $this->__('* Required Fields') ?></p>
<?php echo $this->getBlockHtml('formkey') ?>
</form>
The JS below is not working correctly
<script type="text/javascript">
//<![CDATA[
var billing = new Billing('co-billing-form', '<?php echo $this->getUrl('checkout/onepage/getAddress') ?>address/', '<?php echo $this->getUrl('checkout/onepage/saveBilling') ?>');
var billingForm = new VarienForm('co-billing-form');
//billingForm.setElementsRelation('billing:country_id', 'billing:region', '<?php echo $this->getUrl('directory/json/childRegion') ?>', '<?php echo $this->__('Select State/Province...') ?>');
$('billing-address-select') && billing.newAddress(!$('billing-address-select').value);
var billingRegionUpdater = new RegionUpdater('billing:country_id', 'billing:region', 'billing:region_id', <?php echo $this->helper('directory')->getRegionJson() ?>, undefined, 'billing:postcode');
if ($('onepage-guest-register-button')) {
Event.observe($('onepage-guest-register-button'), 'click', function(event) {
var billingRememberMe = $('co-billing-form').select('#remember-me-box');
if (billingRememberMe.length > 0) {
if ($('login:guest') && $('login:guest').checked) {
billingRememberMe[0].hide();
} else if ($('login:register') && ($('login:register').checked || $('login:register').type == 'hidden')) {
billingRememberMe[0].show();
}
}
});
}
//]]>
</script>
jQuery was blocking another jQuery file and therefore it wasn't working correctly as intended, but since removing one of jQuery files it now works :D

Ajax comment system into a do-while loop

I have a comment system that is working fine. But now I wanna make it work into a loop, so it needs is add an id to identify as unique every "comment box", "submit buttom", so on. Due to there are many classes involved I got lost adding the index to the js function ... and actually everything.
This is my code:
<?php
$sql = mysql_query("SELECT * FROM tblopiniones_persopoli WHERE id_post = '$id_post' AND intActivo = '1' LIMIT 0,10") or die(mysql_error());
while($affcom = mysql_fetch_assoc($sql)){
$name = $affcom['intName'];
$email = $affcom['email'];
$comment = $affcom['strComment'];
$date = $affcom['date'];
// Get gravatar Image
// https://fr.gravatar.com/site/implement/images/php/
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;
?>
<div class="cmt-cnt">
<img src="<?php echo $grav_url; ?>" />
<div class="thecom">
<h5><?php echo ObtenerNombreFull_Usuario($name); ?></h5><span data-utime="1371248446" class="com-dt"></span>
<br/>
<p>
<?php echo $comment; ?>
</p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<div class="new-com-bt" id="<?php echo $m; ?>">
<span id="">Escribe un comentario ...</span>
</div>
<div class="new-com-cnt">
<a name="coment_box" id="coment_box">
<input type="hidden" id="name-com" name="name-com" value="<?php echo $_SESSION['MM_IdUser']; ?>" />
<input type="hidden" id="mail-com" name="mail-com" value="<?php echo 'xxxxxxx#gmail.com'; ?>" />
<input type="hidden" id="pic-com" name="pic-com" value="<?php echo ObtenerNombreFoto_Usuario($_SESSION['MM_IdUser']); ?>" />
<textarea class="the-new-com" placeholder="Ingresa tu comentario"></textarea>
<div class="bt-add-com">Publicar comentario</div>
<div class="bt-cancel-com">Cancelar</div>
</a>
</div>
My Js code:
<script type="text/javascript">
$(function(){
//alert(event.timeStamp);
$('.new-com-bt').click(function(event){
$(this).hide();
$('.new-com-cnt').show();
$('#coment_box').focus();
});
/* when start writing the comment activate the "add" button */
$('.the-new-com').bind('input propertychange', function() {
$(".bt-add-com").css({opacity:0.6});
var checklength = $(this).val().length;
if(checklength){ $(".bt-add-com").css({opacity:1}); }
});
/* on clic on the cancel button */
$('.bt-cancel-com').click(function(){
$('.the-new-com').val('');
$('.new-com-cnt').fadeOut('fast', function(){
$('.new-com-bt').fadeIn('fast');
});
});
// on post comment click
$('.bt-add-com').click(function(){
var theCom = $('.the-new-com');
var theName = $('#name-com');
var theMail = $('#mail-com');
var thePic = $('#pic-com');
if( !theCom.val()){
alert('¡Por favor escribe un comentario!');
}else{
$.ajax({
type: "POST",
url: "add-comment.php",
data: 'act=add-com&id_post='+<?php echo $id_post; ?>+'&name='+theName.val()+'&email='+theMail.val()+'&comment='+theCom.val()+'&pic='+thePic.val(),
success: function(html){
theCom.val('');
/*theMail.val('');
theName.val('');*/
$('.new-com-cnt').hide('fast', function(){
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
}
});
});
I'll highly appreciate any help with this lack of knowledge & expertise.
Many thanks in advance.

'Click' action conflict with `submit` action

So, I have the following setup with a Submit button that saves any changes.
<div class="mysite-body">
<?php do_action('mysite_pre_form_message'); ?>
<form action="" method="post" data-action="<?php echo $template; ?>">
<input type="hidden" name="user_id-<?php echo $i; ?>" id="user_id-<?php echo $i; ?>" value="<?php echo $user_id; ?>" />
<?php
if (!isset($user_id)) $user_id = 0;
$hook_args = array_merge($args, array('user_id' => $user_id, 'unique_id' => $i));
do_action('mysite_before_fields', $hook_args);
?>
<?php foreach( mysite_fields_group_by_template( $template, $args["{$template}_group"] ) as $key => $array ) { ?>
<?php if ($array) echo mysite_edit_field( $key, $array, $i, $args, $user_id ) ?>
<?php } ?>
<?php
if (!isset($user_id)) $user_id = 0;
$hook_args = array_merge($args, array('user_id' => $user_id, 'unique_id' => $i));
do_action('mysite_after_fields', $hook_args);
?>
<?php
if (!isset($user_id)) $user_id = 0;
$hook_args = array_merge($args, array('user_id' => $user_id, 'unique_id' => $i));
do_action('mysite_before_form_submit', $hook_args);
?>
<?php if ( mysite_can_delete_user($user_id) || $mysite->request_verification($user_id) || isset( $args["{$template}_button_primary"] ) || isset( $args["{$template}_button_secondary"] ) ) { ?>
<div class="mysite-field mysite-submit mysite-column" id="A">
<?php if (isset($args["{$template}_button_primary"]) ) { ?>
<input type="submit" value="<?php echo $args["{$template}_button_primary"]; ?>" class="mysite-button" />
<?php } ?>
<?php if (isset( $args["{$template}_button_mysite"] )) { ?>
<input type="button" value="<?php echo $args["{$template}_button_secondary"]; ?>" class="mysite-button secondary" data-template="<?php echo $args["{$template}_button_action"]; ?>" />
<?php } ?>
<?php if ( $mysite->request_verification($user_id) ) { ?>
<input type="button" value="<?php _e('Request Verification','mysite'); ?>" class="popup-request_verify mysite-button secondary" data-up_username="<?php echo $mysite->id_to_member($user_id); ?>" />
<?php } ?>
<?php if ( mysite_can_delete_user($user_id) ) { ?>
<input type="button" value="<?php _e('Delete Profile','mysite'); ?>" class="mysite-button red" data-template="delete" data-up_username="<?php echo $mysite->id_to_member($user_id); ?>" />
<?php } ?>
<img src="<?php echo $mysite->skin_url(); ?>loading.gif" alt="" class="mysite-loading" />
<div class="mysite-clear"></div>
</div>
<?php } ?>
</form>
</div>
<?php } ?>
Then following javascript:
<script>// <![CDATA[
jQuery("#A").click(function(){
jQuery("#B").trigger('click');
return false; });
// ]]></script>
And id="B" is on a header as a simple anchor button:
<div class="startskip"><a id="B" href="http://mysite/start/item">Skip</a></div>
What I want to achieve is that when a submit button is clicked, then the skip button is also triggered and the user will be redirected to the next page.
Of course, I am going to put setTimeoutso there is enough time to save instead of instant redirect.
However, the submit button becomes not-responsive when I add the javascript.
So, it seems that there is a javascript conflict between the click function and submit function. (Without the javascript, the submit button works).
By looking the code, could you guys figure out what the problem is and how to solve it?
Thanks!
I read an article on this previously which explains why it doesn't work - but have lost the link, I'll see if I can find it an update this post tomorrow. But the summary would be to say that the jQuery trigger click method triggers the event handler for the element, it does not trigger the browsers default behaviour i.e. following a link.
You have two choices, if you must use jQuery, then you can use this:
window.location = $('#B').attr('href');
Another option is to use pure JS:
document.getElementById("a_link").click();
In this case, I would go for the second option since I think it is more clear and readable - but that's subjective!
The return false inside the click handler cancels the original click and that is why the form doesn't get submitted.
I don't think it's possible to run any script after the form submission though. You could try submitting the form with ajax and on success do the redirect.

Categories

Resources