Count the number of inputs in a page - codeigniter

Is there a way I can count the number of inputs in a single page?
Say if the page has 5 inputs, a save button will appear- and if there is no inputs on the page, the save button will not appear. How do i do this?
i have this but i dont think this is right
<script>
var x = 0;
var ins = 0;
$(':input').each(function(){
x++;
});
ins = x;
and pass the ins variable to php like
<?php echo '<script>ins</script>';?>
but it doesnt echo anything? is the code right tho

Two line code is enough for you.If you have not any input fields the submit button will be automatically hide.
var inputs = document.querySelectorAll('input');
console.log(inputs);
alert(inputs.length);
if(inputs.length==0)
{
document.querySelector('#button').style.display = 'none';
}
<input type="text" name="name1" value="1111974167" />
<input type="text" name="name2" value="1392666449" />
<input type="text" name="name3" value="1329903177" />
<input type="text" name="name4" value="913532785" />
<button id="button">submit</button>
JS fiddle:
https://jsfiddle.net/njv5e8yc/1/

I am not sure if you actually need to have JavaScript be echoed in php since you can determine count in the first line, but you can not pass javascript to php without ajax. Here is a basic example:
/index.php
<input type="text" name="name1" value="1111974167" />
<input type="text" name="name2" value="1392666449" />
<input type="text" name="name3" value="1329903177" />
<input type="text" name="name4" value="913532785" />
<script>
$(document).ready(function() {
// Get the count of the inputs found
var x = $('input').length;
// Pass the count to php
$.ajax({
url: '/count.php',
data: {
"count": x
},
type: 'post',
// This is what happens with the ajax returns from count.php
success: function(response) {
alert(response);
}
});
});
</script>
/count.php
<?php
if(!empty($_POST['count'])) {
$count = $_POST['count'];
die('The count is: '.$count);
}
You would get an alert dialogue box that says:
The count is: 4

Related

AJAX form $('form')[0].reset(); on submit not clearing values. What am I missing?

thank you in advance for any help given. I'm just learning jQuery and AJAX and would appreciate some help with the following code. All validation rules work, the form submits and the page does not refresh. The problem is that the form values are not clearing/resetting to default after the submit has triggered. Thoughts?
**********EDITED to include HTML markup*************
<div id="form">
<h1 class="title">Contact Us</h1><!-- title ends -->
<p class="contactUs">Ask about our services and request a quote today!</p><!-- contactUs ends -->
<div id="success"><p>Your message was sent successfully. Thank you.</p></div>
<p id="required">* All fields required.</p>
<form name="form" id="contactMe" method="post" action="process.php" onSubmit="return validateForm()" enctype="multipart/form-data">
<input class="txt" type="text" maxlength="50" size="50" required name="name" value="<?php echo $_GET['name'];?>" placeholder="Name" />
<div id="nameError"><p>Your name is required.</p></div>
<input class="txt" type="text" maxlength="50" size="50" required name="email" value="<?php echo $_GET['email'];?>" placeholder="Email Address" />
<div id="emailError"><p>A valid email address is required.</p></div>
<textarea name="message" rows="6" cols="40" required placeholder="Message"></textarea>
<div id="messageError"><p>A message is required.</p></div>
<input type="hidden" maxlength="80" size="50" id="complete" name="complete" placeholder="Please Keep This Field Empty" />
<input type="submit" value="SUBMIT" name="submit" />
<input type="reset" value="RESET" name="reset" />
</form>
</div><!-- form ends -->
//hide form submit success message by default. to be shown on successfull ajax submission only.
$(document).ready(function() {
if ($('#success').is(':visible')){
$(this).hide()
}
});
//form validation
function validateForm() {
//name
var a=document.forms["form"]["name"].value;
if (a==null || a=="")
{
$('#nameError').fadeIn(250);
return false;
}
//email address
var c=document.forms["form"]["email"].value;
var atpos=c.indexOf("#");
var dotpos=c.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=c.length)
{
$('#emailError').fadeIn(250);
return false;
}
//message
var e=document.forms["form"]["message"].value;
if (e==null || e=="")
{
$('#messageError').fadeIn(250);
return false;
}
}//javascript form validation ends
//ajax submit and clear form on success
$(function () {
$('form').on('submit', function (e) {
var myForm = validateForm();
if (myForm == false){
e.preventDefault();//stop submission for safari if fields empty
}
else{
$.ajax({
type: 'post',
url: 'process.php',
data: $('form').serialize(),
success: function () {
$('#success').fadeIn(250);
if ($('#nameError, #emailError, #messageError').is(':visible')) {
$('#nameError, #emailError, #messageError').fadeOut(250);
}
$('form')[0].reset();//clear form after submit success
}//success ends
});//ajax ends
e.preventDefault();//prevent default page refresh
}//else ends
});//submit ends
});//function ends
//if reset button is clicked AND messages displayed, remove all form html messages
$(document).ready(function() {
$('#form input[type="reset"]').click(function() {
if ($('#success, #nameError, #emailError, #messageError').is(':visible')) {
$('#success, #nameError, #emailError, #messageError').fadeOut(250);
}
});
});
By giving your input id="reset" and/or name="reset", you effectively overwrote the form.reset method of the form because by doing so you made form.reset target the reset button. Simply give it a different id and name value.
Never give elements name or id attributes that equal the name of a property of a dom node.

Automate AJAXed forms with Jquery

I want to improve my website and figured out a good way to do it was by submitting forms via AJAX. But, I have so many forms that it would be inpractical to do $('#formx').submit(). I was wondering if there was a way to do this automatically by making an universal markup like;
<form class="ajax_form" meta-submit="ajax/pagename.php">
<input type="text" name="inputx" value="x_value">
<input type="text" name="inputy" value="y_value">
</form>
And have this submit to ajax/pagename.php, where it automatically includes inputx and inputy?
This would not only save me a lot of time but also a lot of lines of code to be written.
First question so I hope it's not a stupid one :)
Something like this should work for all forms. It uses jQuery - is this available in your project? This specific code chunk hasn't been tested per say, but I use this method all the time. It is a wonderful time saver. Notice I changed meta-submit to data-submit so that its value can be fetched using $('.elemenet_class').data('submit');
HTML
<!-- NOTE: All Form items must have a unique 'name' attribute -->
<form action="javascript:void(0);" class="ajax_form" data-submit="ajax/pagename.php">
<input type="text" name="inputx" value="x_value">
<input type="text" name="inputy" value="y_value">
<input type="submit" value="go" />
</form>
JavaScript
$('.ajax_form').submit(function(e){
var path = $(this).attr('data-submit'); //Path to Action
var data = $(this).serialize(); //Form Data
$.post(path, {data:data}, function(obj){
});
return false;
})
PHP
//DEBUGGING CODE
//var_dump($_POST);
//die(null);
$data = $_POST['data'];
$inputx = $data['inputx'];
$inputy = $data['inputy'];
you can create ajax fot text boxes so that it can update to database whenever change the focus from it.
<form id="ajax_form1">
<fieldset>
<input type="text" id="inputx" value="x_value" />
<input type="text" id="inputy" value="y_value" />
</fieldset>
</form>
<script>
$(document).ready(function()
{
$("form#ajax_form1").find(":input").change(function()
{
var field_name=$(this).attr("id");
var field_val=$(this).val();
var params ={ param1:field_name, param2:field_val };
$.ajax({ url: "ajax/pagename.php",
dataType: "json",
data: params,
success: setResult
});
});
});
</script>

ajax contact form Id, bugged

i have a contact form on http://daniloportal.com/NPC2/contact.html
Now this ajax script works very well, but i have other contact forms that i would like to use the same script for. so when i tried to create mulitple instances of the script, i noticed it stopped working because the ID name is not specifically ajax-contact-form. take a look at the code:
<form id="ajax-contact-form" action="">
<input type="text" name="name" value="Name *" title="Name *" />
<input type="text" name="email" value="Email " title="Email *" />
<input type="text" name="email" value="Email *" title="Email *" />
<textarea name="message" id="message" title="Message *">Message *</textarea>
<div class="clear"></div>
<input type="reset" class="btn btn_clear" value="Clear form" />
<input type="submit" class="btn btn_blue btn_send" value="Send message!" />
<div class="clear"></div>
</form>
and heres the JS
$("#ajax-contact-form").submit(function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "contact_form/contact_process.php",
data: str,
success: function(msg) {
// Message Sent - Show the 'Thank You' message and hide the form
if(msg == 'OK') {
result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
$("#fields").hide();
} else {
result = msg;
}
$('#note').html(result);
}
});
return false;
});
Now if i were to switch that ID name on both and MATCH them, the script stops working- Theoretically it should work- not sure whats wrong with this.
as always any help is appreciated, thanks!
If you are trying to access two elements with the same id with jQuery - nothing gonna happen. Each element must have a unique identifier, otherwise you should use classes.
However, can you give us the markup of another form?

Codeigniter Cart: How to add multiple items with ajax and jquery

I'm building a ajax based shopping cart with Codeigniter, and the add / remove functions work perfectly. I am now trying to add an option for adding multiple items, and can't get it to work.
Here's the markup I'm using. I'm not sure if it's the best design, but it's working with the non-ajax function, so I guess it should be fine.
<form action="cart/add_multiple" method="post" accept-charset="utf-8">
<input type="hidden" name="items[0][id]" value="3571310" />
<input type="hidden" name="items[0][qty]" value="1" />
<input type="hidden" name="items[0][price]" value="59.00" />
<input type="hidden" name="items[0][name]" value="London" />
<input type="hidden" name="items[0][heb_name]" value="לונדון" />
<input type="hidden" name="items[0][full_price]" value="59.00" />
<input type="hidden" name="items[0][discount_price]" value="59.00" />
<input type="hidden" name="items[1][id]" value="7397903" />
<input type="hidden" name="items[1][qty]" value="1" />
<input type="hidden" name="items[1][price]" value="29.00" />
<input type="hidden" name="items[1][name]" value="London Triple" />
<input type="hidden" name="items[1][heb_name]" value="לונדון טריפל" />
<input type="hidden" name="items[1][full_price]" value="29.00" />
<input type="hidden" name="items[1][discount_price]" value="29.00" />
<input type="submit" name="add_multi" value="add to cart" /></form>
The ajax script is as follows:
$(document).ready(function() {
$(document).on("submit", "div#winning_combo_small form", function () { //catches every click on the submit button of the "add to cart" form
var items = $(this).serialize();
alert(items);
$.post(base_url + "cart/add_multiple", {items: items, ajax: '1' },
function(data){
if (data =='true')
{ // Interact with returned data
$.get(base_url + "cart", function(cart){ // Get the contents of the url cart/show_cart
$("#cart_sidebar").html(cart);
})
$.get(base_url + "cart/count_items", function(items){
$("#cart_items").html(items);
})
}
});
return false;
})
});
But it's not working, because the add_multiple function receives the data as a string, not an array. Do I have to decode the data somehow to convert it to an array? Do the Hebrew characters get in the way and mess it all up?
I should say that when posting the form the regular way, without ajax, the items are added to the cart and all works well. So what is the difference between the regular post and the ajax post?
Well, I got it to work, though I'm not sure if it's the most elegant way.
Here's what I did:
In the ajax script, I changed var items = $(this).serialize(); to var items = $(this).serializeArray();. I now get an array instead of a string, but it's not the format I need to insert into the cart. So I looped over this array to create an array in the desired format, and used that new array to insert into the cart.
This is my add_multiple function under the cart controller:
function add_multiple()
{
$items = $this->input->post('items');
$ajax = $this->input->post('ajax');
// Check if user has javascript enabled
if($ajax != '1'){
$this->cart->insert($items); //if posted the regular non-ajax way, the fields will be in an array in the correct format
echo 'false';
redirect('cart'); // If javascript is not enabled, reload the page with new data
}else{
$i = 0;
foreach($items as $key=>$form_field)
{
$field_name = $form_field['name'];
$from_char = strrpos($field_name, '[') +1 ;
$length = strlen($field_name)-$from_char-1;
$field = substr($field_name,$from_char,$length);
$data[$i][$field] = $form_field['value'];
if ($field == "discount_price") $i+=1; // I know 'discount price' is always the last field
}
$this->cart->insert($data);
echo 'true'; // If javascript is enabled, return true, so the cart gets updated
}
}

ajax post no update in django template

I want to post some text in django with ajax,and save the input data,show the data in same page and no refresh,like twitter.
my js:
$('#SumbitButton').click(function(){
var data_1 = $('#data_1').val()
var data_2 = $('#data_2').val()
var data_3 = $('#data_3').val()
var data_4 = $('#data_4').val()
var user = $('#AuthorName').text()
var authorprotrait = $('#UserProprait').html()
if(data_1.length>0){
$.ajax({
type: 'POST',
url: '/post/',
data:{'data_1':data_1,'data_2':data_2,'data_3':data_3,'data_4':data_4},
async: false,
error: function(msg){alert('Fail')},
success: function(msg){
$('#TopicWrap').prepend("<div class='topic-all even'><div class='topic-left'><div class='topic-author'><div class='topic-author-protrait'>"+authorprotrait+"</div><div class='topic-author-nickname'>"+authorname+"</div></div></div><div class='topic-right'><div class='topic-meta'><span class='topic-datetime'></span></div><div class='topic-content-wrap'><div class='topic-content'>"+msg+"</div></div></div><div class='clearfix'></div></div>");
$('#data_1').val('');
$('#data_2').val('');
$('#data_3').val('');
$('#data_4').val('');
}
});
} else {
alert('The data_1's length error !'+data_1.length);
}
});
and the html:
<div id="TopicTextarea">
<div>
data1:<input tabindex="4" id="data_1" type="text" name="data1" value="" maxlength="6" placeholder=""/></br>
data2:<input tabindex="4" id="data_2" type="text" name="data2" value="" maxlength="8" placeholder=""/></br>
data3:<input tabindex="4" id="data_3" type="text" name="data3" value="" maxlength="10" placeholder=""/></br>
data4:<input tabindex="4" id="data_4" type="text" name="data4" value="" maxlength="10" placeholder=""/>
<div id="TopicFormControl">
<button type="button" id="SumbitButton" class="button orange">sumbit</button>
</div>
</div>
   <div class="clearfix"></div>
</div>
<div id="TopicWrap">
{% include 'topics.html'%}
</div>
and the views:
#login_required
def post(request):
assert(request.method=='POST' and request.is_ajax()==True)
data_1 = smart_unicode(request.POST['data_1'])
data_2 = smart_unicode(request.POST['data_2'])
data_3 = smart_unicode(request.POST['data_3'])
data_4 = smart_unicode(request.POST['data_4'])
data_obj = DataPool(user=request.user,data_1=data_1,data_2=data_2,data_3=data_3, data_4=data_4)
data_obj.save()
content = '"+data_3+"  "+data_4+" "+data_1+"("+data_2+")'
response = HttpResponse(cgi.escape(content))
return response
when I input the data and click the sumbit button,it can save the data ,but it can't show the data.what's wrong in my code?
thanks.
First, use something like Poster to test that your view is returning what you expect. Only then should you start building the AJAX part.
As for what's wrong... it's a bit difficult to say since you just write that it "can't show the data" instead of saying what it's actually doing. I suspect it has to do with this line in your view:
content = '"+data_3+"  "+data_4+" "+data_1+"("+data_2+")'
It's not really clear to me what you think this would do, but what it actually does is:
>>> '"+data_3+"  "+data_4+" "+data_1+"("+data_2+")'
'"+data_3+" \xe3\x80\x80"+data_4+"\xe3\x80\x80"+data_1+"("+data_2+")'
That is to say that it produces a string containing the substrings "data_3" (etc..) It does not include the submitted data.

Resources