So, I have a website which after selecting day loads some forms with Ajax request. In this loaded website (I just add its content to a modal), I have a button
<button class="btn btn-success" type="button" onclick="addInput()" name="add">
Dodaj kolejny przedziaĆ.
</button>
Which should call the function addInput(), which is defined in the "master" html file
<script type="text/javascript">
$(document).ready(function() {
fields = 0;
function addInput() {
alert("dodajemy");
if (fields != 24) {
document.getElementById('text').innerHTML += "test<br>";
// document.getElementById('text').innerHTML += "Poczatek: <input type='text' value='' />Koniec: <input type='text' value='' /><br />";
fields += 1;
} else {
document.getElementById('text').innerHTML += "No wiecej ci nie potrzeba<br>";
}
};
$.ajaxSetup({ cache: false, type: 'POST',
headers: { "cache-control": "no-cache" } });
$("#wybierz_pokoj").submit(function() {
var url = "/testowa/wybierz_pokoj" // the script where you handle the form input.
document.getElementById("modal").innerHTML = "Czekamy"
$.ajax({
type: "POST",
url: url,
evalJS: true,
data: $("#wybierz_pokoj").serialize(), // serializes the form's elements.
cache: false,
success: function(data)
{
document.getElementById("modal").innerHTML = data;
}
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
And after clicking the button, I'm getting "Uncaught ReferenceError: addInput is not defined" error.
What am I doing wrong?
The best solution is not to write inline JS and use jQuery the way it was intended to be used.
Remove the onclick from your HTML and bind the event with jQuery.
$(document).ready(function() {
$('button[name="add"]').on('click', function(){
addInput();
});
fields = 0;
function addInput() { // etc etc
You don't really need the function within the scope of that dom.ready either.
Demo
You've defined the function inside the document.ready call - try defining it outside like so:
<script type="text/javascript">
function addInput() {
alert("dodajemy");
if (fields != 24) {
document.getElementById('text').innerHTML += "test<br>";
// document.getElementById('text').innerHTML += "Poczatek: <input type='text' value='' />Koniec: <input type='text' value='' /><br />";
fields += 1;
} else {
document.getElementById('text').innerHTML += "No wiecej ci nie potrzeba<br>";
}
};
$(document).ready(function() {
fields = 0;
$.ajaxSetup({ cache: false, type: 'POST', headers: { "cache-control": "no-cache" } });
$("#wybierz_pokoj").submit(function() {
var url = "/testowa/wybierz_pokoj"; // the script where you handle the form input.
document.getElementById("modal").innerHTML = "Czekamy";
$.ajax({
type: "POST",
url: url,
evalJS: true,
data: $("#wybierz_pokoj").serialize(), // serializes the form's elements.
cache: false,
success: function(data)
{
document.getElementById("modal").innerHTML = data;
}
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
I'm not sure what you're doing with the "fields" variable, but if you need it ay any point, make sure it's also declared outside the document.ready function as well.
The problem is scope. The addInput function is inside the the document.ready() anonymous function, so it's not visible outside that scope. Javascript in onXXX attributes is executed in the global scope, so it can't access addInput.
The simplest solution is to move the definition of addInput outside the anonymous function, or change it to:
window.addInput = function() {
...
};
Or instead of using inline Javascript, you could use event delegation. See Event binding on dynamically created elements?
Related
I have a form that I'm trying to submit via ajax and I'm having some issues that I don't understand.
So I have the following function defined at the top of my main.js:
function formSubmit() {
var valid = true;
$(this).find('input, select, textarea').each(function(index, el) {
if(valid)
{
if($(el).is(':hidden'))
{
$(el).removeAttr('required');
}
if(!el.checkValidity())
{
valid = false;
//el.focus();
}
}
});
if (!valid)
return; // not ready to submit
var options = {
url: document.location.origin + 'update.php',
type: 'post',
dataType: 'json',
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
error: showError // post-submit callback
};
// bind form using 'ajaxForm'
$(this).ajaxSubmit(options);
};
Later in my main.js I have the following line that is run when I click a button:
$('#contact-form').formSubmit();
Also in my main.js I have:
$('body').on('change', '#contact-form', formSubmit);
In my HTML:
<form name="contact" id="contact-form">
<input type="text" name="name" value="" required>
<input type="hidden" name="page" value="contact">
</form>
When I run the $('#contact-form').formSubmit(); line, I get the error:
Uncaught TypeError: $(...).formSubmit is not a function
However, when I simply edit the name field (triggering the "on change" line) it updates and runs the function just fine.
What am I missing?
EDIT: It looks like the outcome I'm looking for is not apparent, probably because I'm not super familiar with javascript.
What I was trying to do was have a button that ran the formSubmit() function such that the $(this) element in that function was the form element.
I thought I could just run $('#contact-form').formSubmit() to do that but apparently not?
How would I go about running the formSubmit() function such that $(this) in that function refers to the element with an id of '#contact-form'?
Replace
$('#contact-form').formSubmit();
With
$('#contact-form').submit();
https://api.jquery.com/submit/
Try on submit.
$('#contact-form').submit(function(){
}
Since you are using jQuery, try something like this:
+function ($) {
$.fn.formSubmit = function() {
var valid = true;
$(this).find('input, select, textarea').each(function(index, el) {
if(valid)
{
if($(el).is(':hidden'))
{
$(el).removeAttr('required');
}
if(!el.checkValidity())
{
valid = false;
//el.focus();
}
}
});
if (!valid)
return this; // not ready to submit
var options = {
url: document.location.origin + 'update.php',
type: 'post',
dataType: 'json',
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
error: showError // post-submit callback
};
// bind form using 'ajaxForm'
$(this).ajaxSubmit(options);
return this;
}
}(jQuery);
That way, you should be able to use it like this: $("#contact-form").formSubmit();
<script>
function autocomplet1() {
var min_length = 0; // min caracters to display the autocomplete
var keyword = $('#select01').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'barcode.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#barcode01').show();
$('#barcode01').html(data);
}
});
} else {
$('#barcode01').hide();
}
}
function set_item(item2) {
$('#select01').val(item2);
var customer = $("#customer").val();
$.post("sales/add", {"data[Sales][item]": item2 ,"data[Sales][customer_phone]": customer }, function (data) {
$('#details3').html(data);
$("#select01").val('');
});
// hide proposition list
$('#barcode01').hide();
}
</script>
<script>
// autocomplet : this function will be executed every time we change the text
function autocomplet() {
var min_length = 0; // min caracters to display the autocomplete
var keyword = $('#customer').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'abc.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#country_list_id').show();
$('#country_list_id').html(data);
}
});
} else {
$('#country_list_id').hide();
}
}
function set_item(item1) {
$('#customer').val(item1);
$.post("sales/add", {"data[Sales][customer]": item1 }, function (data) {
$('#details').html(data);
});
// hide proposition list
$('#country_list_id').hide();
}
</script>
<div class="input_container">
<input type="text" id='customer' onkeyup="autocomplet()" name="data[Sales][customer]" class="input-small focused">
<ul id="country_list_id" style='height: 500px;'></ul></div></div>
<div class="content">
<div class="input_container">
<input type="text" id='select01' onkeyup="autocomplet1()" name="data[Sales][item]" class="input-small focused">
<ul id="barcode01" style='height: 500px;'></ul></div></div>
Above is an autocomplete script. Both script having same function set_time . If i changed function name as set_time1, then autocomplete is not working . How to resolve this issue? . I need to use two autocomplete in a single page.
Okay, since this is hard to explain in the tiny comments, I'll write it here.
Take that script :
function set_item(){
alert("Hello!");
}
function set_item(){
alert("Goodbye!");
}
set_item();
What do you think will happen? What will be alerted?
Answer : "Goodbye!", because the second function definition overrode the first one. You will never see the "Hello!" alert.
This is what happens when two functions have the same name. And you have two functions with the same name. Placing them in different <script> tags won't change anything, it's still the same scope.
I want to do is when a user type an email to the inputbox ajax will pass the value automatically to php.
My problem is the result only show if I try to refresh the page
html:
<input type="text" id="email" name="email" />
script:
$(document).ready(function(){
var countTimerEmailName = setInterval(
function ()
{
emailName();
}, 500);
var data = {};
data.email = $('#email').val();
function emailName(){
$.ajax({
type: "POST",
url:"Oppa/view/emailName.php",
data: data,
cache: false,
dataType:"JSON",
success: function (result) {
$("#imageLink").val(result.user_image);
$("#profileImage").attr('src', result.user_image);
$("#emailNameResult").html(result.user_lname);
$("#emailCodeResult").val(result.user_code);
}
});
};
});
You can try with:
Because you dont need declare function in ready() and you need yo get the email value after any change. Now you only get the value when the page is ready.
function emailName( email ){
$.ajax({
type: "POST",
url:"Oppa/view/emailName.php",
data: 'email=,+email,
cache: false,
dataType:"JSON",
success: function (result) {
$("#imageLink").val(result.user_image);
$("#profileImage").attr('src', result.user_image);
$("#emailNameResult").html(result.user_lname);
$("#emailCodeResult").val(result.user_code);
}
});
};
$(document).ready(function(){
$('#email').change(function(e) {
emailName( this.val());
});
});
You're handling it wrong. jQuery has particular events to do these things.
Take this for example:
$(document).ready(function(){
$(document).on('keyup', '#email', function(e) {
e.preventDefault();
val = $(this).val();
console.log("Value: " + val);
});
});
It will look what is in the below input field as the user types. (which is what I presume you're trying to do?)
<input type="text" id="email" name="email" />
Example
You could simply remove that console.log() and replace it with your ajax request. (The above example will run as the user types.)
Alternatively you could use change() like this:
$(document).ready(function(){
$(document).on('change', '#email', function(e) {
e.preventDefault();
val = $(this).val();
console.log("Value: " + val);
});
});
Which will run after the value of the text box has changed. (When the user clicks out of the text box or moves somewhere else on the page.)
Example
I am new in jquery, ajax but I want to call ajax in separate javascript function because that JSP file is dynamically created and button id in JSP file is also created using for loop.
I sharing my code and is there is a solution for this to pass button id to jquery function and pass that id to ajax calling through Jquery.
Here is code for .js file to call ajax through jquery :
function insertData(idvalue)
{
var forsplit = idvalue.id.split("_");
var qtsrl = forsplit[2];
var qtno = forsplit[3];
var queryid=idvalue.id;
var qtsrl_id = document.getElementById("qstn_srl_"+qtsrl+"_"+qtno).value;
var qstn_no_id = document.getElementById("qstn_no_"+qtsrl+"_"+qtno).value;
$.ajax(
{
type: "GET",
url: "aftermarksave.jsp",
data:{setvalues : qtsrl_id},
contentType: "application/json",
async: false,
success: function (data)
{
alert("Data passed");
},
error: function(data)
{
alert('Not passed Data: '+qtsrl_id);
}
});
}
Here I want to pass"qtsrl_id" to "aftermarksave.jsp" through Jquery:Ajax
And here is my dynamically generated .JSP file that "this" is passed to javascript function and extract current id from "this" object
fw1.write("<td><lable for='marksimilar'>"+getmarkentry+"</lable>");
fw1.write("<input type='hidden' id='markentry_"+getmarkentry+"' value="+getmarkentry+">");
fw1.write("<br>");
fw1.write("<label>Serial No</label>");
fw1.write("<br>");
fw1.write("<input type='text' size='10' id='qstn_srl_"+queserial+"_"+queno+"' onBlur='makecapital();doOnBlur(this)'>");
fw1.write("<br>");
fw1.write("<label>Question No</label>");
fw1.write("<br>");
fw1.write("<input type='text' size='10' id='qstn_no_"+queserial+"_"+queno+"' onBlur='doOnBlur(this)'>");
fw1.write("<br>");
fw1.write("<input type='button' id='btn_mark_"+queserial+"_"+queno+"' onClick=**'insertData(this)'** value='Mark'>");
fw1.write("<br>");
if(getmarkentry.equals(""))
{
fw1.write("<input type='button' id='btn_delete' onClick='mark_same()' value='UnMark' disabled='disabled'></td>");
}
else
{
fw1.write("<input type='button' id='btn_delete' onClick='mark_same()' value='UnMark'></td>");
}
fw1.write("</tr>");
fw1.write("<tr>");
In above code "insertData(this)" is called when clicked on button and I want on that click that ajax is called through jquery. how we achieve this in javascript function.
You can use something like this the following:
Put your Ajax script in a function:
function functionWithAjaxScript(qtsrl_id){
$.ajax(
{
type: "GET",
url: "aftermarksave.jsp",
data:{setvalues : qtsrl_id},
contentType: "application/json",
async: false,
success: function (data)
{
alert("Data passed");
},
error: function(data)
{
alert('Not passed Data: '+qtsrl_id);
}
});
}
trigger the function with .on() when your button is clicked:
$(function() {
$("#mybuttonid").on("click",function(){
functionWithAjaxScript(param);
});
})
I hope this helps.
I am using ajax to update the db with a new folder but it refreshes the page after ENTER is hit.
on my form I have onkeypress="if(event.keyCode==13) savefolder();"
here is the javascript code that I have: what it does basically is after you hit enter it calls the function savefolder, savefolder then sends a request through ajax to add the folder to the db. Issue is it refreshes the page... I want it to stay on the same page.
any suggestions? Thank you
<script>
function savefolder() {
var foldername= jQuery('#foldername').val(),
foldercolor= jQuery('#foldercolor').val();
// ajax request to add the folder
jQuery.ajax({
type: 'get',
url: 'addfolder.php',
data: 'foldername=' + foldername + '&foldercolor=' + foldercolor,
beforeSend: function() { alert('beforesend');},
success: function() {alert('success');}
});
return false;
}
</script>
This is working:
<form>
<input type="submit" value="Enter">
<input type="text" value="" placeholder="search">
</form>
function savefolder() {
var foldername= jQuery('#foldername').val(),
foldercolor= jQuery('#foldercolor').val();
jQuery.ajax({
type: 'get',
url: '/echo/html/',
//data: 'ajax=1&delete=' + koo,
beforeSend: function() {
//fe('#r'+koo).slideToggle("slow");
},
success: function() {
$('form').append('<p>Append after success.</p>');
}
});
return false;
}
jQuery(document).ready(function() {
$('form').submit(savefolder);
});
http://jsfiddle.net/TFRA8/
You need to check to see if you're having any errors during processing (Firebug or Chrome Console can help). As it stands, your code is not well-formed, as the $(document).ready() is never closed in the code you included in the question.
Simply stop the propagation of the event at the time of the form submission
jQuery(document).ready(function($) {
$("#whatever-form-you-are-pulling-your-values-from").submit(function(event) {
var foldername = $('#foldername').val();
var foldercolor = $('#foldercolor').val();
event.stopPropagation();
// ajax request to add the folder
$.ajax({
type: 'get',
url: '../addfolder.php',
data: 'ajax=1&delete=' + koo,
beforeSend: function() { fe('#r'+koo).slideToggle("slow"); },
success: function() { }
});
});
Since by default on a form the enter button submits the form, you need to not only handle this with your own code, but cancel the event after.
Try this code instead:
onkeypress="if(event.keyCode==13) {savefolder(); return false;}"
The onkeypress event will that the return value of the javascript and only continue with it's events if it returns true.