Send Input box value in ajax call - javascript

I want to send my input box value in my ajax call.
I am trying but not work.
My Input box
<form>
<input type="text" onkeydown="filter()" id="searchTxt" placeholder="Filter" value="" >
</form>
My Javascript code
function filter()
{
filterText = $('#searchTxt').val();
$( ".pagination" ).html(totalOutput);
$.ajax({
type: "POST",
url: ""+baseUrl+"userList4",
data: { searchText: filterText},
success: function(msg) {
$(".paginateData").html(msg);
}
});
}
Here filterText = $('#searchTxt').val(); always get null

The code to get the value is correct. So, I would say there is another issue here outside of the code you have shared. It could be jquery can't find that field. Try outputting the length to make sure jquery has actually found that text box.
var textBox = $('#searchTxt');
console.log(textBox.length);
You could also just pass 'this' to the method and not have to use jquery at all, which I would suggest.
Another issue could be that the onekeydown is getting called before the text has even reached the textbox. So at the time the value would be null. But I would assume you tested with more than one keystroke?

Related

Jquery Autocomplete widget implementation

I am trying to convert a normal field to autocomplete and making a ajax call to get the data in JSON and then set it to that autocomplete.
I do not know much on JQUERY, I spent around 5-6 hours just to know I have to initialize before using any function on the auto complete field.
What I have done so far
I managed to initialize and convert my text field to autocomplete and checked that using the inspect option it shows autocomplete , and also am able to make the ajax call which is pulling the data verified that using f12 network option.But it does not show up as a type ahead in my autocomplete option.
HTML
<div id ="myName">
<table class="some_class">
<tbody>
<tr>
<td >
<label>NAMES</label>
</td>
</tr>
<tr>
<td >
<input type="text" id="nameText" />
</td>
</tr>
</tbody>
</table>
</div>
initialization part
myName.on('valueChange',function (value){
$("#nameText").autocomplete({
appendTo:"#nameText",
source:function(event,ui){
var name=myName.value();
$.ajax({
url: "www.getmeSomeData.com/query/name:"+name,
type:"GET".
dataType:"json",
success:function(result){
//set this result in autocomplete which I am not sure how to do
}
});
},minLength:1});
});
$("#nameText").focus(function(even,ui){
$((this).data("uiAutocomplete").search$(this).val());
});
PROBLEM
1.The autocomplete does not show any result even though from ajax call i see json data coming.
2.The value change starts only after i type abc and then move the cursor somewhere else and then click it back,before that nothing invokes.Where as what is expected is as soon as I type a or ab or abc it should make ajax call and pull the data show in autocomplete dropdown.
Can someone please help? I did not come here without researched but I think i tried a lot of things and nothing worked so am totally confused.Kindly help me, i have spent around 2 days on this.
Thanks in advance.
I finally figured out what was the problem in my code.I actually was not able to add option to my input autocomplete.To make it work I needed to update my html with
HTML
just replace <input class="nameClass" type="text" id="nameText" />
And the jquery part needed updates, the above was just a very novice attempt.
1. I should have used $.each($(".nameClass"), function(index, item) {
2. and then $(item).autocomplete
3. Also in source should have used source:function(request,response)
4. In the ajax call request.term (which will take whatever you input in the autocomplete field where as my method was invoking the ajax call only after tab out.
5. Map the data of response response($.map(data.data, function(item){
6. Write a select callback function to make anything happen after i click on any entry in the typeahead
7.data("ui-autocomplete")._renderItem = function (ul, item) { >To show the data in a formatted way after the ajax call.
INITIALIZATION
$.each($(".nameClass"), function(index, item) {
$(item).autocomplete({
source:function(request,response){
$.ajax({
url: "www.getmeSomeData.com/query/name:"+request.term,
type:"GET".
dataType:"json",
success:function(result){
//set this result in autocomplete which I am not sure how to do
response($.map(data.data, function(item){
return{
value:item.somethigncomingfromJson //will set into the field
data:item
}}))}}
});
} ,minLength :2,
select:function(event,ui){
//do something on select of a row in the autocomplete dropdown
}}).data("ui-autocomplete")._renderItem=function(ul,item){
return $("format in which you want to see the data").appendTo(ul);
});
}
No other event is required.

how to retrieve a variable from jquery to php

In my php file I call a link with jquery. That link contains a select list with an input text.
$(document).ready(function() {
$(add_button).click(function(e){ //on add input button click
var linkUsers='<div id="selectUsers"><select name="selectUsers" ><option value="">Select a ...</option><option value="LASTNAME">LASTNAME</option><option value="FIRSTNAME">FIRSTNAME</option><option value="ZIPCODE">ZIPCODE</option><option value="EMAIL">EMAIL</option><option value="STATUS">STATUS</option><option value="LICENSE">LICENSE</option><option value="OTHER">OTHER</option></select><br><br> </div><div><input type="text" id="mytext" name="mytext"> <br><br>';
$(wrapper).append(linkUsers);
I want to retrieve the value of selectUser and mytext and put them in a database or php variable.
I tried to see if I can have the correct result with jquery so I used alert and it display the right value.
`//when the user choose an option in the select list
$('#selectUsers select').change(function(){
tableselect = $(this).val() ;
alert(tableselect[$i]);`
What I want to do is to retrieve this value and to put it in a database and to retrieve the input text written by the user (I have no idea how to do that ? how to detect that user has filled the blank ?)
The other problem is that I call the jquery link as many as the user want so it will be useful to put the value of selectUser and mytext in an array variable but I don't know how !
If someone can help me U will be grateful. THANKS A LOT !
This is the jQuery ajax code
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#selectUsers select').change(function(){
tableselect = jQuery(this).val() ;
var data_pro = {
action: 'update_record',
tableselect: tableselect
};
jQuery.ajax({
type: "POST",
dataType : 'html',
url: ajaxurl,
data: data_pro,
success: function(data){
}
});
});
});
</script>
this is the php function put it in your functions.php file
add_action('wp_ajax_update_record', 'update_record');
add_action('wp_ajax_nopriv_update_record', 'update_record');
function local_pickup_shipping_options(){
print_r($_POST['tableselect']);
}
Hope this will resolve your issue
Note : wrapper not specified as class or id ,replace according to that.i am assuming as id
you can pick the value of select box and input like this .
For select :
Note : add id on select box ,for now i have added "selectUsers"
$("#wrapper").on("change","#selectUsers",function(){
alert($(this).val());
});
For input :
$("#wrapper").on("keyup","#mytext",function(){
alert($(this).val());
});
then you can send this response by ajax to php file ands store into db.
you can change event according to need.
Hope this will help you.

How to get modified text from input JQuery or javascript

I'm having a problem getting modified text from input. The input is loaded with some text I get from a database and with an option i should take the onlyread attr off and change the values. Thats ok but when i click on the save button after writing something else in the inputs, it gets the old values with .val(). How can i get the new ones?
The code is something like this.
var anInput = $("#anInput").val(); //gets old value
var otherInput = $("#otherInput").val(); //gets old value
$.ajax({
type: "POST",
dataType: "html",
success: doSomething,
timeout: 4000,
error: someProblems,
url: "modules/mod.php",
data: {anInput: anInput, otherInput: otherInput}
});
I added the AJAX code just to mention that i need the values to do something. AJAX is working.
I know this can be done with a form but that will reload the page and I don't want that.
Sorry for my rusty English and thanks :)
EDIT: Perhaps I'm not correctly speaking when saying "change the values" what I'm doing is selecting the text and writing something else.
I show some information with the inputs, click a button that allows me to modify, type some new text in the inputs and then click "save"
HTML is genereted by another AJAX
<div class="infoVideo">
<input id="anInput" value="someTextFromDataBase">
<input id="otherInput" value="someTextFromDataBase">
<input type="button" id="btnMod">
<input type="button" id="btnSave">
</div>
If I erase and type something else in the input .val() is getting old someTextFromDataBase
Edit: As per a guess in my comments, there was more than one #anInput in the page so the code was only retrieving the value from the first one which was not the one being edited. The solution is to not have any duplicate id values in the HTML of the page.
I suspect that your code isn't really like you show. You are probably doing these:
var anInput = $("#anInput").val(); //gets old value
var otherInput = $("#otherInput").val(); //gets old value
only once and then trying to use anInput and otherInput much later when the form fields have already changed. You can get the current values by not caching those and just retrieving the current values when you need them by changing this:
data: {anInput: anInput, otherInput: otherInput}
to this:
data: {anInput: $("#anInput").val(), otherInput: $("#otherInput").val()}
That way, you are always retrieving the latest and greatest values right before your Ajax call.
Please confirm format of data returned by mod.php. The AJAX block is expecting to receive HTML formatted text dataType: 'html', -- but you are sending json, so is that what you are expecting back?
If this note doesn't reveal the solution, then please show us your doSomething function - that's where the returned data is handled.
Probably you've tried this already, but what happens if you do this:
var anInput = $("#anInput").val(); //gets old value
alert(anInput);
var otherInput = $("#otherInput").val(); //gets old value
alert(otherInput);
$.ajax({ //etc });

Updating an html "value" with a jquery variable

So i'm building a messaging application in which a user clicks on a button, a jquery prompt is displayed asking for the user to type in their message, and then ideally the message is sent using a separate ajax function.
Here is the code in question:
jQuery message prompt function:
function getInput() {
var text = prompt("Enter message", "");
if (text != null) {
document.getElementById("demo").innerHTML = text; //failed attempt at updating the value just using the id of the input.
}
}
HTML:
<form name="messagesend" method="post" onsubmit="return sendMessage(this);">
<input type="hidden" id="demo" name="message" value="I want to update this field with the result of the javascript text variable" />
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
<input type="submit" class="send_btn" value="Volume-Vibrate" onclick="getInput()"/>
</form>
As you can see, the field I want to update is the string contained in value which is the message being sent. How could I get that to update with the result of whatever the user puts in the text prompt?
Any help would be greatly appreciated!
EDIT:
Updated jQuery function to the following:
function getInput() {
var text = prompt("Enter message", "");
if (text != null) {
$("#demo").val(text);
}
}
This may be a different question, but when the button that is created in the HTML I originally posted is clicked, it displays the prompt and I type in a message, but the default value that I placed is still the message being sent. Is
onsubmit="return sendMessage(this);"
Being executed before the jQuery is updating the value field? And if so, is there anyway to fix that?
If it helps, here is sendMessage which uses ajax to send off the message to a php script.
The HTML value field (which I'm trying to get to be the user-input string from the jQuery prompt using getInput()) becomes the data variable, which also contains the registration id of the designated recipient of the message.
function sendMessage(formObj){
var data = $(formObj).serialize();
$(formObj).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
A HTML field doesn't have inner HTML (the tag is self-closing), it has a value (and a value property).
But as you're using jQuery, you should use its functions anyway: $("#demo").val(text)
As #Lucas has mentioned, $("#demo").val(text) works (see the JQuery documentation)
Another way of doing the same thing (referencing the input field by name):
$('input[name="demo"]').val()
However, a name does not need to be unique, while an id should be unique (see this SO answer). It would be safer to add id="demo" to your input name - overkill in this case, but good practice.

Dynamic Divs in jsp

I'm trying to create a page that will be rendered in steps. A user selects a certain option and the next div is dynamically rendered on the jsp page depending on the values selected. for example
MyPage.jsp
<input type="button" onclick="somejsfunction();" value="Select Choice" />
somejsfunction() issues a POST to the server and sets some values in the session. I then need to render a div in MyPage.jsp. I'm thinking i could always just spit out the HTML code from the post call and then append it to the document body in somejsfunction() but i was wondering if there is a cleaner way to do this? Thanks
It is much cleaner with jQuery
function callMe(){
$.ajax({
type: "POST",
url: "/someServlet",
data: { methodToInvoke: "sayHello" , data: "Abc" }
}).done(function( msg ) {
//msg is the HTML received from server
$("#someDivId").html(msg);
});
}

Categories

Resources