I have a form which has two jQuery datapicker input fields, and a form button,
From: <input class="input-large" type="text" id="datepicker_from" name="datepicker_from">
To: <input class="input-large" type="text" id="datepicker_to" name="datepicker_to">
<a class="btn btn-primary" onclick="get_call_details(1, from_date, to_date )" >Check Availability</a>
What i am trying to do is get the date of both fields datepicker_from and datepicker_to and then on click of a form button call function get_call_details(1, from_date, to_date )
The problem is i am not able to get the value of both date fields
Following is how i am trying to get the date field values
$("#datepicker_from").blur(function(){
var from_date = document.getElementsByName('datepicker_from').value;
alert (from_date);
});
$("#datepicker_to").blur(function(){
var to_date = document.getElementsByName('datepicker_to').value;
alert (to_date);
});
and this is the JS function I am trying to pass the both dates to
function get_call_details(id, from_date, to_date) {
alert(id, from_date, to_date );
$('#dvloader').show();
$.ajax({
url: 'outlook_calendar.php',
type: 'POST',
data: {'userid': id},
success: function (data) {
$(this).parent("#availability").append(data);
$("#availability").html(data);
$('#dvloader').hide();
}
});
}
All i want is to get the dates of both fields and pass it to function on click of a button, But I am not able to get the dates. I will appreciate any help.
Why not just write this all into a jquery function attached to the a click event:
From: <input class="input-large" type="text" id="datepicker_from" name="datepicker_from">
To: <input class="input-large" type="text" id="datepicker_to" name="datepicker_to">
<a class="btn btn-primary" id="checkavail" >Check Availability</a>
$('#checkavail').click(function(){
var from = $("#datepicker_from").datepicker('getDate');
var to = $("#datepicker_to").datepicker('getDate');
$('#dvloader').show();
$.ajax({
url: 'outlook_calendar.php',
type: 'POST',
data: {'userid': 1, 'from':from, 'to':to},
success: function (data) {
$(this).parent("#availability").append(data);
$("#availability").html(data);
$('#dvloader').hide();
}
});
I think the better approach would be to read the to and from date inside get_call_details function.
Function get_call_details(id)
{
from_date = $("#datepicker_from").val();
to_date = $("#datepicker_to").val();
}
The getElementsByName() returns an array of result. you should use the getElementById or either use the jQuery selector $('#yourId').val().
Related
I have a problem. I want to exchange certain data using PHP, MySQL and Ajax.
To do this I always have to pass the ID of a field to my backend, so I can continue working with this ID.
How do I pass the value from my button to my URL in Ajax?
What do I have to consider?
row['id'] is my variable (PHP)
HTML Code:
<a class='commentSikayet'>
<button id='commentSikayet' name='commentSikayet' value='{$row['id']}'>
Şikayet et
</button>
</a>
Ajax:
$(document).ready(function () {
$("#commentSikayet").click(function () {
$.ajax({
url: 'report_comment.php',
type: 'POST',
data: {bar: $("#bar").val()},
success: function (result) {
alert('Erfolgreich gemeldet.');
}
});
});
});
Assuming there might be more than one data sets in your page I modified your example to the following snippet. Each buttons has a data-id attribute that identifies the current dataset (the id would be supplied through your PHP script as $row["id"]):
$("body").on("click","button", function(ev){
ev.preventDefault(); // prevent submitting a form ...
let data={cmt_id: $(this).data("id"),
value: $(this).prev().val()}
$.post("https://jsonplaceholder.typicode.com/comments",data)
.done(function (result) {
console.log("Erfolgreich gemeldet:",result);
});
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div><input type="text" value="some text">
<button name="commentSikayet" data-id="123">Şikayet et</button></div>
<div><input type="text" value="some other text">
<button name="commentSikayet" data-id="124">Şikayet et</button></div>
<div><input type="text" value="more text">
<button name="commentSikayet" data-id="125">Şikayet et</button></div>
In your backend PHP script (taking the place of the above typicode-URL) you can pick up the values from the $_POST superglobal as
$_POST["cmt_id"]; // id value
$_POST["value"];. // actual text content
Since you're listening for the click event on the button, you can access it via this in your handler function.
Add the name / value pair to your AJAX data option
$("#commentSikayet").on("click", function (e) {
e.preventDefault();
$.post("report_comment.php", {
bar: $("#bar").val(),
[ this.name ]: this.value // add name / value in here
}).done(function (result) {
alert('Erfolgreich gemeldet.');
});
});
This will include commentSikayet=rowIdValue in the POST request body which you access on the PHP side via...
$rowId = $_POST["commentSikayet"];
I need to submit a form using FormData() but in the form i use a button with type="button" instead of type="submit" which will refresh the page. I tried to search on google for solution but so far couldn't find the right answer or a clear answer. I will be posting a simple form with 3 inputs and start from here if i want to go bigger. When i var_dump[$_POST] i get empty array[0]{}
please help.
$("#discussion_submit_button").on("click", function(e){
//$("#discussion_form").submit(function(e){
e.preventDefault();
var title = $("#discussion_title").val();
var discussion = $("#discussion_input_textarea").val();
if (title == '' || discussion == '') {
$(".discussion_label_arrow, .discussion_required_fields").fadeIn("Slow");
// error message, we select span tag with ID error_message and we change its content to this text
setTimeout(function(){
$('.discussion_label_arrow, .discussion_required_fields').fadeOut("Slow");
}, 2000);
} else {
var formData = new FormData(this);
alert(formData);
$.ajax({
url: "widgets/discussion_board_submit.php",
method: "POST",
cache: false,
processData: false,
contentType: false,
data: formData,
success:function(data){
//alert(data);
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="" class="discussion_form" id="discussion_form">
<div class="discussion_label_div"><span class="discussion_label_span">Title</span><span class="discussion_label_arrow"><span></div>
<div class="discussion_input_div"><input type="text" name="discussion_title" class="discussion_input" size="50" id="discussion_title"/></div>
<div class="discussion_label_div"><span class="discussion_label_span">Subject</span><span class="discussion_label_arrow"><span></div>
<div class="discussion_label_div"><span class="discussion_label_span">Discussion</span><span class="discussion_label_arrow"><span></div>
<textarea rows="5" cols="50" name="discussion_textarea" class="discussion_input_textarea" placeholder="Open your discussion..." id="discussion_input_textarea"></textarea>
<input type="button" name="discussion_submit_button" value="Assert" class="share_button" id="discussion_submit_button"/>
</form>
and this is my php :
var_dump($_POST);
Instead of validating the form with javascript add a required attribute to the fields that can't be empty.
If you like You can use css styling such as :invalid to style them
user will get focus on the first element that is wrong and will be able to correct it when they try to submit it.but that can't happen unless the submit event is triggered which won't happen if you use a button.onclick or a type="button" and prevent the flow. And that is your mistake.
when you construct your formdata the argument becomes a button element and not a form which the FormData requires
new FormData(this); // <-- `this` is a button elm in your case
So when you use constraint validation, then submit event will only get trigger if all fields are valid. So you will always have a valid form on the submit event and this will be referred to the form element which you need for the FormData
So here is what i should have done:
function form2ajax(evt) {
evt.preventDefault();
var formData = new FormData(this);
// Having html define the markup
// makes you able to reuse this function
// for other forms
$.ajax({
url: this.action,
method: this.method,
cache: false,
processData: false,
contentType: false,
data: formData,
success: function(data) {
//alert(data);
}
});
// Just Another solution to submit the form...
// fetch(this.action, {method: this.method, body: formData})
// .then(res => res.text())
// .then(console.log)
}
$("#discussion_form").submit(form2ajax)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="widgets/discussion_board_submit.php" class="discussion_form" id="discussion_form">
<div class="discussion_label_div">
<span class="discussion_label_span">Title</span>
<span class="discussion_label_arrow"><span> <!-- note missing / in span -->
</div>
<div class="discussion_input_div">
<!-- note required attribute -->
<input type="text" required name="discussion_title" class="discussion_input" size="50" id="discussion_title"/>
</div>
<div class="discussion_label_div">
<span class="discussion_label_span">Subject</span>
<span class="discussion_label_arrow"><span> <!-- note missing / in span -->
</div>
<div class="discussion_label_div">
<span class="discussion_label_span">Discussion</span>
<span class="discussion_label_arrow"><span> <!-- note missing / in span -->
</div>
<!-- note required attribute -->
<textarea required rows="5" cols="50" name="discussion_textarea" class="discussion_input_textarea" placeholder="Open your discussion..." id="discussion_input_textarea"></textarea>
<!-- note using type=submit instead of type=button -->
<!-- type=button don't trigger a submit -->
<input type="submit" name="discussion_submit_button" value="Assert" class="share_button" id="discussion_submit_button"/>
</form>
The problem is you pass this to FormData constructor, but it requires form element to initialize object.
You can do this:
var formData = new FormData(this.form);
or just pick form from DOM:
var formData = new FormData($("#discussion_form")[0]);
Just remember you have to pass HTMLFormElement to FormData, so you can't use jQuery object. That is why I pick first element from the jQuery array.
I am trying to add a date into my database. When I had it the type set to date it would be set to 00000000 when trying to add data to db, so I changed it to varchar, but now when I input dates it says for example -1995 or -2000. I just want to include the date the user selects into the database. I am so stuck and have tried absolutely everything I can think of.
If anyone has any ideas as how to fix this, I would be very grateful. Thanks, below is the code I have
HTML
<span class="dpWrapper"><p class="date"> Date From: </p>
<input type="text" class="datepickerdoc dpInputFrom"> </span>
<span class="dpWrapper"><p class="date">Date To: </p>
<input type="text" class="datepickerdoc dpInputTo"> </span>
jAVASCRIPT
$(function () {
$(".datepickerdoc").datepicker({dateFormat: 'dd-mm-yy'});
});
hotelImg.addEventListener('click', function () {
var data = {
fromDate : document.getElementsByClassName('dpInputFrom')[0].value,
toDate : document.getElementsByClassName('dpInputTo')[0].value,
id : hotelData.hotel_id
};
$.ajax({
url: 'php/uploadItinerary.php',
type: 'POST',
data: data,
success: console.log,
error: console.log
});
});
PHP
$userId = $_SESSION['userId'];
$hotelId = $_POST['id'];
$dateTo = $_POST['toDate'];
$dateFrom = $_POST['fromDate'];
The hotel id successfully is added to the database, just not the dates.
I've got the following form:
<div>
<form name="ajaxformname" id="ajaxform" action="/request" method="POST">
AJAX:
<input id="btn1" name="feeling" type="submit" value="Fine">
<input id="btn2" name="feeling" type="submit" value="Neutral">
<input id="btn3" name="feeling" type="submit" value="Bad">
</form>
</div>
which should be posted to a server via ajax.
Here is the associated javascript:
$('#ajaxform').submit(function (event) {
event.preventDefault();
var form = $(this);
var action = form.attr("action"),
method = form.attr("method"),
data = form.attr("value");
$.ajax({
url: "/request",
type: method,
data: data
});
Now - depending on which of the three buttons has been clicked - I want their values to be posted to the server. But form.attr("value") just gives me the value of the form but not of the input field.
Any suggestions? A solution would be to create the different forms but that doesn't seems to be DRY ...
First thing, if you wanna use the action attribute of the form, you should reference it in the url param of ajax request:
url: form.attr('action'),
Now, for the button clicked, you should use this (it's a workaround because submit buttons are not incluided in the form serialization, if not, I would use it instead):
$(function () {
//When any of the buttons is clicked, we store in the form data the clicked button value
$('#ajaxform').on('click', 'input[type=submit][name=feeling]', function(e) {
$(this.form).data('clicked', this.value);
});
$('#ajaxform').submit(function (event) {
event.preventDefault();
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr("method"),
data: { clickedButton : form.data('clicked') } //Retrieve the button clicked value from the form data
});
});
});
Here the working example: https://jsfiddle.net/68qLxLgm/1/
Hi kindly use the following to get the id of the button that has been clicked
$("input").click(function(e){
var idClicked = e.target.id;
});
I am looking for a way to take input from an HTML form and store it into a JSON object for use with AJAX. I can't use the normal $('#id').val();, because, as you can see below, there are a lot of fields. Here is some sample code
Javascript/jQuery:
$(document).ready(function() {
$('.add-to-cart').click(function() {
var id = $(this).attr('id');
//var qty = $(this).attr('qty'); <- need the quantity from the field
console.log(id);
//console.log(qty);
$.ajax({
url: 'addproduct',
type: 'POST',
datazType: 'JSON',
data: {
"id": id
//"qty": qty
},
success: function(addedproduct) {
console.log(addedproduct.name);
$('#cart').append('<li>'+ addedproduct.name +'</li>');
},
error: function() {
console.log('failed to add product');
}
})
});
});
HTML:
<p class="name">{{$product->name}}</p>
<input type="number" id="qty" class="qty" name="qty">
<button type="submit" id="{{$product->id}}" class="add-to-cart">Add to cart</button>
Help me please, or at least guide me in the right direction, this HAS to happen using AJAX.
jQuery's selialize method is what you are looking for. It serializes the values of inputs in a form.
Helpful example: https://stackoverflow.com/a/6960586/4180481