Autocomplete ajax is not working - javascript

<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.

Related

AJAX not sending current value of selected option

php code
<?php
if(isset($_POST['data'])) {
$file_handle = fopen('my_file.json', 'w');
fwrite($file_handle, json_encode($_POST['data']));
fclose($file_handle);
}
?>
html
<h1 id="title" class="text-lg-center text-md-center text-sm-left mb-4">test
title</h1>
<p class="lead text-lg-center text-md-center text-sm-left mb-4">test
content</p>
<button id="test" type="button" class="btn btn-lg btn-block btn-outline-
success">Publish List</button>
<div class="form-group">
<label for="exampleFormControlSelect1">Example select</label>
<select class="form-control" id="selectfont">
</select>
</div>
javascript
$(function () {
var font = 0;
var font_names = ["Montez","Lobster","Josefin Sans"];
$.each(font_names , function (index , value) {
$('<option />' , {
'value' : index,
'text' : value
})
.css({'font-family' : font_names[index]})
.appendTo("#selectfont");
});
$("#selectfont").change(function () {
var font = $(this).val();
$("p").css('font-family' , font_names[font]);
});
var htmldata = {
'content_font_type': font_names[font],
'content_font_size': parseFloat($("title").css('font-size'))
};
$("#test").click( function(){
$.ajax({
method: "POST",
url: "test.php",
data: {data: htmldata},
success: function(data) {
alert(data);
}
});
});
});
so what i want to ask is why in my_file.json the content_font_type and content_font_size not changing, but when i use alert() function in $("#selectfont").change it show correctly. Also, success always return empty when i use console.log and alert()
You have two problems:
When #selectfont changes, you're setting a local variable font, not the global variable, because you re-declare it with var font. Get rid of the var keyword.
You're setting htmldata when the page first loads. You need to set it when the user clicks on the button, so you get the updated values.
You don't really need the font variable at all. You can get the value of #selectfont when you're setting htmldata.
$("#test").click( function(){
var htmldata = {
'content_font_type': font_names[$("#selectfont").val()],
'content_font_size': parseFloat($("title").css('font-size'))
};
$.ajax({
method: "POST",
url: "test.php",
data: {data: htmldata},
success: function(data) {
alert(data);
}
});
});

Get id of parent div from clicked form submit

Okay so I have multiple forms on the page, the difference is their id, also each one has a parent box, all of which also have a different id.
The html of one of the box:
<div class="center-block" id="box2">
<form action="/login" id="form2" method="post" novalidate="novalidate">
<input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="Id" name="Id" type="hidden" value="2">
<input id="Name" name="Name" type="hidden">
<input type="submit" value="Submit">
</form>
</div>
I submit the forms with ajax, and what I want to do is find the id of the box that had its form submitted.
This is the script:
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function () {
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: $(this).serialize(),
success: function (data) {
if (data !== "0") {
window.location.href = data;
} else {
//Here I would like to alert the id of the parent box.
//Something like this:
alert($(this).closest('div').attr('id'));
//Which returns undefined
}
},
error: function () {
alert("No idea what went wrong");
}
});
return false;
});
});
</script>
Any idea how I would do that?
$(this) won't work in success callback. $(this) is relative, the scope of $(this) will be of success callback. You need to assign a variable first & then use it in success callback
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function () {
var curr_form = $(this);
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: $(this).serialize(),
success: function (data) {
if (data !== "0") {
window.location.href = data;
} else {
//Here I would like to alert the id of the parent box.
//Something like this:
curr_form.closest('div').attr('id')
//Which returns undefined
}
},
error: function () {
alert("No idea what went wrong");
}
});
return false;
});
});
</script>
Just use the JQuery parent() method:
alert($(this).parent().attr('id'));
Also, as others have pointed out, you have a different issue in that this isn't pointing to the form when you use it in the success callback. You should cache that value and then use the cache variable. You can read more about how this works in JavaScript in another post of mine.
$(document).ready(function() {
$('form').submit(function () {
// Cache the object that "this" is bound to because
// in the success function, the invocation context
// changes and "this" won't point to the same object
// it does now.
var theForm = this;
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: $(this).serialize(),
success: function (data) {
if (data !== "0") {
window.location.href = data;
} else {
//Just use the JQuery parent() method with the cached object
$(theForm).parent().attr('id')
}
},
error: function () {
alert("No idea what went wrong");
}
});
return false;
});
});

Reset the data after unchecking the checkbox

I have some results in div's ,each result has one checkbox associated with it, when a user click on single checkbox user, Current checked box's value is passed to another page using an ajax call and data is fetched and displayed in a hidden div box.
Now problem is, when user uncheck the checkbox it should remove the data associated with the checkbox.
My code is :
<div id='compare_box'>
</div>
<div class="col-md-3 photo-grid " style="float:left">
<div class="well well-sm">
<a href="final.php?id=<?php echo $id;?>&name=<?php echo $title;?>" target="_blank">
<h4><small><?php echo $title; ?></small></h4>
</a>
<br>
<input type ='checkbox' name="compare" class="compare" value="<?php echo $id;?>">add to compare
</div>
</div>
Ajax call
<script type="text/javascript">
$(document).ready(function()
{
$(".compare").change(function() {
if(this.checked) {
var check = $(this).val();
$.ajax({
type: 'POST',
url: 'compare.php',
dataType : 'JSON',
data:{value : check},
success: function(data)
{
console.log(data);
$('#compare_box').append(data);
}
});
}
});
});
Use something like this to empty the contents of the DIV
$('#compare_box').empty()
better way is to keep the reference map, something like this
$(document).ready(function() {
var boxes = {};
$(".compare").change(function() {
var check = $(this).val();
var data = $(this).closest('.box').clone();
if (this.checked) {
boxes[check] = data;
$('#comparebox').append(boxes[check]);
} else if (!this.checked && boxes[check]) {
boxes[check].remove();
delete boxes[check];
}
});
});
EDIT - should be working (not tested)
var check = $(this).val();
if (this.checked) {
$.ajax({
type: 'POST',
url: 'compare.php',
dataType: 'JSON',
data: {
value: check
},
success: function(data) {
boxes[check] = $(data);
$('#compare_box').append(boxes[check]);
}
});
} else if(!this.checked && boxes[check]) {
boxes[check].remove();
delete boxes[check];
}
DEMO

How to show php passed results to ajax without refreshing

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

onclick function doesn't work in an Ajax loaded button

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?

Categories