all I want to do is make a call by using "idx".
something like this.. alerts/1 alerts/2 alerts/3.....
{{#alerts}}
<tr name = "alerts">
<input name = "idx" style="display : None" value="{{id}}">
<td><input type="submit" value="start alert" name="alert-start"/></td>
<td>ticker : {{ticker}}</td>
<td>price : {{price}}</td>
</tr>
{{/alerts}}
So I made a Jquery
$('input[name=alert-start]').on('click', function() {
_this.alertStart();
});
},
alertStart : function() {
var idx = $('input[name=idx]').val();
$.ajax({
type: 'GET',
url: '/alerts/'+idx,
}).done(function() {
alert('start alert');
}).fail(function (error) {
alert(JSON.stringify(error));
});
},
But... with this code, I can only call "alerts/1". No matter how many alerts are there...
What can I do?? Please someone help.. I'm really struggling with this..
Look into followings
<input name = "idx" type="hidden" value="{{id}}"> is the correct way of hiding any imput from appearing on page
$('input[name="idx"]').val(); is correct way to read the idx value
rest seems to be fine look for any error in console
What you could do is pass the input you click on to the alertStart function. Then use the object to find the input[name=idx] related to the clicked input.
$('input[name=alert-start]').on('click', function() {
_this.alertStart(this);
});
alertStart: function(obj) {
var idx = $(obj).closest("tr").find('input[name=idx]').val();
$.ajax({
type: 'GET',
url: '/alerts/' + idx,
}).done(function() {
alert('start alert');
}).fail(function(error) {
alert(JSON.stringify(error));
});
}
Related
I have a form with text fields which the user can "Add New" by clicking a button. These fields share the same name. I'm trying pass the values into Google Spreadsheets, but the values all come through as 'undefined' with the following code, even though console.log prints the answers as strings which look okay to me.
So if the user for example submits 3 separate entries for SUNDAY_NOTES[], all 3 strings should end up in one cell broken up by new lines, but instead I'm just getting "undefined".
<form action="" method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]"> // the user can create multiples of these ^ for each day of the week
<input type="submit" id="submit" />
</form>
<script>
$(document).ready(function() {
var $form = $('form#timesheet'),
url = 'https://script.google.com/macros/s/AKf45XRaA/exec'
$('#submit').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeArray().map((e) => {
return e.value
}).join('\n')
});
})
});
</script>
Your code works. In the snippet below I am storing the data split by \n in a variable and logging it. You can check the output.
Although your JS is correct, I suspect that you actually want to be using a different HTTP method. Perhaps POST or PUT? I can't be specific as you have not said which API endpoint you are using.
$(document).ready(function() {
var $form = $('form#timesheet'),
url = 'https://script.google.com/macros/s/AKf45XRaA/exec'
$('#submit').on('click', function(e) {
e.preventDefault();
var data = $form.serializeArray().map((e) => {
return e.value
}).join('\n');
console.log(data);
var jqxhr = $.ajax({
url: url,
method: "POST",
dataType: "json",
data: data
}).done(response => {
console.log(response);
}).fail((jqXHR, textStatus) => {
console.log("Request failed: " + textStatus);
});
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="submit" id="submit" />
</form>
remove the [] from your input's name as this is needed if you want to receive an array in the server side, then create a function that groups the values according to the inouts' keys :
function group(arr) {
var tempArr = [];
arr.forEach(function(e) {
var tempObj = tempArr.find(function(a) { return a.name == e.name });
if (!tempObj)
tempArr.push(e)
else
tempArr[tempArr.indexOf(tempObj)].value += ', ' + e.value;
});
return tempArr;
}
and use it like :
$('#submit').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: group($form.serializeArray()),
//... rest of your code
this will keep the original structure that works,
here's a snippet :
var $form = $('form#timesheet');
function group(arr) {
var tempArr = [];
arr.forEach(function(e) {
var tempObj = tempArr.find(function(a) { return a.name == e.name });
if (!tempObj)
tempArr.push(e)
else
tempArr[tempArr.indexOf(tempObj)].value += ', ' + e.value;
});
return tempArr;
}
$form.submit(function(e) {
e.preventDefault();
var grouped = group($form.serializeArray());
console.log(JSON.stringify(grouped))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES"><br />
<input type="text" name="SUNDAY_NOTES"> // user can click a button to keep adding more SUNDAY_NOTES fields
<input type="text" name="MONDAY_NOTES"> // and so forth
<input type="submit" id="submit" />
</form>
I am trying to make search button:
<input type="text" name="searchme" id="searchme" onkeydown="searchme()" />
<input type="button" value="SearchMe" />
I want to get all data from table if textbox is empty else myFunction() will be execute and search.
<script>
function searchme() {
var searchvalue;
searchvalue = document.getElementById('search_id').value;
alert(searchvalue);
$.ajax({
type: "GET",
url: "get_projectList.php",
data: {searchvalue: value }
})
}
</script>
is there any problem with script? What should I add?
Your code is looks fine to me. You just need to add success for fetching results.
HTML
<input type="text" name="searchme" id="searchme" onkeyup="searchme()" />
Change onkeydown to onkeyup. because on key the you are not able to get the value.
include jQuery in <head> of your html
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
now JS
function searchme() {
var searchvalue;
searchvalue = $('#searchme').val();
alert(searchvalue);
var table = "table_name";
$.ajax({
type: "GET",
url: "get_projectList.php",
data: {searchvalue: searchvalue, revanue: table},
success: function (result)
{
$(".resultDiv").html(result);
}
})
}
Where .resultDiv is the div where you want to show the result. and remove ' from searchvalue and revanue.
I would do it like this. Since you're using jquery. Might as well use it everywhere.
<input type="text" name="searchme" id="searchme" />
Then your JS
$('#searchme').keyup(function(){
var search = $(this).val();
$.ajax({
type: "GET",
url: "get_projectList.php",
data: {searchvalue: search},
success: function (data)
{
$(".results").html(data);
}
})
});
But also...you probably dont want your script firing on every keystroke. Instead you should wait a fraction of a second between strokes, to only fire the request when the user is actually done typing.
So like this...
// The delay function
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$('#searchme').keyup(function() {
var search = $(this).val();
delay(function(){
$.ajax({
type: "GET",
url: "get_projectList.php",
data: {searchvalue: search},
success: function (data)
{
$(".results").html(data);
}
})
}, 800 );
});
EXAMPLE HERE
I have select2 ComboBox the data is loaded by Ajax. I am trying to set the default value to the select2 by reading the id from the input value (which is set on the server side) and set it to the select2 programmatically.
I think I should implement the initSelection() function in a way to solve this issue.
Here is my code:
The HTML input is:
<input type="hidden" class="mySelect2" value="01" name="someName" />
The value "01" is set at the server
The JavaScript is:
$(".mySelect2").select2({
ajax: {
url:"data.php",
dataType:"json",
data:function(term, page) {
return {
query:term, page: page -1
} ;
},
results:function(data, page) {
return data
}
}
});
I tried this but it did not work .
$(".mySelect2").select2('val', '01');
And an error occured : "cannot call val() if initSelection() is not defined "
try something like this
$(function(){
$(".mySelect2").select2({
ajax: {
url:"data.php",
dataType:"json",
data:function(term, page) {
return {
query:term, page: page -1
} ;
},
results:function(data, page) {
return data
},
}
});
$(".mySelect2").select2('data', {id:'01',text:'01'});
})
HTML CODE
<input type="hidden" class="mySelect2" style="width:100px;" value="[{id:'01',text:'01'}]" name="someName" />
The general premise of initialising a default value in a select2 control using ajax can be solved using something like:
initSelection: function (element, callback) {
var id = $(element).val();
if (id !== "") {
$.ajax("data.php", {
data: {
id: id // return a single item from your service
},
dataType: "json"
}).done(function (data) {
var results = [];
$.each(data, function (index, item) {
results.push({
id: item.Id, // whatever your id field is
text: item.TextValue // whatever your text field is
});
});
callback(results[0]);
});
}
}
I'm not a PHP person, but this should be standard across ajax requests. The approach basically assumes you can return a single result as well as the list.
I've edited this question from the original OP to better represent my issue.
How can I pass the variable data-uid with AJAX ?
Right now the variable doesnt get passed.
var uid = $(this).data("uid"); doesn't work = undefined
var uid = '199'; gets passed. works.
is it possible to have something like : var uid = $uid; ?
HTML
<form>
<fieldset>
<textarea id="post_form" type="text" data-uid="<?php echo $uid ?>"/></textarea>
<button type="submit" id="add" value="Update" name="submit" />OK</button>
</fieldset>
</form>
JS
$(function() {
$("#add").click(function() {
var boxval = $("#post_form").val();
var uid = $(this).data("uid"); // this needs to be changed
var dataString = 'post_form=' + boxval + '&uid=' + uid;
if (boxval == '') {
return false;
} else {
$.ajax({
type: "POST",
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
}
});
return false;
});
});
problem in your code in:
var uid = $(this).data("uid");
you're trying to wrap this into jquery object, but it is button object in this context, then you're trying to obtain something unassigned from it
you shoud use:
var uid = $('#post_form').attr('data-uid');
or, you can add <input type="hidden" name=... value=... and get id from it, this is more general way
Looks like your issue is with the data attribute that should be data-uid="somevalue" Like.
Check this fiddle to see if this solves your main problem
I'm trying to use the typeahead script for Bootstrap. It's working great, but I'd like it to be a bit more dynamic. I'd like to run several auto-complete inputs on the same page without duplicating code.
HTML:
<input type="text" class="typeahead" name="person_name" id="person-search">
<input type="text" class="typeahead" name="city_name" id="city-search">
Basic jQuery:
$('.typeahead').typeahead({
source: function(typeahead, query) {
return $.ajax({
url: '/ajax_lookup_script.php'
+ '?source=' + ###[HOW CAN I PUT ELEMENT ID HERE?]###
+ '&q=' + query,
success: function(data) {
return typeahead.process(data);
}
});
},
property: 'name'
});
The above doesn't work (obviously). But if I set the class name to .typeahead-person-search and then create a new typeahead function that manually adds the source person-search, and another function entirely for .typeahead-city-search, then everything works fine. I'd like to avoid having two functions when it's really just a variable that separates the two.
How can I put the element ID of the active .typeahead class into the $.ajax function?
Ok, I've gone up on something else, I couldn't test it directly with the .typeahead librairy, but I've done the same thing with another librairy I amusing.
How bout doing
$('.typeahead').each(function(){
var self = $(this);
self.typeahead({
source: function(typeahead, query) {
return $.ajax({
url: '/ajax_lookup_script.php'
+ '?source=' + self.attr('id')
+ '&q=' + query,
success: function(data) {
return typeahead.process(data);
}
});
},
property: 'name'
});
});
EDIT :: try my second answer it should work, I've been using that with another librairy that had the same problem
try something like
var id = $(this).attr('id');
then
var url = 'blahblah' + id + 'blablahblah);
and put the var url in your ajax query at the url: spot
You could add a data attribute to each input that contains the dynamic portion of the URL.
<input type="text" class="typeahead" name="person_name" id="person-search" data-source="person-search">
<input type="text" class="typeahead" name="city_name" id="city-search" data-source="city-search">
You can then grab that using jQuery and pass it into the URL.
$('.typeahead').typeahead({
source: function(typeahead, query) {
var source = $(this).data('source');
return $.ajax({
url: '/ajax_lookup_directory/'+source+'.php?q=' + query,
success: function(data) {
return typeahead.process(data);
}
});
},
property: 'name'
});
You can try the following
$('.typeahead').typeahead({
source: function(typeahead, query) {
return $.ajax({
url: '/ajax_lookup_directory/' + $(this).attr('id') + '.php?q=' + query,
success: function(data) {
return typeahead.process(data);
}
});
},
property: 'name'
});