I need help. Now I trying to create a function that can detect any change value from PHP form. Now I'm working using CodeIgniter. I explain more detail about this.
I making an e-commerce site. If the user in the cart page and changing the qty but the user not yet checkout and still want to browser more.... when the user has to change qty and press to another page. It will display pop up alert. This pop-up alert have a function to save the changing Qty. But if the user not changing anything. The pop-up alert should not show.
I already set this in the menu.
<?php echo form_open('order_products_execute', 'class="order_form"'); ?>
<?php include(VIEWPATH.'_order_parts.html') ?>
<div class="common_btn_area">
<input type="hidden" name="branch_id" value="<?php echo $branch_id; ?>">
<button type="button" class="add_cart_more">add more</button>
<button type="submit" class="common_save_btn confirmation">Order</button>
</div>
<?php echo form_close(); ?>
<!-- footer menu -->
<ul>
<li>
<a href="<?php echo base_url('top/'); ?>" class="footer_link" onclick="ExitCart('<?php echo base_url('top/'); ?>')" >
<span>Home</span>
</a>
</li>
<li>
<a href="<?php echo base_url('product/'); ?>" class="footer_link" onclick="ExitCart('<?php echo base_url('product/'); ?>')" >
<span>Product</span>
</a>
</li>
</ul>
and set the script
<script>
function ExitCart(link){
var $form = $('.order_form');
#code for compare previous value with changing value
$.ajax( {
type: $form.attr('method'),
url : "/buyer/ajax/compare_form_add_cart",
dataType : "json",
data : $form.serialize(),
success : function(resultdata) {
if(resultdata){
if(confirm("Do you want to save your changes?")){
#if confirm yes
$.ajax({
type: 'post',
url: '/buyer/Ajax/add_order_data_in_cart_session',
data: $('.order_form').serialize(),
dataType: 'json',
success: function(res, textStatus, xhr){
if(res.result) {
location.href = link;
} else {
$( "#loading_layer" ).css('display', 'none');
alert('Failed to save cart data. Please try again.');
}
}
});
}else{
#if confirm not
location.href = link;
};
}else{
return true;
}
}
});
}
</script>
When I implement this ajax code, sometimes the code is working. But sometimes it is not. Is there any code that can detect any change from the form. But without the press submit button.
in jQuery you can bind all the inputs changes
$('.order_form input').change(functon(){
var $form = $('.order_form');
#code for compare previous value with changing value
$.ajax( {
type: $form.attr('method'),
url : "/buyer/ajax/compare_form_add_cart",
dataType : "json",
data : $form.serialize(),
success : function(resultdata) {
if(resultdata){
if(confirm("Do you want to save your changes?")){
#if confirm yes
$.ajax({
type: 'post',
url: '/buyer/Ajax/add_order_data_in_cart_session',
data: $('.order_form').serialize(),
dataType: 'json',
success: function(res, textStatus, xhr){
if(res.result) {
location.href = link;
} else {
$( "#loading_layer" ).css('display', 'none');
alert('Failed to save cart data. Please try again.');
}
}
});
}else{
#if confirm not
location.href = link;
};
}else{
return true;
}
}
});
})
You need to make copies of your input fields for example
// Input Field (TEXT)
< input type="text" id="input1" value="Same Value" />
// Hidden Input for comparison
< input type="hidden" value="Same Value" />
at on click function, you should compare these fields like
function ExitCart(link){
// Get Input Value
var val = $.trim($('#input1').val());
// Get Reference Value from next input
var valChk = $.trim($('#input1').next().val());
if(val != valChk) {
YOUR CODE HERE
}
}
Related
Need some help, ive searched google and have no luck.
I am trying to update my radios-button's value in the div class "size-number". That value I want use it within the ajax request below. When i inspect element, the radio-button has the updated value of the button available but when i console.log it in jquery, it gives me the same initial value, despite which i pick. Ive tried setting the radio-buttons to checked="checked". Also i believe its a matter of the default value. Ive also tried input validation within jquery. In addition, ive attempted to reference the input ("input[name='radiobten']:checked") in jquery as well. any suggestions would very appreciated!
$(".size-number").click(function(){
var modelid = $("#modelval").attr('value');
console.log(modelid);
$.ajax({
url: '"Example API"',
data: [],
dataType: 'json',
type: "GET",
success: function(res){
var newarr = (res).filter(function(indx){
return indx.model_cat_id == modelid
});
console.log(newarr)
$('modelselect').slideToggle(200).html(res);
}});
});
<?php foreach ($brands as $brand){ ?>
<div class="search-select">
<i class="fas fa-chevron-down"></i>
<a href="/<?php echo $brand->full_slug.$urlSize; ?>">
<?php echo $brand->name; ?></a>
</div>
<?php
$slugCurrent = $brand->slug;
foreach ($models as $model){
if($model->brand_id == $brand->id){
if(is_null($model->model_cat_id)){?>
<div class="size-number" style="display: none;">
<?php echo $model->name; ?><input type="radio" id="modelval" name="radiobten" value="<?php echo $model->id?>"/>
</div>
<?php
}
}
}
}?>
You cannot have multiple element with same id i.e : modelval. This will always give you value of first radio button no matter which button you choose.Instead use class to get value of radio button.So ,onclick of div you can use $(this).find("yourclassname").attr('value') to get value of that particular button only.
Demo Code :
$(".size-number").click(function() {
//div->find closest modelval->value
var modelid = $(this).find(".modelval").attr('value');
console.log(modelid);
$.ajax({
url: '"Example API"',
data: [],
dataType: 'json',
type: "GET",
success: function(res) {
var newarr = (res).filter(function(indx) {
return indx.model_cat_id == modelid
});
console.log(newarr)
$('modelselect').slideToggle(200).html(res);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="size-number" >
Abc<input type="radio" class="modelval" name="radiobten" value="1"/>
</div>
<div class="size-number" >
Xyz<input type="radio" class="modelval" name="radiobten" value="2"/>
</div>
I am trying to pass a variable when a class("women") is clicked using ajax to a php file but it is not working. Here is my code
jquery:
$('.women').click(function(){
var test="hello";
$.ajax({
type: "POST",
url: 'data.php',
data: {'variable':test},
success:function(data){
console.log(data);
},
});
$(".women").attr('href','data.php');
})
php code:
if (isset($_POST['variable']))
{
echo($_POST['variable']);
}
else
{
echo ("failure");
}
html:
<li class="nav-item mr-auto ml-auto" data-target="#collapsewomen">
<a class="nav-link active women productlink" href="#">Women</a>
</li>
In the console I can see "hello" which mean ajax is working, but once directed to php page I get "failure". What I am not able to pass test variable to php file
The purpose of ajax is to send data to a URL without refreshing the page. If you want redirect the page, there is no use of using ajax.
Doing an ajax call will not automatically save the data sent and the data can't be use if you redirect to that page.
Using GET
$('.women').click(function(){
var test="hello";
window.location.href = "data.php?variable=" + test;
})
On your php
if (isset($_GET['variable']))
{
echo($_GET['variable']);
}
else
{
echo ("failure");
}
Using POST, one option is to use hidden form like:
On your main page:
$('.women').click(function(){
var test = "hello";
$('[name="variable"]').val(test); //Update the value of hidden input
$("#toPost").submit(); //Submit the form
})
HTML:
<a class="nav-link active women productlink" href="#">Women</a>
<form id="toPost" action="data.php" method="POST">
<input type="hidden" name="variable" value="">
</form>
On your data.php:
<?php
if (isset($_POST['variable']))
{
echo($_POST['variable']);
}
else
{
echo ("failure");
}
?>
I think it should be data: {variable:test} not data: {'variable':test}
add this to your frontend file
<input type="button" class="women" value="Button" name="ash_b" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js" >
$('.women').click(function(){
var test="hello";
$.ajax({
type: "POST",
url: 'data.php',
data: {'variable':test},
success:function(data){
console.log(data);
},
});
$(".women").attr('href','data.php');
})
</script>
And in your data.php use following code
if (isset($_POST['variable']))
{
echo($_POST['variable']);
}
else
{
echo ("failure");
}
it works perfectly for me, try this if this doesnt work show your both files
Please try this code:
$('.women').click(function(){
var test="hello";
var datastr = 'test='+test;
$.ajax({
type: "POST",
url: 'data.php',
data: datastr,
success:function(data){
console.log(data);
},
});
$(".women").attr('href','data.php');
})
I have this php script to count button clicks to a txt file
<?php
if (isset($_POST['clicks1'])) {
incrementClickCount1();
}
function getClickCount1() {
return (int) file_get_contents("count_files/clickcount1.txt");
}
function incrementClickCount1() {
$count = getClickCount1() + 1;
file_put_contents("count_files/clickcount1.txt", $count);
}
if (isset($_POST['clicks2'])) {
incrementClickCount2();
}
function getClickCount2() {
return (int) file_get_contents("count_files/clickcount2.txt");
}
function incrementClickCount2() {
$count2 = getClickCount2() + 1;
file_put_contents("count_files/clickcount2.txt", $count2);
}
?>
this is my html
<?php
include ('counter.php');
?>
<div class="count_right"><?php echo getClickCount1(); ?></div>
<div class="count_left"><?php echo getClickCount2(); ?></div>
<form action="counter.php" method="post" >
<button type="submit" class="vote_right" name="clicks1" ></button>
<button type="submit" class="vote_left" name="clicks2"></button>
</form>
What I'm trying or want to do is to update the counts on the divs but without refreshing the page.
I've tried using ajax but could not get the click value to show in the divs.
i thought about using text feilds insted, but dont realy know how.
This is a part of my jquery ajax code i used :
$('.vote_right, .vote_left').click(function(){
$.ajax({
url: 'counter.php',
type: 'post',
dataType:'html', //expect return data as html from server
data: $('.form1').serialize(),
});
});
I assume i made a bit of a mess, but thats why I'm here :)
EDIT
thanks guys, forgot to mention.. the code works but my problame is that its:
refreshes the page after submiting
not working when i use onSubmit="return false"
not displaying changes with e.preventDefault();
Add e.preventDefault(); to your click handler:
$('.vote_right, .vote_left').click(function(e){
e.preventDefault();
$.ajax({
url: 'counter.php',
type: 'post',
dataType:'html', //expect return data as html from server
data: $('.form1').serialize(),
});
});
You should use ajax.
Html
<?php
include ('counter.php');
?>
<div class="vote_right"><?php echo getClickCount1(); ?></div>
<div class="vote_left"><?php echo getClickCount2(); ?></div>
<form action="counter.php" method="post" >
<input type="button" class="vote_right" name="clicks1" >
<input type="button" class="vote_left" name="clicks2" >
</form>
jquery
$('.vote_right, .vote_left').click(function(){
class_count = $(this).attr("class");
count = $("."+class_count).text();
type = class_count == "vote_right" ? "right" : "left";
$.ajax({
url: 'counter.php',
type: 'post',
data: {"type": type,"count" : count},
success: function(data){
$("."+class_count).text(data);
}
});
});
In your php you will get which button it clicked by $_REQUEST["type"](left or right) and current count of this button by $_REQUEST["count"] . Add these lines at the top of your php file.
php
if(isset($_REQUEST["type"]){
if($_REQUEST["type"] == "right" )
$_POST['clicks1'] = "1";
else
$_POST['clicks2'] = "1";
}
It should done your work;
The page's link is: localhost/mysite/create-user
This is the code:
<form class="form-horizontal" name = "signUp1F" id = "signUp1F">
<input class="input-xlarge focused" name="pskil" id ="pskil" type="text" placeholder = "Doctor, Trainer, Human Resource etc.">
<input type="hidden" name="neoid" id="neoid" value="<?php echo $neoid; ?>" />
<span><button id = "plus" class="btn btn-success">Plus</button></span>
<div id="skillsAdded"></div>
</form>
The jquery code:
<script type="text/javascript">
$('#plus').click( function(event){
var pskil = $('#pskil').val();
var neoid = $('#neoid').val();
if( !pskil){
alert( "Please write a skill.");
return false;
}
$.ajax({
type: 'post',
url: "localhost/mysite/add-skill",
data: { pskil: pskil, neoid: neoid},
success: function( response){
$('#skillsAdded').append( pskil + "<br>");
return false;
}
});
});
</script>
The purpose is this: user enters a skill value to the input, clicks the Plus button, an ajax request is sent to add the skill to the database. And the code that handles this request is on localhost/mysite/add-skill.
But things go wrong. When I click the "plus" button, it goes to the page localhost/mysite/create-user?pskil=php&neoid=53. What can possibly make this direction? I've been working on this issue for almost 2 hours and I cannot manage to handle it.
The issue is that your button tag submit your form. Here is a updated JavaScript source that you can use. jQuery got a built in preventDefault() method for events. This will for an example prevent the button to submit the form.
<script type="text/javascript">
$('#plus').click( function(event){
event.preventDefault();
var pskil = $('#pskil').val();
var neoid = $('#neoid').val();
if( !pskil){
alert( "Please write a skill.");
return false;
}
$.ajax({
type: 'post',
url: "localhost/mysite/add-skill",
data: { pskil: pskil, neoid: neoid},
success: function( response){
$('#skillsAdded').append( pskil + "<br>");
return false;
}
});
});
</script>
Tryout: http://jsfiddle.net/3A7Mg/1/
I have a form like this:
one.php
<form id='myFormId' name='myFormName'>
<input type='text' name='myTextField'>
<a href='two.php'>Show Value</a>
</form>
Question:
I want to pass 'myTextField' textbox value to two.php and want to echo it on screen. I can't use submit button and also can't submit the form. Is there any trick ?
Thanks
You could start by giving the anchor an unique id:
<a id="mylink" href="two.php">Show Value</a>
and then register for the click event handler and send an AJAX request:
$(function() {
$('#mylink').click(function() {
$.ajax({
url: this.href,
data: { myTextField: $('#myFormId input[name=myTextField]').val() },
success: function(result) {
// TODO: use the resulting value
alert(result);
}
});
return false;
});
});
one.php
<form id='myFormId' name='myFormName'>
<input type='text' name='myTextField'>
<a href='two.php?value=myTextField'>Show Value</a>
</form>
two.php
echo $_GET['value'];
<form id='myFormId' name='myFormName'>
<input type='text' name='myTextField'>
<a href='two.php' id='myLink'>Show Value</a>
</form>
jQuery('#myLink').live('click',function() {
$.ajax({
url: this.href,
type: 'POST',
data: $('#myFormId').serialize(),
success: function( data ) {
// TODO: use the resulting value
alert(data);
}
});
return false;
});