custom keys for form.serializeArray() - javascript

I have a Questionnaire page which is dynamically created via the back end. I need to serialize the form data but the form.serialize array takes the name attribute I want to assign my own key for the data I send. I'm very new to javascript.
I need to put the question data-id in place of the key and the selected input value is this possible?
I'm using AJAX to post the form.
The back end is Flask.
The html page
<h4 class="text-edit" id="question-{{key}}" data-id="{{key}} //will be numeric">1. Does the lecturer Communicate clearly?</h4>
<!-- I need the data-id of the h4 tag-->
<input type="radio" name="options1" id="options" value="1" >
<!-- And the value of the value in the radio button-->
<label class="radio-inline mg" for='options'> Yes</label>
<input type="radio" name="options1" id="options" value="2">
<label class="radio-inline mg" for='options'> No</label>
The Javascript I'm using
var dataset = {
"stream": $("#stream_id").data("name"),
"subject": $('#subject_select option:selected').val(),
"teacher": $('#teacher_select option:selected').val()
};
// IF I COULD Even append the data to the above thing that also would work
$.ajax({
url: "{{url_for('question.gen_teacher')}}",
data: $('form#questionform').serialize(),
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});

1. With .serialize()
Actually, .serialize() method will make your form key it's value to be like :
key1=value1&key2=value2
so just append some string to your .serialize() method :
var dataset = {
"stream": $("#stream_id").data("name"),
"subject": $('#subject_select option:selected').val(),
"teacher": $('#teacher_select option:selected').val()
};
$.ajax({
url: "{{url_for('question.gen_teacher')}}",
data: $('form#questionform').serialize() + "&data-id=value",
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
2. With .serializeArray()
var formData = $('form#questionform').serializeArray();
formData.push({ name: "data-id", value: "somevalue" });
and put formData variable inside your $ajax data
Requested Answer ?
with
HTML :
<h4 h-id="1" class="text-edit" id="question-{{key}}" data-id="{{key}} //will be numeric">1. Does the lecturer Communicate clearly?</h4>
<select answer-id="1">
<option value="1">Yes</option>
<option value="0">No</option>
</select>
JavaScript :
var formData = {};
$("h4[h-id]").each(function(){
var hid = $(this).attr("h-id");
var id = $(this).attr("id");
var answer = $('select[answer-id="'+hid+'"]');
formData.push({id:answer});
})
// ... ajax
data: formData,

Related

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);
},
})
});

Form ajax post data to php file [duplicate]

This question already has answers here:
jQuery Ajax POST example with PHP
(17 answers)
Closed 5 years ago.
Hi i trying make form using ajax. But i get some problems to sending form vars to php file. I get error: Undefined index: name.
I check chrome dev tools and i see variable is sending. But when made echo json_encode i see in php file i get empty array. So i dont have any idea where i made misstake.
file Main.js
var name = $('#user_name').val();
var lname = $('#user_lastname').val();
function formLogin(name, lname)
{
$.ajax({ url: 'database/register.php',
data: {
'name' : name,
'lname' : lname
},
type: 'post',
dataType:'json',
success: function(data) {
alert(data);
}
});
}
Html form:
<form class="circleForm" id="registerForm">
Imię: <input type="text" id="user_name"><br>
Nazwisko: <input type="text" id="user_lastname">
<br>
<input class="btnCircle" type="button" id="submit" value="Przejdź dalej" onclick="formLogin(name, lname)">
</form>
Php Code:
$dane = $_POST;
echo json_encode($dane);
Chrome dev:
I just want figure how can i echo this variables(name,lname) in php file register.php
Version with serialize:
function formLogin() {
var dane = $('form').serialize();
$.ajax({
url: 'database/register.php',
data: {'dane': dane},
method: 'post',
success: function(data) {
console.log(data);
}
});
}
Then result console:
<pre class='xdebug-var-dump' dir='ltr'>
<small>D:\xampp\htdocs\szkola\database\register.php:8:</small>
<b>array</b> <i>(size=1)</i>
'dane' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>''</font> <i>(length=0)</i>
</pre>
jquery-3.2.1.min.js:4 XHR finished loading: POST "http://localhost/szkola/database/register.php".
But when i go to http://localhost/szkola/database/register.php
i get this:
D:\xampp\htdocs\szkola\database\register.php:8:
array (size=0)
empty
You need to change the way you define your variables in your Javascript and declare them inside your function, not outside :
function formLogin(){
var name = $('#user_name').val();
var lname = $('#user_lastname').val();
$.ajax({ url: 'database/register.php',
data: {
'name' : name,
'lname' : lname
},
type: 'post',
dataType:'json',
success: function(data) {
alert(data);
}
});
}
And you need to update your HTML the same way (formLogin() instead of formLogin(...,...)) :
<form class="circleForm" id="registerForm">
Imię: <input type="text" id="user_name"><br>
Nazwisko: <input type="text" id="user_lastname">
<br>
<input class="btnCircle" type="button" id="submit" value="Przejdź dalej" onclick="formLogin()">
</form>
Try using method instead of type.
The HTML:
<form class="circleForm" id="registerForm">
Imię: <input type="text" id="user_name" name="name"><br />
Nazwisko: <input type="text" id="user_lastname" name="lname"><br />
<input class="btnCircle" type="button" id="submit" value="Przejdź dalej" onclick="formLogin();">
</form>
The JavaScript:
function formLogin() {
// Serialize the form
var data = $('form').serialize();
// Ajax call
$.ajax({
url: 'database/register.php',
data: data,
method: 'post',
dataType: 'json',
success: function(data) {
console.log(data);
}
});
}
Also remember that you're requesting a JSON so you have to echo a json_encode($array) in your PHP file for a simple string will not be returned.

Call change and click event together jquery

I'm not able to access skills value using id while I can access finduserType value.
I don't know why, It should call on change event and click event as well.
$(function() {
$("#findUserType").change(function () {
var user_type = $("#findUserType").val();
var skills = $("#skills").val();
var phone = $("#phones").val();
var src = '{{Request::root()}}/api/user/suggestion/email';
var srcPhone = '{{Request::root()}}/api/user/suggestion/phone';
/* var skills = $("#skills").val();
var phone = $("#phones").val();*/
// Load the Users from the server, passing the usertype as an extra param
$("#skills").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
method: 'GET',
dataType: "json",
data: {
term : skills,
user_type : user_type
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
delay: 300
});
// Load the Users from phone to the server, passing the usertype as an extra param
$("#phones").autocomplete({
source: function(request, response) {
$.ajax({
url: srcPhone,
dataType: "json",
data: {
term : phone,
user_type : user_type
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
delay: 300
});
});
});
<form>
<div class="input-group">
<select class="form-control" id="findUserType" name="finduser">
<option value="">--Select--</option>
<option value="2">D</option>
<option value="3">P</option>
</select>
</div>
<div class="input-group">
<input type="text" id="skills" class="form-control">
<input type="text" id="phones" class="form-control" name="phone">
</div>
</form>
Updated the code please take a look what exactly i'm going to stuck it does not take email's values. When I call ajax change event does work fine but skills value does not have the any value. Also suggest how can i compress this code. I just want to check on change event call ajax base on skills and phone values.
I think this will work better:
$("#findUserType").change(function() {
if ($(this).val() == "") {
$("#textboxes").hide();
} else {
$("#textboxes").show();
}
});
$("#skills").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
method: 'GET',
dataType: "json",
data: {
term: $("#skills").val(),
user_type: $("#findUserType").val()
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
delay: 300
});
// Load the Users from phone to the server, passing the usertype as an extra param
$("#phones").autocomplete({
source: function(request, response) {
$.ajax({
url: srcPhone,
dataType: "json",
data: {
term: $("#phones").val(),
user_type: $("#findUserType").val()
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
delay: 300
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select class="form-control" id="findUserType" name="finduser">
<option value="">--Select--</option>
<option value="2">Doctor</option>
<option value="3">Pharmacy</option>
</select>
<br/>
<div id="textboxes" hidden>
<input type="text" id="skills" class="form-control">
<br/>
<input type="text" id="phones" class="form-control" name="phone">
</div>
</form>
At present your two later autocomplete handlers are not bound until the "findUserType"'s "change" event has happened at least once, because they are declared within that code block. And also if that "change" event happens multiple times then multiple handlers will be attached to the other two elements, and then when those events are triggered, multiple copies of the code will run - I doubt that's what you intended.
The change handler for #skills and the click handler for #phone will only be registered after the first change event firing on #findUserType.
Move those two handlers outside of #findUserType's change handler.
$(document).ready(function(){
$("#findUserType").change(function () {
var user_type = $(this).val();
});
$("#skills").change(function () {
var skills = $(this).val();
var phone = $("#phones").val();
});
$("#phone").change(function () {
var phone = $(this).val();
});
});
I hope you this will help you get the values of skills and phone when user type is selected.

How to get value to the controller from view

I am struggling hard to get value to my controller. Please can some one suggest a way to get value to controller from view. Application is in .Net3.5 and MVC 2 for .Net3.5
The view with jquery and controller is:
The jquery and the html is:
<tr>
<td style ="width: 313px">
<label for="Product Code"> Product
Code
</label>
<select id ="prodList" style = "width:150px">
<option value ="GL ">GL </option>
<option value ="Property" selected="selected">Property </option>
<option value ="Package" >Package </option>
<option value ="Island" >Island </option>
</select>
</td>
<td style="width: 313px"><input type ="button" id="addProd" value ="Add Product" /></td>
</tr>
<script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="/Scripts/jquery-1.4.1.min-vsdoc.js" type="text/javascript"></script>
<script src="/Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("#addProd").click(function() {
//alert("here");
var selectedID = $("#prodList").val();
alert("me 1" + selectedID);
$.ajax({
url: "/WorkFlowTest/ProductSubmission/",
type: 'POST',
data: { productID: $("#prodList").val() },
contentType: 'application/json; charset=utf-8',
success: function(data) {
//alert(data.success);
alert("success");
},
error: function() {
alert("error");
}
});
});
});
</script>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ProductSubmission(string productID, ViewModels.WorkFlowTestViewModel SubmissionModelView)
{
SubmissionModelView.selectedProd = prodSelected ;
return View("Submission", SubmissionModelView);
}
In the jquery function the alert has the selected value, but
for the SubmissionModelView has all properties null and the productId is null too.
Though in browser console I get Source {"productId":"Property"} , but I can not understand why my post does not get any value in the Action ProductSubmission.
Can any one help , I just need the controller to get the selected option value on Post or even a text value on Post. I am not able to get any value from view to controller and my model has also all properties null in POST. Please help
You should convert the object to JSON string by using the JSON.stringify function.
$.ajax({
url: "/WorkFlowTest/ProductSubmission/",
type: 'POST',
data: JSON.stringify({ productID: $("#prodList").val() }),
contentType: 'application/json; charset=utf-8',
success: function(data) {
//alert(data.success);
alert("success");
},
error: function() {
alert("error");
}
});

multipart/form-data using jquery ajax

i have the following form,
<form action="localhost/xyz.aspx" method = "post" enctype="multipart/form-data">
<input type="text" name="name">
<input type="text" name="age">
<input type="text" name="submit">
</form>
My requirement is to complete the action using AJAX & jQuery and without a form tag explicitly added in html.
TIA
update1
i have tried
function onButtonClicked()
{
$.ajax({
type: 'POST',
url: "xyz.aspx",
data : {"name" : "john", "age" : "22"},
crossDomain : true,
beforeSend: function (x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("multipart/form-data");
}
},
success: function(data){
alert("Success");
},
error: function(data){
alert("on start process error");
}
});
}
sample.html
<html>
<body>
<input type="button" onclick = "onButtonClicked()">
</body>
</html>
It returns Unsupported Media Type 415.
I want send form data using ajax
You can select the individual inputs and use them in an array to post. This way doesn't need a wrapper:
// Click button with ID #submit
$("button#submit").click(function () {
// Send to submit.php
$.post("submit.php", {
// Send these values via POST
val1: $("#val1").val(), // Get value from input #val1
val2: $("#val2").val() // Get value from input #val2
}, function(result){
// Output result to #output element
$('#output').html(result);
});
});

Categories