I have scenario here, input and display page are generated dynamically from php code.
enter code here
<div>Aeroplane</div>
<input id="Item556" type='number' onchange="funCal('Item556', this.value, 'Aeroplane')">
<input class="disp" name="Item556" type="text" disabled>
<div>Plane</div>
<input id="Item557" type='number' onchange="funCal('Item557', this.value, 'Plane')">
<input class="disp" name="Item557" type="text" disabled>
<div>Bikes</div>
<input id="Item558" type='number' onchange="funCal('Item558', this.value, 'Bikes')">
<input class="disp" name="Item558" type="text" disabled >
<div>Cars</div>
<input id="Item559" type='number' onchange="funCal('Item559', this.value, 'Cars')">
<input class="disp" name="Item559" type="text" disabled >
Ajax is :
function funCal(ID, value, name){
var ID1 = ID; var value1 = value; var name1 = name;
$.ajax({
type:"post",
url:"calculate.php",
data: "id="+ID1+"&value="+value1,
cache: false,
dataType: 'json',
success:function(data){
<span>pound;+ data.output +</span>
//added similar to self.next().val(data.output); and tweak around it to work.
updateTotal();
}
});
};
);
function updateTotal() {
var total = 0;
$("input.disp").each(function() {
getPrices = parseFloat($(this).val().replace(/,/g, ''));
total += getPrices;
});
$("span#total").html("£" + total.toFixed(2)).digits();
}
1 . What I want to achieve is when value is entered in input box the corresponding box (with class "disp" box should display the calculated value.)
ex, the input id with Item559 should display after the ajax success value on input box with name"Item559".
Any experts advice will be valuable and much appreciated , because I am very new to ajax and php.---I got the answer for the first as Bhadra suggested below
2 . How do I add-up or sum the total value from the input.disp box? Suggestion or recommendation much appreciated Please!
Thanks in advance
function updateTotal() {
var total = 0;
$(".disp").each(function() {
var getPrices = parseFloat($(this).val().replace(/,/g, '').replace('pound;',''),10);
total += getPrices;
});
$("span#total").html("£" + total.toFixed(2)).digits();
}
Related
I have read several of the posts regarding the PHP date inserting into MySQL as 12/31/1969, but not seeing how to do that with AJAX.
My data/form flow:
- Use a datepicker to select date (Y-m-d)
- Submit form
- Passes through AJAX form in Header
- Is passed to a Processing page to INSERT into db.
*****MY AJAX FORM IN THE HEADER:*****
<script><!--BEGIN: AJAX PROCESS FORM-->
$(document).ready(function() {
$("#subformgeneral").click(function() {
// IF VISIBLE CHECKBOX IS CHECKED THEN = Y ELSE = N
if ($('#usersalevisible').is(":checked"))
{
var user_salevisible = 'Y';
} else {
var user_salevisible = 'N';
}
// END CHECKBOX CONDITIONAL
var user_title = $("#title").val();
var user_startdate = $("#startdate").val();
var user_enddate = $("#enddate").val();
var user_restrictions = $("#salerestrictions").val();
var user_numsellers = $("#numsellers").val();
var user_form = $("#formid").val();
var user_saleid = $("#saleID").val();
$.post("usr-update-sale-process-2.php",{title:user_title,startdate:user_startdate,enddate:user_enddate,salerestrictions:user_restrictions,numsellers:user_numsellers,salevisible:user_salevisible,formid:user_form,saleID:user_saleid},function(data){
$("#result").html(data);
});
});
});
</script>
My DATE INPUT field from my form:
<!-- Start Date -->
<label class="control-label" for="username">Start Date</label>
<div class="controls">
<input type="text" id="datepicker" name="startdate" placeholder="Start Date" class="input-xlarge form-control" value="12/31/1969">
</div>
<input type="hidden" value="formgeneral" id="formid">
<input name="saleID" type="hidden" id="saleID" value="3262" />
<input class="btn btn-primary" type="submit" name="subformgeneral" id="subformgeneral" value="Update General" />
I read an article from here regarding how to do StrToTime conversion, and that worked... on a regular form, but somehow it gets lost when passing through the AJAX form.
I do not have my Processing page code here, where I am at the moment, but it just receives my AJAX POST for STARTDATE, and INSERTS into MySQL.
I assume some sort of conversion has to take place on the Processing page (and I have tried, all I know to do), but not sure how, exactly.
You should handle the success error outcomes.
var user_title = $("#title").val();
var user_startdate = $("#startdate").val();
var user_enddate = $("#enddate").val();
var user_restrictions = $("#salerestrictions").val();
var user_numsellers = $("#numsellers").val();
$.ajax({
url: "usr-update-sale-process-2.php",
type: "POST",
data: {
user_title: user_title,
user_startdate: user_startdate,
user_enddate: user_enddate,
user_restrictions: user_restrictions,
user_numsellers: user_numsellers
},
cache: false,
success: function(data) {
// Success message
},
error: function(data) {
// Fail message
},
});
Things to note: data the key is what the server will look for. Example:
$_POST['user_title'] will be equal to the var user_title = $("#title").val();
Also you can return true and false from the server which will be success and error respectively.
I have here Jquery code with ajax/json. First i will discuss the flow. I have 3 textboxes, my item textbox pass it's value to auto-complete.php through ajax to get it's details. The return value is post or place into mode textbox. And if the post value is 1 or 2 the number textbox should change is css into display:none. But the problem this not working, I set the number textbox into readonly. The change function is working when I change directly the value of number textbox. Why isn't working when the value is post value?
<script>
$(document).ready(function() {
$("#number").css("display","none");
$(document).on('change','#mode',function(){
if($("#mode").val() =="1"){
$("#number").css("display","");
} else if($("#mode").val() =="2"){
$("#number").css("display","");
} else {
$("#number").css("display","none");
}
return true;
});
});
</script>
<input name="item" id="item" type="text"/>
<input name="mode" id="mode" type="text"/>
<input name="number" id="number" type="text" readonly />
<script type="text/javascript">
$(document).ready(function()
{
$('#item').change(function()
{
var item= $("#item").val();
$.ajax({
type: "POST",
url: "autocomplete-ajax.php",
data :"item="+item,
dataType:'json',
type:'POST',
success:function(data){
var mode=data.mode;
//send to element ID
$('#mode').val(mode);
}
});
return false;
});
});
</script>
When you change the value using JavaScript it won't trigger events.
A simple fix is to trigger the event yourself after you update the value.
success:function(data){
var mode=data.mode;
//send to element ID
$('#mode').val(mode).change();
/* OR */
$('#mode').val(mode).trigger('change');
}
i dont want to use serialize() function please help me with this. I am a beginner
html
<input type='button' value='Add Tier Flavor' id='Add'>
<input type='button' value='Remove Tier Flavor' id='Remove'>
<div id='batch'>
<div id="BatchDiv1">
<h4>Batch #1 :</h4>
<label>Flavor<input class="textbox" type='text' id="fl1" name="fl[]" value=""/></label></br>
<label>Filling<input class="textbox" type='text' id="fi1" name="fi[]" value="" /></label></br>
<label>Frosting<input class="textbox" type='text' id="fr1" name="fr[]" value=""/></label></br>
</div>
</div>
<br>
</div>
this is a dynamically added fields using javascript the code is:
javascript
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#Add").click(function () {
if(counter>5){
alert("Only 5 Tiers allow");
return false;
}
var newBatchBoxDiv = $(document.createElement('div')).attr("id", 'BatchDiv' + counter);
newBatchBoxDiv.html('<h4>Batch #'+ counter + ' : </h4>' +
'<label> Flavor<input type="text" name="fl[]" id="fl' + counter + '" value=""></label><br>'+
'<label> Filling<input type="text" name="fi[]" id="fi' + counter + '" value=""></label><br>'+
'<label> Frosting<input type="text" name="fr[]" id="fr' + counter + '" value=""></label><br>' );
newBatchBoxDiv.appendTo("#batch");
counter++;
});
$("#Remove").click(function () {
if(counter==1){
alert("No more tier to remove");
return false;
}
counter--;
$("#BatchDiv" + counter).remove();
});
});
</script>
i am trying to post the values in an array to post it onto next .php page
i am using this
var user_cupfl = $('input[name^="fl"]').serialize();
var user_cupfi = $('input[name^="fi"]').serialize();
var user_cupfr = $('input[name^="fr"]').serialize();
serialize is not passing the values. :(
on second page i am trying to mail it using
$message .= "<tr><td><strong>Cake Flavors(according to batches):</strong> </td><td><pre>" .implode("\n", $user_cupfl). "</pre></td></tr>";
$message .= "<tr><td><strong>Filling type (Inside the cake):</strong> </td><td><pre>" .implode("\n", $user_cupfi). "</pre></td></tr>";
$message .= "<tr><td><strong>Frosting type (top of the cake):</strong> </td><td><pre>" .implode("\n", $user_cupfr). "</pre></td></tr>";
i m posting array like this
$user_cupfl=filter_var($_POST["userCupfl"], FILTER_SANITIZE_STRING);
$user_cupfi=filter_var($_POST["userCupfi"], FILTER_SANITIZE_STRING);
$user_cupfr=filter_var($_POST["userCupfr"], FILTER_SANITIZE_STRING);
your replies will be highly appreciated
Just because you name a variable user_* doesn't mean that is what the name of the field is in the serialized POST data. You would still be looking for $_POST['fl'], $_POST['fi'] etc.
I don't understand why you think you need to serialize sets of input groups individually. You should just serialize the whole form at once.
I also see no reason why you need to have all this logic around unique id's with the counter and what not. If you are not using id's at all, just drop them altogether.
You might also consider simply using clone techniques to generate your dynamically added fields. You could greatly simplify all that javascript code by doing these things.
A more reasonable implementation may look like this.
HTML (cleaning up your code - consistent use of double quotes around properties, better strategy for class and id usage, etc.)
<div id="batch">
<div class="batchDiv">
<h4 class="batchLabel">Batch #1 :</h4>
<label>Flavor</label>
<input class="textbox" type="text" name="fl[]" value=""/>
</br>
<label>Filling</label>
<input class="textbox" type="text" name="fi[]" value="" />
</br>
<label>Frosting</label>
<input class="textbox" type="text" name="fr[]" value=""/>
</br>
</div>
</div>
Javascript:
$(document).ready(function() {
$('#Add').click(function(){
var $existingBatches = $('.batchDiv');
var count = $existingBatches.size();
if (count < 5) {
// get last batch div
var $newBatch = $existingBatches.last().clone();
// reset input values to empty string
$newBatch.find('input').val('');
// change batch label
count++;
$newBatch.find('.batchLabel').html('Batch #' + count + ' :');
// append to document
$newBatch.appendTo('#batch');
} else {
// alert or whatever
}
});
$('#Remove').click(function(){
var $existingBatches = $('.batchDiv');
var count = $existingBatches.size();
// delete last batch item if more than 1 exists
if(count > 1) {
$existingBatches.last().remove();
} else {
// alert or whatever
}
});
});
Now you haven't shown your AJAX code, but all you would need to do is something like:
var url = '/some/url';
var postData = $('[some form selector]').serialize();
var dataType = '...'; //whatever dataType you are expecting back
$.post(url, postData, function(){
// success handler
}, dataType));
Your data when then be available in PHP script at $_POST['fl'], etc.
I'm developing a site (only for fun and learn programming with jquery)
and i'd like to know what's wrong with this :
$(window).unload(function(){
var myid = $('input#v1').attr('value'); // hidden
var playauth = $('input#v2').attr('value'); // hidden
var srvid = $('input#v3').attr('value'); // hidden
var result = 'myid='+ myid +'&auth='+ playauth +'&srvid='+ srvid;
$.ajax({
type: "GET",
data: result,
url: "closing.php",
complete: function(data) {
alert(data.responseText);
}
});
});
I'm trying to update a database table. When i close the window nothing happens.
With a previous version of this function :
window.onunload = function () {
var xhReq = new XMLHttpRequest();
var n = document.getElementById("v1").InnerHTML;
var o = document.getElementById("v2").InnerHTML;
var p = document.getElementById("v3").InnerHTML;
xhReq.open("GET", ("closing.php?myid=" + n + "&auth=" + o + "&srvid=" + p) , false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
alert(serverResponse);
};
.. i saw the response alert but GET values were 'undefined'.
.... probably because the type of inputs is hidden..?
This is my form... maybe i miss something ?? I'm really new to jquery/ajax .. please help!!
<form method="get">
<input id="v1" type="hidden" name="val1" class="aget" value="<?php echo $_GET['myid']; ?>" />
<input id="v2" type="hidden" name="val2" class="bget" value="<?php echo $_GET['playauth']; ?>" />
<input id="v3" type="hidden" name="val3" class="cget" value="<?php echo $_SESSION['srvid']; ?>" />
</form>
change
var myid = $('input#v1').attr('value'); // hidden
var playauth = $('input#v2').attr('value'); // hidden
var srvid = $('input#v3').attr('value'); // hidden
to
var myid = $('input#v1').val(); // hidden
var playauth = $('input#v2').val(); // hidden
var srvid = $('input#v3').val(); // hidden
You must use
.val(); instead of .attr('value');
I will probably sound or look dumb by this but I need to learn. Check out the following part of a code:
$('.buttonclass').click(function(){
var button_id = $(this).attr('id');
$('#'+button_id).click(function(){
var yes = $("input#yes").val();
if (yes == "") {
return false;
}
var id = $("input#id").val();
if (id == "") {
return false;
}
var dataString = 'yes='+ yes + '&id=' + id;
//try insted this //alert (dataString);return false;
$.ajax({ type: "POST", dataType:'HTML',
//or the appropiate type of data you are getting back
url: "http://www.edshaer.com/EdinburgCISD/Gorena/Gorena.php", data: dataString,
//in the php file do $email = $_POST['email'];
//not a good practice but you can try with it and without it
success: function(data) {
$("#div").hide(data).fadeOut();
$("#div").html(data);
$("#div").show(data).fadeIn();
// Change the content of the message element
// Fade the element back in
} });
//ajax ends
return false; });
//click ends
});//document ready ends
My button ID that is being submitted in my html page is sending random numbers. For example
It can be:
$("#383").click(function() {
or it can be:
$("#521").click(function() {
My question is, how do I do it to auto increment the ID of the button clicked so that no matter what ID number is clicked it will still run the run the code smoothly... Right now I have this:
$('.buttonclass').click(function(){
var button_id = $(this).attr('id');
$('#'+button_id).click(function(){
Hopefully someone can help me... let me know if you need more info... Thank you in advanced...
Here is part of my HTML code... Hopefully it will be a little more understandable...
<?php
$data3 = mysql_query("SELECT * FROM `EdinburgCISDGorenamessage`
ORDER BY `ID` DESC LIMIT 0, 100")
or die(mysql_error());
echo "<div id=\"div\"> <table align=\"center\" width=\"570\">";
while($info3 = mysql_fetch_array( $data3 ))
{
$id = $info3['ID'];
}
?>
<form name="contact" id="post" method="post" action="">
<input id="id" value="<?php echo $id?>"/>
<input type="submit" class="buttonclass" id="<?php echo $id?>" name="<?php echo $id?>" value="Yes" />
<input type="submit" id="no<?php echo $id ?>" name="no<?php echo $id ?>" value=" No " /> </form>
I don' want to provide the whole code because its too messy and it doesn't go with the question... Let me know if you need anything else.
Use a class instead. Add a class to the button, and an incremental id you give it while printing it out in your html (I suppose you echo buttons in a loop?), and then just use one snippet:
$('.buttonclass').click(function(){
var button_id = $(this).attr('id');
$('#'+button_id).click(function(){
// your function here
alert(button_id); // just to see if ID is retrieved
)};
});
So, if you have
<button id="325" class="buttonclass" type="button">BUTTON 325</button>
<button id="150" class="buttonclass" type="button">BUTTON 150</button>
The ID of the button you click is retrieved only when you press it