Jquery is sending multiple requests - javascript

I'm trying to make a search bar which sends a request for proposals from the entered letter. jQuery is sending the same number of requests as the number of the entered letters.
If I write "sa" jQuery is sending 2 requests. If I write "Sa" jQuery is sending 3 Requests (the big letter is counted as 2 letters since I'm pressing shift".
The code should work like the following instructions: The user writes the name of what he wants to found and the code search in the database and shows all possible search words.
EDITS:
the script should send 2 Request: the first one to get all results which have "sa". after selecting a result. it should send only one request to the database to get the rest of the information. what my script is doing: he is sending the firs request as he should do. the second request is getting send as same time as the number of the letters. even when only one request is enough
here is also a link to a youtube video which I record to explain the problem
Here is my jQuery code:
$('.sucherInput').on('keyup', function () {
// ** .sucherInput is the class of the input field
var inputValue = $('.sucherInput').val();
var result = $(".sucherres");
var resultList = $(".sucherres ul");
if (inputValue.length) {
console.log(inputValue);
$.post("action/php/artikelSucher.php", {
name: inputValue
}).done(function(data){
// Display the returned data in browser
//console.log(data);
resultList.html(data);
result.show();
}); //.done
} else{
console.log("empty");
resultList.empty();
result.hide();
}
$(document).on("click", ".sucherres ul li p", function(){
//set the search bar value as same as the clicked <p> tag
$('.sucherInput').val($(this).text());
//clear the Proposals list
$(resultList).empty();
$(result).hide();
//renew the value of the search bar
//since im taking the value which have to be searched in the database from the searchbar
var sucherLastIndex = $('.sucherInput').val();
console.log("Getting data from database: " + sucherLastIndex);
//load the data into the HTML file
$("#updateDiv #info").load("action/php/index-preis-liste.php", {
name: sucherLastIndex
});
});
});
Here is the Html Code:
<div class="sucher">
<ul style="width: 100%; margin-bottom: 0;">
<li style="width: 33%;">
<input type="text" class="sucherInput" placeholder="Geben Sie einen Suchbegriff ein">
</li>
</ul>
<div class="sucherres">
<ul>
<!-- ## HERE COMES THE Proposals ## -->
</ul>
</div>
<div id="info">
</div>

I found the solution**
it's by changing
$(document).on("click", ".sucherres ul li p", function(){
to
$(document).off('click').on("click", ".sucherres ul li p", function(){
so simply by adding
.off('click')
**

Related

jQuery get clicked value in jinja2 loop

I have a small app with a flask backend and jinja2 templating.
In the html, I have a loop that organizes into batches creating 3 columns on the page:
{% for batch in df.iterrows() | batch(3) %}
<div class="row">
{% for row_id, row in batch %}
I have some jQuery to get the item that is clicked on in a cascading dropdown. A jinja2 loop is populating the dropdown by looping through a dataframe. The jQuery is getting the value from the html by ID (as the ul id):
<ul id="model1" class="list-group">
Ultimately I need three values, one for each batch. However, the code only returns the most recent item clicked on. The reason for that is I can't figure out how to get jQuery to get one item per batch -- or link to the batch somehow. Can I put the batch number in the ul id somehow?
$(document).ready(function(){
$('ul#menu li').hover(function(){
$(this).children('ul').delay(20).slideDown(200);
}, function(){
$(this).children('ul').delay(20).slideUp(200);
});
$('#model1 li').on("click", function(e){
e.stopPropagation();
e.preventDefault();
console.log('model1 ' + e.target.getAttribute('data-val'))
$("input[name=suggestion1]").val(e.target.getAttribute('data-val'));
});
//CODE is past here DOESN'T work but I left it in to give an idea
$('#model2 li').on("click", function(e){
e.stopPropagation();
e.preventDefault();
console.log('model2 ' + e.target.getAttribute('data-val'))
$("input[name=suggestion2]").val(e.target.getAttribute('data-val'));
});
$('#model3 li').on("click", function(e){
e.stopPropagation();
e.preventDefault();
console.log('model3 ' + e.target.getAttribute('data-val'))
$("input[name=suggestion3]").val(e.target.getAttribute('data-val'));
});
$("form").submit(function(){
var s1 = $("input[name=suggestion1]").val();
var s2 = $("input[name=suggestion2]").val();
var s3 = $("input[name=suggestion3]").val();
console.log(s1, s2, s3);
});
});
Posting this in case it helps someone else.
This excellent post explains how to use the loop variable in a flask template: count number of rows in flask templates
For my code, I made the div ID change based on the loop index.
{% for batch in recomm_df.iterrows() | batch(3) %}
<div class="row">
{% for row_id, row in batch %}
<div class="col-md-4" id="cat_{{loop.index}}">
Within that loop, I gave my unordered list an ID like :
<ul id="cat_sug" class="list-group">
Then you can grab those the data val that is clicked on in JQuery:
$('#cat_1 #cat_sug').on("click", function(e){
e.stopPropagation();
e.preventDefault();
console.log('cat_1 ' + e.target.getAttribute('data-val'))
// var s1 = e.target.getAttribute('data-val');
$("input[name=suggestion1]").val(e.target.getAttribute('data-val'));
});

Multiple Delete/Update using php- Codeigniter Ajax

The console.log(response) returns the code of whole page in console when I inspect it in ajax . I have created a codeigniter project with MySQL as back end database . I have fetched content from table from database into table. Now I want to give option to user of mulitple delete. Please take it into account that I am not actually deleting value from table I am just turning status of of that row to inactive. It goes as :
If status= 0 : the row's data will be visible in table.
If status= 1:the row's data will not be visible in table.
I have given checkbox option in the table to select multiple checkbox.
Here is my javascript:
To check all the check boxes:-
<script language="JavaScript">
function selectAll(source) {
checkboxes = document.getElementsByName('sport');
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
</script>
javascript to get value's from the checkboxes and send it to controller:
<script type="text/javascript">
function okay(){
var favorite = [];
$.each($("input[name='sport']:checked"), function(){
favorite.push($(this).val());
var txt=$(this).val();
});
for (var i = 0;i<favorite.length;i++) {
$.ajax({
url:('<?=base_url()?>/Repots/supervisor_muldel'),
type:'POST',
data:{'value_id':favorite[i]},
success:function(response)
{
console.log(response);
},
error:function(response)
{
console.log('nahi gaya');
},
});
//console.log(favorite[i]);
}
//alert("My favourite sports are: " + favorite.join(", "));
}
</script>
every check box is associate with particular values.
here the html button to call the fucntion:
<button onclick="okay();">Delete Selected</button>
Controller:Reports/supervisor_muldel:
//multiple delete supervisor
public function supervisor_muldel() {
$value_id = $this->input->post('value_id');
$selected_supervisor = array('supervisor_id' =>$value_id);
$staus=array('status'=>1);
$this->load->model('Entry_model');
$result = $this->Entry_model->supervisor_muldel($staus,$selected_supervisor);
}
Entry_model/supervisor_muldel:
//delete multiple supervisor
public function supervisor_muldel($staus,$condition)
{
$this->db->trans_start();
$this->db->where($condition)
->update('tbl_supervisor',$staus);
$this->db->trans_complete();
}
The console.log returns the code of whole page in console.I am stuck here.
You have put wrong ajax request URL.
Change
url:('<?=base_url()?>/Repots/supervisor_muldel'),
to
url:('<?=base_url()?>/Reports/supervisor_muldel'),
Look at the controller name in URL.

Angular.js - Slicing a json request according to user input

I am a beginner at Angular.js and am currently going through the tutorial. I decided to try making the number of phones displayed changeable by the user. In my controller:
function PhoneListController($http) {
var self = this;
self.orderProp = 'age';
$http.get('phones/phones.json').then(function(response) {
self.phones = response.data.slice(0, self.displayNum);
});
}
PhoneListController.$inject = ['$http']; //services to inject for each parameter in PhoneListController
I slice the response data that I get from the server according to the displayNum input by the user. I'm sure that displayNum is updated in the model, however it doesn't slice the json as I expected it to. Is the http request only made once at the start?
The relevant section of my template:
<p>
Number of phones displayed:
<input ng-model="$ctrl.displayNum" />
</p>
...
<ul class="phones">
<li ng-repeat="phone in $ctrl.phones | filter:$ctrl.query | orderBy:$ctrl.orderProp">
<span>{{phone.name}}</span>
<p>{{phone.snippet}}</p>
</li>
</ul>
<p>display num: {{$ctrl.displayNum}}</p>
The display num: {{$ctrl.displayNum}} at bottom updates according to the number input in <input ng-model="$ctrl.displayNum" />, but the list does not change size. If I hardcode a value in for self.displayNum in the controller the list is sliced correctly when I refresh the page, but changing the value in the input does nothing to the list.
As mentioned by #Alexander-Bolzhatov, I simply put the http request in a change function, called by ng-change in the template.
$http.get('phones/phones.json').then(function(response) {
self.phones = response.data;
});
self.change = function(){
$http.get('phones/phones.json').then(function(response) {
self.phones = response.data.slice(0, self.displayNum);
});
};
Template code:
Number of phones displayed:
<input ng-model="$ctrl.displayNum" ng-change="$ctrl.change()"/>

How to insert Bootstrap drop-down values in database

i am using bootstrap for making a user form.
Now i need to insert selected drop-down value in database.
But i am facing two problems.
1) When i select any item from drop-down, it jumps to top of my screen in url because of href="#". When i removed "#", it started the page refresh on selection item.
2) How i target my drop-down list to insert any selected value in database using php.
My code is
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">Select City
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li>Lahore</li>
<li>Islamabad</li>
<li>karachi</li>
</ul>
</div>
javascript code
$(document).ready(function() {
$(".dropdown-menu li a").click(function(){
$(this).parents(".dropdown").find('.btn').html($(this).text() + ' <span class="caret"></span>');
$(this).parents(".dropdown").find('.btn').val($(this).data('value'));
});
For the point 1 :
Since you have the # in the href the page scrolls up (i.e. navigating to the link target). You can prevent this event by adding event.preventDefault() in your code.
For Point 2: Since you said if you are able to get the value to your server side php code then you can proceed further you can make use of AJAX Post method. The final code would be
$(document).ready(function() {
$(".dropdown-menu li a").click(function(e){
e.preventDefault(); //this is the line which prevents the event
$(this).parents(".dropdown").find('.btn').html($(this).text() + ' <span class="caret"></span>');
$(this).parents(".dropdown").find('.btn').val($(this).data('value'));
//this is the code to post the value to server
$.post("YourPHPMethod.php",{name: $(this).text()} ,function(response){
alert("Response from server: "+response);
});
});
You have to post it to a php. I do it with ajax like this.
Look: http://www.codesheet.org/codesheet/wOHDXFju
function postContent(cv) {
$("#myDiv").html('L O A D I N G ...').show();
var url = "/post.php";
$.post(url, {id: cv} ,function(data) { //contentVar is the variable in post.php
$("#myDiv").html(data).show();
});
}

Simple quiz - how to get clicked values and send it to php

I have to write a simple quiz app. As I picked it after someone this is what I have.
There are 10 questions with 3 answers each. All question are loaded at once and only one visible. After clicking the answer next question shows up etc.
However as javascript is kinda magic to me I have no clue how to get all answers and send it to php to check if user chose correct.
The code looks something like this:
<form action="result.php">
<div class=“quiz>
<div class=“question”> Some question ?
<ul>
<li><a href=“#”>Answer A</a></li>
<li><a href=“#”>Answer B</a></li>
<li><a href=“#”>Answer C</a></li>
</ul>
</div>
[… more question here …]
<div class="question">Last question ?
<ul>
<li>Answer A</li>
<li>Answer B</li>
<li>Answer C</li>
</ul>
</div>
</div>
<input type=“hidden” name=“answers” value=“answers[]>
</form>
So basically user click on answer, next question pop up and at the end I need to populate all answer and send it to result.php where somehow I would get results within array with chosen answers like {1,3,2,1,2,3,1,2,3,1} or something like that.
There are many ways to accomplish this. Here's an easy one:
add a
<input type="hidden" name="questions[]" value="" />
inside each .question DIV
update the value of this input when one of the links are clicked:
$('.question a').on('click', function(){
var answer = $(this).text();
$(this).parents('.question').find('input').val(answer);
});
put a request method on your form, let's say POST
Then in your PHP script you'll get a numerically indexed array with the selected answer for each question, $_POST['questions'].
I do not know how your design looks like, but it may be possible to achieve this without any javascript, using hidden radio inputs and labels (I'm assuming here you're using links because of styling limitations on input fields).
Normally, you would create an HTTP request to your verification back-end. jQuery, for one, makes this quite easy. Also, I would try to generate the questions HTML, so that you're ready to generate quizzes with other sets of questions without having to re-type your html.
I'm trying to create a quizz-like app myself, currently, and would be glad to hear your feedback. A brief snipped of what I mean is on this fiddle: http://jsfiddle.net/xtofl/2SMPd/
Basically something like:
function verify(answers) {
jQuery.ajax("http://yoursite/verify.php?answers="+answers,
{ async: true,
complete: function(response, status){
// e.g.
alert(response.text);
}
};
};
This request would be sent when all answers are completed. I would try to create the questions on-the-fly using javascript and the DOM, something like:
function retrieveQuestions() {
//TODO: get them from a json-request like http://yourquizz/quizz1/questions
return [{ text: "what if Zoo went to Blohom in a Flurk?",
options: { a: "he frunts and vloghses",
b: "the Blohom doesn't snorf anymore" }
},
{ text: "how many this and that",
options: { a: "1", b: "2", c: "14" }
}
];
};
// retrieve and create the questions elements
var questions = retrieveQuestions();
questions.forEach(function(question, index){
jQuery("#questions").append(createQuestionElement(question));
});
// what does a question element look like:
function createQuestionElement(question){
var li=document.createElement("li");
var options = [];
Object.keys(question.options).forEach(function(key){
var o = document.createElement("div");
jQuery(o).on('click', function(){question.answer=jQuery(o).val();});
li.appendChild(o);
});
return li;
}
Your php backend verify.php script will check the arguments and return the result in json format, e.g.:
$correct = ($answers[ $_GET["question"] ] == $_GET["answer"]);
print("{ 'correct': '$correct' }");
(provided your answers are stored in an array $answers.
Yet another solution to the problem:
jsFiddle
We use event handlers, to check if an answer was clicked, then add the index of the answer to an array. When the last answer was submitted, we send the data to a php page, where you can process it using the $_POST array.
$('.question a').on('click', function (e) {
e.preventDefault();
var self = $(this);
var ans = self.parent().index() + 1;
answers.push(ans);
var hasNext = nextQuestion();
if (!hasNext) {
$.ajax({
type: "POST",
url: "/echo/json/",
data: {
"answers": answers
}
}).done(function (response) {
response = 'Stuff you output with PHP';
$('body').append('<p> Result: ' + response + '</p>');
});
}
});

Categories