Getting value from an input field in html off a button click - javascript

I have a button and input field, and want to send the value of that field into an ajax call. I'm having a brain freeze at the moment and could use some help. Here's what I have so far.
function submit() {
$.ajax({
type: 'POST',
url: 'http://localhost:8000/getCoords',
dataType: 'json',
data: {name: 'Abduh'},
success: (success) => {
console.log(success);
},
error: (error) => {
console.log(error);
}
});
}
<input type=text id=search placeholder=Search />
<br/>
<button id=submit onclick="submit()">Submit</button>

you should sue quote around properties values
<input type='text' id='search' placeholder=Search />
<br/>
<button id='submit' onclick="submit();">Submit</button>

$("#submit").on("click",function(){
var url= 'http://localhost:8000/getCoords';
$.post( url, { name: $("#search").val() }).done(function(data) {
alert( "Data Loaded: " + data );
});
});
<input type="text" id="search" placeholder="Search" />
<button id="submit">Submit</button>

Related

Deleting form values with same name attribute

i have a problem, i want to delete some name and leave some. but the problem when i try to delete one name it deletes the first one yet you have clicked to delete the last one.
so the main point is
how can i delete or send the name value which i want to delete instead deleting the first one or all.
because they all have same name 'info' but different values.
so i want to be deleting some and leave some instead all or only on top ones
any idea how i can do this
$(document).ready(function() {
$("#remove").click(function(event) {
Execute();
});
function Execute() {
$.ajax({
type: 'POST',
url: 'remove.php',
data: {
'info': $("input[name='info']").val()
},
success: function(response) {},
error: function() {
alert("error");
}
});
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST">
<input type="text" name="info" value="John">
<button type='button' id='remove'> delete</button>
<input type="text" name="info" value="Jane">
<button type='button' id='remove'> delete</button>
<input type="text" name="info" value="jacobo">
<button type='button' id='remove'> delete</button>
</form>
First, use a class instead of an id for your buttons. The ID should be unique.
Second, you can grab the previous input for the clicked button (target).
$(document).ready(function() {
$('.remove').click(function(event) {
execute($(event.target).prev('input'));
});
function execute($input) {
console.log(`Deleting: ${$input.val()}`);
$.ajax({
type: 'POST',
url: 'remove.php',
data: {
'info': $input.val()
},
success: function(response) {},
error: function() {
alert("error");
}
});
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST">
<input type="text" name="info" value="John">
<button type="button" class="remove">Delete</button>
<input type="text" name="info" value="Jane">
<button type="button" class="remove">Delete</button>
<input type="text" name="info" value="jacobo">
<button type="button" class="remove">Delete</button>
</form>

Update query insert if I want to edit row in PHP

I created a page, where I can easily update or insert data. It actually works, but if I click on the edit button, then I close the modal, then I add new data, it updates the previous data instead of inserting a new row. But if I refresh a page, then I update a row, it works. How can I solve this problem?
index.php:
<form method="post" id="insert_form">
<label><b>Name:</b></label>
<input type="text" name="name" id="name" class="form-control" readonly required />
<br />
<label><b>Description:</b></label>
<input type="text" name="hu" id="hu" class="form-control"></textarea>
<br />
<label><b>Cégek:</b></label>
<select name="company[]" id="company" multiple>
<?php
while($row = $huResult2->fetch_array()) {
?>
<option value="<?php echo $row['company_id'];?>"><?php echo $row['company_name'];?></option>
<?php
}
?>
</select>
<br/><br/>
<input type="hidden" name="data_id" id="data_id" />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-success" />
</form>
<script>
$('#add').click(function() {
$('#insert').val("Insert");
$('#insert_form')[0].reset();
$('#company').multiselect('refresh');
$('#name').removeAttr('readonly');
});
// Edit roles
$(document).on('click', '.edit_data', function() {
$("#company option").prop("selected", false);
$("#name").attr('readonly', true);
var data_id = $(this).attr("id");
// Receive the current datas for the roles
$.ajax({
url: "fetchRole.php",
method: "POST",
data: {
'data_id': data_id
},
dataType: "json",
success: function(data) {
$('#name').val(data.name);
$('#hu').val(data.hu);
$.each(data.companies, function(i, e) {
$("#company option[value='" + e + "']").prop("selected", true);
});
$('#company').multiselect('refresh');
$('#data_id').val(data.id);
$('#insert').val("Update");
$('#add_data_Modal').modal('show');
}
});
});
$('#insert_form').on("submit", function(e) {
e.preventDefault();
// Update and insert
$.ajax({
url: "insertRole.php",
method: "POST",
data: $('#insert_form').serialize(),
beforeSend: function() {
$('#insert').val("Updating...");
},
success: function(data) {
$('#insert_form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#role_table').html(data);
location.reload();
}
});
});
</script>
Do one thing make data_id field value blank when you are closing the modal
$('#myModal').on('hidden.bs.modal', function () {
$("#data_id").val("");
})
Maybe it will help
or on click of add new button do the same
$('#add').click(function() {
$('#insert').val("Insert");
$('#insert_form')[0].reset();
$('#company').multiselect('refresh');
$("#data_id").val("");
$('#name').removeAttr('readonly');
});

How to send similar data in array using JSON and AJAX Post Method using jQuery

HTML CODE
<form id="details">
<div>
<input type="text" placeholder="Email ID" id="email"></input>
<input type="text" placeholder="Mobile Number" id="mobile"></input>
</div>
<h5>Data</h5>
<div>
<div>
<input type="text" placeholder="Name" id="name1"></input>
<input type="text" placeholder="Age" id="age1"></input>
</div>
<div>
<input type="text" placeholder="Name" id="name2"></input>
<input type="text" placeholder="Age" id="age2"></input>
</div>
</div>
</form>
JS CODE
$(document).ready(function() {
$("form").on('submit', function(e) {
// Prepare data
var form = $("form");
var formData = new FormData(document.getElementById("details"));
e.preventDefault();
$.ajax(form.attr('action'), {
type: 'POST',
data: formData,
contentType: false,
cache: false,
processData:false,
dataType: "json",
success: function(result) {
// Success Code
},
error: function(result) {
// Failure Code
},
timeout: 5000,
});
});
});
The codepen link for my code is http://codepen.io/anon/pen/VKzGRG
I want to send data like
{
"email" : "xyz#gmail.com",
"mobile" : "9898989898",
"data" : [
{
"name":"xyz",
"age":45
},
{
"name":"xyz",
"age":45
}
]
}
I tried sending the data using jQuery.
The problem is that it's sending only one name and age.
Also, in my project, I'm dynamically adding a Name and Age box using jQuery and a button.
How can I send the data using AJAX post method using jQuery?
you have missed the name of input that's why data is not posting
see the below working code.
//HTML code
<form name="details" action="t.php" id="details">
<div>
<input type="text" name="email" placeholder="Email ID" id="email"></input>
<input type="text" name="mobile" placeholder="Mobile Number" id="mobile"></input>
</div>
<h5>Data</h5>
<div>
<div>
<input type="text" name="data1[]" placeholder="Name" id="name1"></input>
<input type="text" name="data1[]" placeholder="Age" id="age1"></input>
</div>
<div>
<input type="text" name="data2[]" placeholder="Name" id="name2"></input>
<input type="text" name="data2[]" placeholder="Age" id="age2"></input>
</div>
</div>
<input type="submit" value="send">
</form>
//ajax code
$(document).ready(function() {
$("form").on('submit', function(e) {
// Prepare data
var form = $("form");
var formData = new FormData(document.getElementById("details"));
console.log(formData);
e.preventDefault();
$.ajax(form.attr('action'), {
type: 'POST',
data: formData,
contentType: false,
cache: false,
processData:false,
dataType: "json",
success: function(result) {
// Success Code
},
error: function(result) {
// Failure Code
},
timeout: 5000,
});
});
});
To post data with jQuery and Ajax, you can do something like this
var myObj = {
"email" : "xyz#gmail.com",
"mobile" : "9898989898",
"data" : [
{
"name":"xyz",
"age":45
},
{
"name":"xyz",
"age":45
}
]
};
$.post( "test.php", myObj)
.done(function( data ) {
alert( "Data Loaded: " + data );
});
That will post the data and alert the response of the request.

Jquery serialize does not send input fields

I have a form with input fields which will be triggered every 1 min to update the user entries to the server.
$(document).ready(function()
{
timer = setInterval(function() { save(); }, 60000);
});
function save() {
jQuery('form').each(function() {
jQuery.ajax({
url: "http://localhost:7002/submitStudent.do?requestType=auto&autosave=true",
data: $('#form').serialize(),
type: 'POST',
success: function(data){
if(data && data == 'success') {
alert("data saved");
}else{
}
}
});
});
}
And here is my form
<form name="listBean">
<c:forEach var="Item" items="${listBean.nameList}" varStatus="status">
<input type="number"name="nameList<c:outvalue='[${status.index}]'/>.initialWeight" onchange="checkOnChange(this,'<c:out value='${Item.personId}'/>','<c:out value='${Item.minWeight}'/>','<c:out value='${Item.maxWeight}'/>','<c:out value='[${status.index}]'/>')">
<br><br>
<input type="number" name="nameList<c:out value='[${status.index}]'/>.finalWeight" onchange="checkOnChange(this,'<c:out value='${Item.personId}'/>','<c:out value='${Item.minWeight}'/>','<c:out value='${Item.maxWeight}'/>','<c:out value='[${status.index}]'/>')">
<br><br>
<input type="text" class="formtext" name="nameList<c:out value='[${status.index}]'/>.Reason" id ="reason<c:out value='[${status.index}]'/>" value="" maxlength="255" >
<br><br>
<input type="submit" value="submit" id="submit" />
</c:forEach>
</form>
So the ajax calls to the server works fine for every 1 min .But the values entered are not available at the server side.
I am getting the value as listBean.Item.getInitialWeight().
what am i doing wrong ?
Any suggestions are welcome.Thanks for your time ..
data: $('#form').serialize(),
should become
data: $('form').serialize(),
You are referencing to the wrong DOM item
jQuery will treat your
$('#form')
as "an element with id form". So you should change your jQuery DOM reference.
In your case it can be
$('form[name="listBean"]').serialize()

Ajax is giving me an error when I send data

I am trying to submit a form by Ajax but I am unable to . I have multiple forms and I am using (this) to submit the data. I am getting the error From error:0 error.The alert messages are showing me that I have the value.
<script type="text/javascript">
$(document).ready(function() {
$(".submitform").click(function (){
alert ($(this).parent().serialize());
$.ajax({
type: "POST",
url: "reply_business.php",
timeout:5000,
data: $(this).parent().serialize(),
beforeSend: function(xhr){
$('#load').show();
},
success: function(response){
$(this).parent().find('.sentreply').append(response);
$('.sentreply div:last').fadeOut(10).fadeIn(2000);
//uncomment for debugging purposes
//alert(response);
},
error: function(jqXHR) {
alert ('From error:' + jqXHR.status + ' ' +jqXHR.statusText);
},
complete: function(jqXHR, textStatus){
//uncomment for debugging purposes
//alert ('From complete:' + jqXHR.status + ' ' +jqXHR.statusText + ' ' + textStatus);
$('#load').hide();
}
});
});
});
</script>
I am creating the form below by the PHP code
foreach ($array['business_ids'] as $business)
{
?>
<form >
<input type="hidden" name="b_id" value="<?php echo $business ; ?>" />
<input type="hidden" name="c_id" value="<?php echo $sqlr['conversation_id']; ?>" />
<input type="hidden" name="q_id" value="<?php echo $sqlr['query_id']; ?>" />
<input type="hidden" name="u_id" value="<?php echo $sqlr['u_id']; ?>" />
<textarea name="reply">Type the reply here.</textarea>
<input type="submit" class="submitform" value="Submit">
</form>
<?php
}
I do not understand why Ajax isn't able to send the data.
Without seeing the markup or the network traffic, we can only guess. Perhaps $(this).parent() isn't the form?
It's typically safer to attach $(form).submit() than $(button).click() for this reason and because $(button).click() doesn't capture form submit by hitting the enter key.
Edit Here's an example:
<form id="theform">
<input type="text" id="thetext" name="thetext" />
<input type="submit" value="send" />
</form>
<form id="anotherform">
<input type="text" id="anothertext" name="anothertext" />
<input type="submit" value="save 2" />
</form>
<script>
$(document).ready(function () {
$("#theform").submit(function (e) {
var data = {
thetext: $("#thetext").val()
};
$.ajax("/the/server/url", {
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: function (r) {
alert("done");
}
});
// Technically you need only one or the other
e.preventDefault();
return false;
});
});
</script>
You seem to have submitted the form after starting the Ajax request - and when the page is unloaded, the request is cancelled. Since your form has no action, the submit will just reload the current page so you might not notice it.
To prevent this, you will need to preventDefault() the catched event. Also, you should not handle just click events on submit-buttons, but rather the submit-event of the <form> itself.

Categories

Resources