How to automatically run a jQuery script, without having to click submit? - php

I am currently working on an online store. I have succeeded in coding a script that calculates a product's price and shows this price on the product page when the user clicks on an 'update price' button. Is there a way of doing this without a submit button? In other words: is there a way to make the price show and update automatically?
(I have not included my .php file because it uses data from a database.)
Any help would be greatly appreciated!
<form action="/" id="updatePrice">
<h3>Size</h3>
<select class="form-control" id="sizejquery" name="size">
<option>A0</option>
<option>A1</option>
<option>A2</option>
</select>
<h3>Type of paper</h3>
<select class="form-control" id="paperjquery" name="paper">
<option>white coated paper</option>
<option>photo paper</option>
</select>
<h3>Quantity</h3>
<select class="form-control" id="quantityjquery" name="quantity">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<br>
<input class="btn btn-default" type="submit" value="update price">
</form>
<div id="price">
<h3>$0.00</h3>
</div>
<script>
// Attach a submit handler to the form
$("#updatePrice").submit(function(event) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $(this),
size = $form.find("#sizejquery").val(),
paper = $form.find("#paperjquery").val(),
quantity = $form.find("#quantityjquery").val(),
url = $form.attr("action");
// Send the data using post
var posting = $.post(url, {
size: size,
paper: paper,
quantity: quantity
});
// Put the results in a div
posting.done(function(data) {
var content = $(data).find("#content");
$("#price").empty().append(content);
});
});
</script>

You can register the blur() event on Quantity drop down ad then pus the results.
I have modified the script. Please see if it works for your implementation.
<script>
$(document).ready(function(){
$("#quantityjquery").blur(function(){
// Get some values from elements on the page:
var size = $("#sizejquery").val();
var paper = $("#paperjquery").val();
var quantity = $("#quantityjquery").val();
var url=$("#updatePrice").attr("action");
// Send the data using post
var posting = $.post(url, {
size: size,
paper: paper,
quantity: quantity
});
// Put the results in a div
posting.done(function(data) {
var content = $(data).find("#content");
$("#price").empty().append(content);
});
});
});
</script>

Right, so, try the following:
$(function() {
$formBtn = $("#updatePrice").find("input.btn-default");
$formBtn.on("click", function(event) {
//all your code (the one you already have) here....
});
$(window).on("load", function() {
$formBtn.trigger("click");
});
$("#updatePrice").on("change", ".form-control", function() {
$formBtn.trigger("click");
});
});
Full code:
$(function() {
$formBtn = $("#updatePrice").find("input.btn-default");
$formBtn.on("click", function(event) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $("#updatePrice"),
size = $form.find("#sizejquery").val(),
paper = $form.find("#paperjquery").val(),
quantity = $form.find("#quantityjquery")
.val(),
url = $form.attr("action");
// Send the data using post
var posting = $.post(url, {
size: size,
paper: paper,
quantity: quantity
});
// Put the results in a div
posting.done(function(data) {
var content = $(data).find(
"#content");
$("#price").empty().append(
content);
});
});
$(window).on("load", function() {
$formBtn.trigger("click");
});
$("#updatePrice").on("change", ".form-control", function() {
$formBtn.trigger("click");
});
});

Call that method at document ready api in jquery as
$(document).ready(function(){
// your logic
});
In terms of your code
function fetchPrice(){
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $(this),
size = $form.find("#sizejquery").val(),
paper = $form.find("#paperjquery").val(),
quantity = $form.find("#quantityjquery").val(),
url = $form.attr("action");
// Send the data using post
var posting = $.post(url, {
size: size,
paper: paper,
quantity: quantity
});
// Put the results in a div
posting.done(function(data) {
var content = $(data).find("#content");
$("#price").empty().append(content);
});
}
$(document).ready(function(){
fetchPrice(); // calls as the page load complete
});
Hope it helps ..........

Related

Grabbing div content and sending to php email

New here and glad to be, I've gotten a lot of answers from this forum. I am however stuck at the moment.
I have some javascript that is creating a window color and handle picker (click on the color swatch it changes the image, click on a handle and it does the same). Below the image is a description of the window selected. This text is being generated by the javascript by pulling the image titles.
Now the fun part. Below this picker I need to add a form that will be emailed using php. Within that email I need to pull the window description that is being generated by the javascript.
I have tried so many things today I have lost count. The last bit of code I tried was
<script>
$(document).ready(function() {
$("windowDesc").each(function() {
var html = jQuery(this).html();
});
});
</script>
And in the php mail file I added:
$windowtitle = $_GET['html'];
as well as trying
$windowtitle = $_POST['html'];
and I have also tried the following:
<script>
var content = $('#windowDesc').html();
$.ajax({
url: 'send_mail.php',
type: 'POST',
data: {
content: content
}
});
</script>
And in the php mail file I added:
$windowtitle = $_GET['content'];
as well as trying
$windowtitle = $_POST['content'];
Not to mention a plethora of other things.
Basically what I am trying to do is grab the content of the div that holds the generated text and email it. If any of the above are correct then I must be placing them in the wrong position or something. With the first one I have tried it inside the form, outside the form, before the div, after the div. Just haven't tried it on top of my head yet. It's been a long day, thanks in advance :o)
Sorry for the delay, been a busy two days. OK, so here is the code that handles the window color and handle picker:
var Color = "color";
var Handle = "handledescription";
var ColorDesc = "color";
var HandleDesc = "handle description"
function Window(Color,Handle,ColorDesc,HandleDesc) {
$('#windowPic').animate({opacity: 0}, 250, function () {
thePicSrc = "http://www.site.com/images/windows/" + Color + Handle + ".jpg";
$('#windowPic').attr('src', thePicSrc);
$('#windowDesc').html("<p>" + ColorDesc + " frame with " + HandleDesc + " hardware</p>");
$('#windowPic').animate({opacity: 1}, 250)
})
}
$(document).ready(function() {
$('#wColors li').click( function() {
Color = $(this).attr('id');
ColorDesc = $(this).attr('title');
Window(Color,Handle,ColorDesc,HandleDesc);
});
$('#wHandles li').click( function() {
Handle = $(this).attr('id');
HandleDesc = $(this).attr('title');
Window(Color,Handle,ColorDesc,HandleDesc);
});
});
You need a hidden input in your form:
<form id="send_email" action="send_email.php">
<input id="content" type="hidden" name="content"/>
... other inputs here
</form>
Then you can use Javascript to fill it in before submission:
$("#send_email").submit(function() {
$("#content").val($("#windowDesc").html());
}
<script>
var content = $('#windowDesc').html();
$.ajax({
url: 'send_mail.php',
type: 'POST',
data: content
});
</script>
It worked here.

localize dynamic drop down from database using jquery

This is the language select box.
<select name="lang" id="lang" browser="Indicated by the browser">
<option value="en">English</option>
<option value="fr">French</option>
<option value="ch">Chinese</option>
<option value="sp">Spain</option>`enter code here`
</select>
This is script i have written.
<script type="text/javascript">
jQuery(document).ready(function() {
loadBundles('en');
jQuery('#lang').change(function() {
var selection = jQuery('#lang option:selected').val();
loadBundles(selection != 'browser' ? selection : null);
jQuery('#langBrowser').empty();
if(selection == 'browser') { jQuery('#langBrowser').text('('+jQuery.i18n.browserLang()+')');
}
});
});
function loadBundles(lang) {
jQuery.i18n.properties({
name:'Messages',
path:'bundle/',
mode:'both',
language:lang,
callback: function() {
updateExamples();
}
});
}
function updateExamples() {
var ex1 = 'Firstname';
var ex2 = 'Lastname';
var ex3 = 'Youremail';
var ex4 = 'Reenteremail';
var ex5 = 'Newpassword';
var ex6 = 'Dateofbirth';
var ex7 = 'Signup';
var ex8 = 'Itsfreeandalwayswillbe';
var ex9 = 'Birthlabel';
var ex10 = 'Termslabel';
var ex11 = 'Summarylabel';
var ex12 = 'PersonalLabel';
var ex13 = 'Interestlabel';
var ex14 = 'Addlabel';
var ex15 = 'Editlabel';
var ex16 = 'Deletelabel';
var spreadsheet_label = 'Spreadsheetlabel';
var invite_google_label = 'Invitegooglelabel';
var invite_facebook_label = 'Invitefacebooklabel';
var upload_label = 'Uploadlabel';
var subBut='Submit';
var dialogTitle = 'DTitle';
jQuery("#first_name_label").text(eval(ex1));
jQuery("#first_name_label1").text(eval(ex1));
jQuery("#last_name_label").text(eval(ex2));
jQuery("#last_name_label1").text(eval(ex2));
jQuery("#email_label").text(eval(ex3));
jQuery("#email_label1").text(eval(ex3));
jQuery("#reenter_email_label").text(eval(ex4));
jQuery("#new_password_label").text(eval(ex5));
jQuery("#date_of_birth_label").text(eval(ex6));
jQuery("#date_of_birth_label1").text(eval(ex6));
jQuery("#sign_up").text(eval(ex7));
jQuery("#label1").text(eval(ex8));
jQuery("#button").val(eval(ex7));
jQuery("#birth_label").text(eval(ex9));
jQuery("#terms_label").text(eval(ex10));
jQuery("#summary_label").text(eval(ex11));
jQuery("#personal_label").text(eval(ex12));
jQuery("#interest_label").text(eval(ex13));
jQuery("#add_label").text(eval(ex14));
jQuery("#edit_label").text(eval(ex15));
jQuery("#delete_label").text(eval(ex16));
jQuery("#spreadsheet_label").text(eval(spreadsheet_label));
jQuery("#invite_google_label").text(eval(invite_google_label));
jQuery("#invite_facebook_label").text(eval(invite_facebook_label));
jQuery("#upload_label").val(eval(upload_label));
jQuery("#submit_button").val(eval(subBut));
jQuery("#ui-dialog-title-dialog").text(eval(dialogTitle));
}
</script>
Everything is working fine for the labels. But in the case of dynamic drop down i got problem. How to localize the dynamic drop down data when the user selected the language.
The data in the drop down is coming from the database.
I have a language select drop down box, after selecting one language from dropdown list am able to change the text filed names and all other text in the language that is selected.
At the same time i have another dropdown, in that data is generated dynamically form the database. After the user selecting the language from dropdown list i have to change the data in this drop down list also. please suggest me if u have any idea.
Thank you.
I suggest you to use ajax for this issue.
You can bind ajax to first drop down and then fill secound dropdown by data which you get from back-end.
You can do something like this :
<select name='lang'>
<option value='eng'>Eng</option>
<option value='french'>French</option>
</select>
<!-- below div is another div whose data changes as per the language selected -->
<div id="another_div"></div>​
JS:
$("select[name='lang']").live({
change: function(e){
var selected_lang = $("select[name='lang'] option:selected").html();
data = {}
data['selected_lang'] = selected_lang;
$.ajax({
url: "required url",
data: data,
success: function(res){
$("#another_div").text(res); // if result is a direct text sent from server
// or
$("#another_div").text(res.content); //if result is an object with the required content present in the key 'content'
},
error: function(err){
alert("error occured");
}
});
}
});​
I would use one of the many Cascading jQuery Dropdowns:
http://www.ryanmwright.com/2010/10/13/cascading-drop-down-in-jquery/

pass <input type="file"> to other form after submit

I have an upload form that submits using ajax.
This all works fine but what i want to do is have the name of the file i was uploading stored in a hidden input type so when i submit my form with text fields,the name of the image can be submitted to the database.
I have noticed that when i submit my main form to database, the name of the image has been lost. I have just realised the input file is on the upload form so that's why the name won't have been submitted.
My question is how do i pass the name of the uploaded file to my other form?
In my main form i presume i would have a
<input type="hidden" name="imgname" id="imgname" value="" />
Here is my jquery that submits the form
<script type="text/javascript">
$(document).ready(function() {
//elements
var progressbox = $('#progressbox');
var progressbar = $('#progressbar');
var statustxt = $('#statustxt');
var submitbutton = $("#SubmitButton");
var myform = $("#UploadForm");
var output = $("#output");
var lotterydiv = $("#lottovidpreview");
var completed = '0%';
$(myform).ajaxForm({
beforeSend: function() { //brfore sending form
lotterydiv.remove();
submitbutton.attr('disabled', ''); // disable upload button
statustxt.empty();
progressbox.slideDown(); //show progressbar
progressbar.width(completed); //initial value 0% of progressbar
statustxt.html(completed); //set status text
statustxt.css('color','#000'); //initial color of status text
},
uploadProgress: function(event, position, total, percentComplete) { //on progress
progressbar.width(percentComplete + '%') //update progressbar percent complete
statustxt.html(percentComplete + '%'); //update status text
if(percentComplete>50) {
statustxt.css('color','#fff'); //change status text to white after 50%
}
},
complete: function(response) { // on complete
output.html(response.responseText); //update element with received data
myform.resetForm(); // reset form
submitbutton.removeAttr('disabled'); //enable submit button
progressbox.slideUp(); // hide progressbar
}
});
});
</script>
I am also presuming I need to do something in the complete: function part but don't know what. Would i need to get the name of the file that was sent to the php script to move the image or can i grab it from the client side?
I just had to enter this in the complete: function
$("#imagename").val($("#filepc").val());

Ajax call not working on enter keypress, works only for click function

I have a ajax method of calling data from php file, i learned it from one of a blog, now it works file for submit button click function, but when i press enter the variables get shown in address bar and ajax process is not executed, Can any one please help me doing it on a press enter method....
This is my code:-
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("input[name='search_user_submit']").click(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = { "cv" : cv, "cvtwo" : cvtwo }; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "../elements/search-user.php";
$.post(url, data, function(data) {
$("#SearchResult").html(data).show();
});
});
});
});//]]>
</script>
I have tried it by taking an if condition along with keypress event still its not working:-
if (e.keyCode == 13) { // Do stuff }
else { // My above code }
//In this also it seems that i am doing something wrong.
Can anybody please enlighten me oh how to do it.
My input field is:-
<input type="text" name="searchuser_text" id="newInput" maxlength="255" class="inputbox MarginTop10">
My submit button is:-
<input class="Button" name="search_user_submit" type="button" value="Search">
You can try with event.preventDefault(); for enter keypress.
Thanks.
When you type enter there is executed default onSubmit handler for a form. You can use submit jquery function to handle both enter and click on submit button.
$("form").submit(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = { "cv" : cv, "cvtwo" : cvtwo }; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "../elements/search-user.php";
$.post(url, data, function(data) {
$("#SearchResult").html(data).show();
});
return false;
});
return false in this function will prevent submit of the form.

jquery/ ajax callback doesn't fire twice without a page reload. Part 1

I'm learning how to apply ajax to my jquery/php/mysql script for the purpose of callback firing. This question is probably from my ignorance when it come to the name of this term.
The Question: Is there a way to reset ajax callback without reloading the page script.
The Goal: I have a mysql query displaying on jQuery Accordian 1, 2, and 3. The goal is to click a query result href from Accordian and display the results in jQuery UI Tab 3 without a page reload...So far the script fires on my first callback but it doesn't fire a second time. Is there a term or jquery command that will reset jquery/ajax?
index.php
<?php
...script... include'right.content.php';
?>
<script type="text/javascript" >
$(function() {
$("#submit").click(function(){ // when submitted
var name = $('#string2').val();
var lname = $('#string3').val(); // // POST name to php
$('#stage').load('test.arena/test.php', {'string2':name, 'string3':lname,} );
});
$( "#tabs" ).tabs().find( ".ui-tabs-nav" );
$( "#accordion" ).accordion();
});
</script>
index.php - html section
<div id="stage">
<?php include'test.arena/test.php';?>
</div>
right.content.php
while ($row = mysql_fetch_array($result)){
if($row['stats'] == "1"){
$data .= "<tr><td colspan='2'>".$row['order_number']."</td>
<td colspan='2'>
<input type='hidden' id='string3' value='".$row['details']."'>
<input type='hidden' id='string2' value='".$row['order_number']."'>
<input type='button' id='submit' value='View'></td>
<td>info</td></tr>";
test.arena/test.php
if(!isset($_POST['string2'])){
$_POST['string2'] = "";
}else{
$string3 = "PO Number:" .$_POST['string3'];
$string2 = "Order:" .$_POST['string2'];
echo $string3 ."</br>";
echo $string2 ."</br>";
}
Is the element with ID 'submit' inside the one with ID 'stage'? If so, try changing $("#submit").click(function(){ to $("#submit").live('click', function(){.
The problem is probably because your submit button is inside of the 'stage' div. This means that when you load the new 'stage' content, it will delete the old button and add a new one and the new one won't have any click thing attached.
The quick fix for this is to use a 'live' handler.
$(function() {
$("#submit").live('click', function(){ // when submitted
var name = $('#string2').val();
var lname = $('#string3').val(); // // POST name to php
$('#stage').load('test.arena/test.php', {'string2':name, 'string3':lname,} );
});
$( "#tabs" ).tabs().find( ".ui-tabs-nav" );
$( "#accordion" ).accordion();
});
But the other solution, which might make the problem clearer, is to re-add the click handler after the load finishes.
$(function() {
function submitClicked() {
var name = $('#string2').val();
var lname = $('#string3').val(); // // POST name to php
$('#stage').load(
'test.arena/test.php',
{ 'string2':name, 'string3':lname },
function() {
addClickHandler();
}
); // display results from test.php into #stage
}
function addClickHandler() {
$('#submit').click(submitClicked);
}
addClickHandler();
$( "#tabs" ).tabs().find( ".ui-tabs-nav" );
$( "#accordion" ).accordion();
});

Categories