How to post jquery ajax data object with multiple values - javascript

I have a form with two inputs (later more inputs). One input is a text input and the second one is a checkbox. I would like to send these two inputs with $.ajax.
I created an Object formData with one input. The second one I would like to append to the Object if the checkbox is active or not.
Unfortunately, I can't pass the Object because of a wrong format.
My Code:
<form id="myForm">
<input type="text" name="search_text" id="search_text" placeholder="Search by a name">
<input type="checkbox" name="exact" value="Exact">Exact
</form>
<br>
<div id="result"></div>
<script type="text/javascript">
$(document).ready(function(){
$('#myForm').on('change', ':checkbox', function(){
if($(this).is(':checked')) {
console.log($(this).val() + ' is now checked');
}
else {
console.log($(this).val() + ' is now unchecked');
}
});
var formData = {'qry':search};
$('#search_text').on('keyup', function(e){
e.preventDefault();
var search = $(this).val();
$('#result').html('');
$.ajax({
url:"fetch.php",
method: "POST",
data: formData,
dataType: "text",
success:function(data) {
$('#result').html(data);
}
});
});
});
</script>

You need to serialise the form data and then add more data if required:
var data = $('#myForm').serializeArray();
data.push({name: 'sample', value: "something_more"});
Your ajax should then be something like:
var data = $('#myForm').serializeArray();
data.push({name: 'sample', value: "something_more"});
$.ajax({
url:"fetch.php",
method: "POST",
data: data,
dataType: "text",
processData: false,
success:function(data) {
$('#result').html(data);
}
});

Related

auto check checkboxes for matching result in ajax call

I'm trying to make it so that when my ajax call is returned with an object/array, I can match up the results to checkboxes so that if there is a match I auto check the boxes
Here are my checkboxes
<input type="checkbox" name='Magazine' data-md-icheck />
<input type="checkbox" name='Website' data-md-icheck />
<input type="checkbox" name='Advertisement' data-md-icheck />
Now my ajax call is successful
I get back:
0: {}
type: "Magazine"
1: {}
type: "Website"
so in my ajax success, what I would like to do is take any result in that object, whether just one or all 3, and if the type matches the 'name' of the checkbox I want to check that box.
Here is my function that makes the successful ajax call. I just can't figure out a way to loop the return that I get so that I can match up any result that comes through
function getDetails(ID) {
console.log(ID);
$.ajax({
url: "/details",
data: {ID:ID},
_token: "{{ csrf_token() }}",
type: "POST",
success: function (data) {
},
});
};
So in this case, how would I modify my ajax success to check the magazine and website boxes?
Here is a pure JS and simple solution to this:-
// Assuming you get the response as an array of objects, which has a key as type
success: function (data) {
data.forEach(obj => {
let ele = document.getElementsByName(obj.type)[0];
if(ele) {
ele.checked = true;
}
});
}
This is how I would tackle it:
function getDetails(ID) {
console.log(ID);
$.ajax({
url: "/details",
data: {ID:ID},
_token: "{{ csrf_token() }}",
type: "POST",
success: function (data) {
for(var i=0;i<data.length;i++){
var item = data[i].type;
var checkbox = $('input[name="'+item+'"]);
if (checkbox.length){
checkbox.prop('checked', true);
}
}
},
});
};
Assume the result is pure text exactly the same as you provided (ES6+)
let a = 'result...'
['Magazine', 'Website', 'Advertisement'].filter(item => a.indexOf(item) != -1).forEach(item => {
let inputs = document.getElementsByName(item)
if (inputs.length > 0)
inputs[0].checked = true
})

jquery ajax form submit with edit values

I have a datatable where I have the detail column with an edit button. When the user clicks on the edit am passing the id as a parameter. I am fetching all the values for that id and displaying in the form. Now when I edit the values and submit the form using PUT method it is getting inserted in the table, the values are passing as a parameter and it shows the empty form. How to solve this issue.
HTML:
<form class="container" id="myform" name="myform" novalidate>
<div class="form-group row">
<label for="position" class="col-sm-2 col-form-label fw-6">Position</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="position" name="position" placeholder="Position" required>
</div>
</div>
<div class="form-group row">
<label for="location" class="col-sm-2 col-form-label fw-6">Location</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="location" name="location" placeholder="Location" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
PUT Method Script:
<script type='text/javascript'>
$(document).ready(function(){
$("#myform").submit(function(e) {
var parms = {
position : $("#position").val(),
location : $("#location").val()
};
var par_val;
var param_id = new window.URLSearchParams(window.location.search);
par_val = param_id.get('id');
console.log(par_val);
var par_url = par_val;
$.ajax({
url: "http://localhost:3000/joblists/"+par_val,
method: 'PUT',
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data){
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
});
});
</script>
GET method script:
<script type="text/javascript">
$(document).ready(function(){
var id_val;
var params = new window.URLSearchParams(window.location.search);
id_val = params.get('id');
console.log(id_val);
var url1=id_val;
$.ajax({
url: "http://localhost:3000/joblists/"+id_val,
type: "GET",
dataType: "json",
success: function (data) {
// alert(JSON.stringify(data));
console.log(typeof(data));
$("#position").val(data.position);
$("#location").val(data.location);
},
error: function(data) {
console.log(data);
}
});
});
</script>
After submitting the form the page should remain the same with edit form values. only the edited values should be inserted. How to achieve this.
$('#myform').on('submit', function (e) {
e.preventDefault();
..........
I have checked your code in my editor. There are some changes which i made in ajax request, and it now works for me. here is the code. Try it
<script type='text/javascript'>
$(document).ready(function(){
$("#myform").submit(function(e) {
e.preventDefault();
var parms = {
position : $("#position").val(),
location : $("#location").val()
};
var par_val;
var param_id = new window.URLSearchParams(window.location.search);
par_val = param_id.get('id');
console.log(par_val);
var par_url = par_val;
$.ajax({
url: "http://localhost:3000/joblists/"+id_val,
method: 'POST', //or you can use GET
dataType : "json", //REMOVED CONTENT TYPE AND ASYNC
data: {send_obj:JSON.stringify(parms)}, //ADDED OBJECT FOR DATA
success: function(data){
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
});
});
</script>
Adding prevent default in form submit handle is enough. You're handling the post request by ajax call.
e.preventDefault();
There are 2 changes in your code.
This code will prevent your page from reloading and also you are not sending the data in proper format.
$("#myform").submit(function(e) {
e.preventDefault(); // 1. Dont reload the page
var parms = {
position : $("#position").val(),
location : $("#location").val()
};
var par_val;
var param_id = new window.URLSearchParams(window.location.search);
par_val = param_id.get('id');
console.log(par_val);
var par_url = par_val;
$.ajax({
url: "http://localhost:3000/joblists/"+par_val,
method: 'PUT',
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: parms, // 2. Just send the parms object bcoz you already defined the dataType as json so it will automatically convert it into string.
success: function(data){
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
});

jQuery autocomplete UI - doesn't work

I am trying to make an autocomplete widget that will display item's codes returned from a database.
I have successfully made it so my database will return the appropriate JSON response.
The problem now is I don't know why the drop-down list doesn't show up.
Here's the code down below:
<input type="text" id="search" class="form-control" placeholder="">
<form action="post" action="" id="spareParts" class="spareparts">
</form>
$('#search').keyup(function(event) {
var search = $(this).val();
if($.trim(search).length){
var arr = [];
$.ajax({
url: 'get_spareparts',
type: 'POST',
dataType: 'JSON',
data: {item: search},
success: function (data) {
arr = $.parseJSON( data );
console.log(arr);// CONSOLE.LOG WORKS WELL
//[Object { id="1", value="25.00", desc="Fuel pump", more...}]
// AUTOCOMPLETE DOESN'T WORK
$('#spareParts').autocomplete({
minLength:0,
source: arr
});
}
});
}
});
The autocomplete with AJAX loaded data should be configured differently. source property can be a function which accepts a callback parameter. You should feed this callback with data loaded from server.
Also you don't need to bind keyup event manually. Your code will become:
$('#search').autocomplete({
minLength: 0,
source: function(request, response) {
$.ajax({
url: 'get_spareparts',
type: 'POST',
dataType: 'JSON',
data: {item: request.term}
}).done(function(data) {
response(data.map(function(el) {
return {
value: el.value,
label: el.desc
};
}))
});
}
});

Submit checkbox state without a submit button

I have a view with a few checkboxes that can be selected or unselected. I'd like to always register any change in a checkbox, without the use of a submit button (the user could forget to do it, and it would waste time).
So, is there a way to handle this inside the view? Up to now, I've only used the controller to do that job.
So, a piece of code :
#ModelType MvcApplication.OpportuniteDetails
#Code
ViewData("Title")="Details"
#End Code
<script type="text/javascript">
$(function () {
$(':checkbox').change(function() {
$.ajax({
url: '#Url.Action("update")',
type: 'POST',
data: { isChecked: $(this).is(':checked') },
success: function (result) { }
});
});
});
</script>
[... Some code here...]
#Html.Raw("Mail sent?") #Html.CheckBox(Model.Opportunite.Mail)
<input type="checkbox" name="mail" id="mail" onclick="test()" />
You could use AJAX:
$(function() {
$(':checkbox').change(function() {
var form = $(this).closest('form');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(result) {
}
});
});
});
In this example we subscribe to the change event of each checkbox. When this event is trigerred we look for the containing form and send its contents to the server using an AJAX request.
And if you only wanted to submit the current checkbox state to the server and not the entire form:
$(function() {
$(':checkbox').change(function() {
$.ajax({
url: '#Url.Action("SomeAction")',
type: 'POST',
data: { isChecked: $(this).is(':checked') },
success: function(result) {
}
});
});
});
where you could have a controller action which will do the necessary processing:
[HttpPost]
public ActionResult SomeAction(bool isChecked)
{
...
}
If you don't need or want AJAX and just want to submit the form, this
$(':checkbox').change(function() {
var form = $(this).closest('form');
form.get( 0 ).submit();
});
would do it.

How to pass checkbox values into an array using jQuery?

I am have the below checkboxes and I want to pass the checked values to an array so that I can do an ajax post. However, I am hitting an error and I am not sure where I went wrong...
How do I pass the values into the array and how do I retrieve them?
HTML
<input type="checkbox" name="newCheckboxes" value="1" />
<input type="checkbox" name="newCheckboxes" value="2" />
<input type="checkbox" name="newCheckboxes" value="3" />
Script (not working)
var allFields = $( [] );
$("#newCheckboxes:checked").each(function() {
allFields.add( $(this).val() );
});
$.ajax(
{
type:"POST",
url: "PostedHere",
data:{
checkedValues: allFields
}
});
You only need:
$.ajax({
type:"POST",
url: "PostedHere",
data: { checkedValues: $("#newCheckboxes:checked").serialize() }
});
// checkedValues: "newCheckboxes=1&newCheckboxes=2" etc..
Using karim79 code idea:
$.post('URL', $('[name="newCheckboxes"]:checked').serializeArray(), function(data){
//data
});
What I prefer to do is: Create a new Object and add all checkboxes 'Value' and 'Ischecked' to an array (access), then pass it to page by Json:
$(document).ready(function () {
$("#btnSave").click(function () {
event.preventDefault();
$("#newCheckboxes").each(function () {
var data= new Object()
var access = new Array();
access.ChValue = $(this).attr("value");
if ($(this).attr("checked") == "checked") access.ChChecked = true;
data.push(access);
});
$.ajax({
type: 'POST',
url: '#Url.Content("~/URLofPage")',
data: $.json.encode(data),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
});
});
please do not forgot to add Json reference to your page:
<script src="../../../Scripts/jquery.json.js" type="text/javascript"></script>

Categories