Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post text input value to ajax

Tags:

jquery

ajax

forms

I have a functional AJAX post that's working great. My client requested an additional text input field, and for the life of me, I can't get it. The script is long so I'll give you the relevant bits in hopes that it's a matter of syntax.

HTML for my input:

<input type="text" name="why" id="why" maxlength="70">

Javascript call

$(document).on("click", ".take-claim-link", function(){
var id= $(this).attr('data-id');    
var point= $(this).attr('data-point');
var val= $(this).attr('data-val');  
var type = $(this).attr('data-type');
var why = $("#why").val();

var follow = document.getElementById("follow-" + id + "-"+ type);
var followuser='0';
if (follow.checked) {
    var followuser = "1";
}


var takeurl = '/api/responseClaim.json';
var newPrice ='';   

var newData = $.ajax({ 
    type: "POST",
    url: takeurl,
    dataType: "json",
    data: { point: point, claimId: id, type: val,why: why,follow: followuser }
    })
(etc).

It returns nothing for "why".

The funny thing: if I change the variable to var why = 'sample why'; it passes. Likewise, if I change my input to <input type="text" name="why" id="why" maxlength="70" value="some value"> it reads it. So I think the problem is in the way I'm defining it.

But what? I've also tried var why = $("input#why").val(); and document.getElementById("why").value;

like image 624
dilettante Avatar asked Jan 12 '23 22:01

dilettante


1 Answers

There could be another element with same id="why" in your HTML code. So try to search for it. Or change the id of above input to something else.

Optionally you can try to get that input value with:

var why = $('input[name="why"]').val();

Hope it helps.

like image 127
Hieu Nguyen Avatar answered Jan 17 '23 09:01

Hieu Nguyen