how to send multiple value from client to server using ajax json - javascript

I'm trying to send multiple data from client to server using ajax json.
case First: when i send my form inputs data from client to server it was going well.
case second:now one modification done in my form and i am generating dynamic multiple rows with textboxes .and it's values should also pass using same ajax method but my try go in vain so any idea would be appreciated.
Refer below article for more coding part details about this question.
enter link description here
I am trying like this
$(document).on("click", "[id*=btnFrmSubmit]", function () {
alert("hi");
var fields = $("#WireDimTbl tbody").find(":input").serializeArray();
var user = {};
user.PRODUCT_ID = 1;
user.TDC_NO = $("[id*=Tdc_No]").val();
user.REVISION = $("#Revision").text();
$.ajax({
type: "POST",
url: "TDC.aspx/SaveFrmDetails",
data: JSON.stringify({ user: user,fields:fields}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Data has been added successfully.");
window.location.reload();
},
error: function (response) { alert(response.responseText); }
});
return false;
});
At Sever side part what modification should be done.how would i define parameter object with same strucutre at server side and how would i store in db.

Related

Execute a function , after form successfully submitted

I'm trying to alter the registration procedure that WordPress is using by adding another 'step.'
Since I added foreign key constraints in my database tables, wp_users need to be filled first and after executing the rest of the code.
My current code for WordPress form submit interruption is:
jQuery("#registerform").submit(function (e){
e.preventDefault();
let self = jQuery(this);
self.unbind().submit();
setTimeout(function(){
if (jQuery("#registerusingwebauthn").is(":checked")) {
let username = jQuery("#user_login").val();
initializeCredentialType({
authenticationMethod: "webauthn"
});
webauthn_registration(username,null)
.then(function(e){
alert(e);})
.catch(function (e){
console.log(e)});
}
},60000);
});
The self.unbind().submit(); part it's used because the wp_users table must be filled in first, or else a violation of constraints will occur.
The webauthn_registration is returning a new Promise and it's defined as follows:
const webauthn_registration=(username,type)=>{
return new Promise((resolve,reject)=>{
// some variable definition here//
if (username === ""){
reject("Error: Username not given");
}
$.ajax({
url: url,
type: 'GET',
data: {'username': username},
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (error){reject(error);},
success: function(serverregdata){
// some variable definition here//
navigator.credentials.create({publicKey: serverregdata})
.then(function(credentials){
// some variable definition here//
$.ajax({
url: url,
type: 'POST',
data: JSON.stringify(credentials),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (error){alert(error);reject(error);},
success:function(success){alert(success);resolve('success');}
})
});
}
});
});
}
The problem is that setTimeout() doesn't wait until the promise that webauthn_registration is resolved and reloads the page before webauthn_registration is finished.
For some more information (if needed), AJAX is interacting with a python server, and the Tables Constraints are as follow:
wp_users.username is a foreign key to webauthn_users.
webauthn_users.id is a foreign key to webauthn_credentials.
PS
The webauthn_registration function was working fine in a static HTML website that the submit function was directly linked to webauthn_registration.
Welcome to stackoverflow. I would suggest to try the following trick:
$('form').one('submit', function(e) {
e.preventDefault();
// do your things ...
// and when you done:
$(this).submit();
});

Ajax: How to send FormData inside of json object

To give you a better understanding consider my ajax request:
$.ajax({
url: '{% url "validate-upload-single" %}',
type: "POST",
data: JSON.stringify({
'mainForm': Myform,
'currentForm': 1,
}),
dataType: 'json', // response type
Where:
var Myform = new FormData( $(this)[0] );
The problem is that when i send the request, i get back an empty 'dict' on the server side. Im using Django as my backend
DJANGO VIEW:
print('SORTING THE POST REQUEST')
body = request.body.decode('utf-8')
serialized = loads(body)
print(f'POST: {request.POST}')
print(f'Body: {body}')
print(f'Serialized: {serialized}')
RESULT:
SORTING THE POST REQUEST
POST: <QueryDict: {'{"mainForm":{},"currentForm":1}': ['']}>
Body: {"mainForm":{},"currentForm":1}
Serialized: {'mainForm': {}, 'currentForm': 1}
I've tried $("form").serializeArray() but this only return text data, files seem to be missing
I guess the problem is with contentType header - it should be 'multipart/form-data'. Check this link to make it work with jQuery.ajax
In the .js file you HAVE TO add the fist block of csrf token for properly working.
//Getting csrf token
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
Then you use json in you ajax, getting the template that you want to display by variable here "html_form":
// Submit post on submit
$('#post-form').on('submit', function(event){
event.preventDefault();
console.log("form submitted!") // sanity check
//Send data to server for getting back sorted
$.ajax({
url: '/schedule/sort_group/',
async: true,
type: 'post',
data: { //data sent with the post request
group_field_value: $("#select_group").children("#group-option:selected").val(),
lector_field_value: $("#select_lector").children("#lector-option:selected").attr("name"),
},
dataType: 'json',
success: function (data) {
$("#change_by_select").html(data.html_form);
}
});
});
In the views.py file at the bottom you need to determine the data like that:
data['html_form'] = render_to_string('schedule/select_sort.html', context,
request=request)
return JsonResponse(data)
So I suggest the information that you want to retrieve from the server put into the particular another file, whatever it would be (dictionary or lists or other data structures or html templates).
I hope it would help. Feel free to ask any questions.

Auto parsing and formatting JSON property names

I use a script to auto populate form. When user selects an option from dropdown, it makes AJAX request to an external file (which returns data from database using json_encode) and forms gets auto-filled.
Here's the code:
function myrequest(e) {
var name = $('#username').val();
$.ajax({
method: "POST",
url: "autofill.php",
dataType: 'json',
cache: false,
data: {
username: name
},
success: function(responseObject) {
$('#posts').val(responseObject.posts);
$('#joindate').val(responseObject.joindate);
}
});
}
As you see, when dropdown with ID username is changed, AJAX call is made, and form fields with IDs posts and joindate are auto-filled.
However, I want to use the same function for more forms which will have fields with different IDs to be auto-filled (and JSON will return other data, of course). Is there any way to modify this function, so I don't need to write a separate line (like $('#posts').val(responseObject.posts);) for each JSON value to be parsed.
In other words, the function should auto parse returned JSON data and if there's a field with a specific ID, it should be auto filled. So if JSON returns data like {"abc123":"666","some_other_field":"2017-03-06"}, function should find and prefill fields with IDs abc123 and some_other_field accordingly.
I guess something like this could work:
function myrequest(e) {
var name = $('#username').val();
$.ajax({
method: "POST",
url: "autofill.php",
dataType: 'json',
cache: false,
data: {
username: name
},
success: function(responseObject) {
for (var prop in responseObject) {
if (responseObject.hasOwnProperty(prop)) {
$('#' + prop).val(responseObject[prop]);
}
}
}
});
}

Rails: sending ajax object using Jquery and keeping datatype on rails

I'm using Jquery for creating object and sending to server:
data = {};
data.number = 5;
$.ajax({
url: 'some_link',
type: 'POST',
dataType: 'json',
data: data,
success: function() {
alert('data sent');
},
error: function() {
alert('fail');
}
});
And on rails, I test submitted param by:
params[:number] => "5"
How can I force rails to understand 5 instead of "5". Because I send a large bunch of data, I cannot manually do conversion.
Thanks
If you need to save to a database, then your model should have the attribute type set as integer. When you save it, it will automatically coerce the string '5' into the integer 5

How to add local json file in jsfiddle?

How can I add a JSON file in jsfiddle? I have a JSON file but I am not able to attach it in jsfiddle. I can make a JSON object and use it, but is there any way to add an external JSON file to a fiddle?
Myjson.com provides api, which runs in Jsfiddle.net.
Custom my myjson:
// Loading JSON with CROS
var url = 'https://api.myjson.com/bins/3ko1q';
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('success');
console.log(data);
},
error: function (e) {
alert('error');
console.log(e);
}
});
Myjson GET Example:
// 1. Create valid uri via POST
// 2. GET using newly created uri
var obj = {
"key": "value",
"key2": "value2"
};
var data = JSON.stringify(obj);
$("#clickMe").click(function () {
$.ajax({
url: "https://api.myjson.com/bins",
type: "POST",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, jqXHR) {
// load created json
$.get(data.uri, function (data, textStatus, jqXHR) {
var json = JSON.stringify(data);
$("#data").val(json);
});
}
});
});
You can harness the power of Cross-Origin Resource Sharing (CORS) to achieve your task.
Basically how CORS works is that if the Access-Control-Allow-Orign header is set in the HTTP response, then the content loaded by AJAX can be used in our script regardless of the fact it is on the same domain or some other.
Now for your purpose, you can upload your local JSON file to Dropbox's Public folder and get a Public URL, that you can load by a simple AJAX call.
The AJAX call will succeed in this case because Dropbox sets the following value in the response Access-Control-Allow-Orign:* which means any domain can use the loaded content.
Jquery code will be something like this(you can even use pure JavaScript if you prefer ).
var url = 'https://dl.dropboxusercontent.com/u/94145612/example.json';
var myJsonData= {};
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('success');
console.log(data);
myJsonData= data;
},
error: function (e) {
alert('error');
console.log(e);
}
});
Example JSFiddle
Based on your comment, you want to use a pure JSON file as an external resource in a jsFiddle. You can't do this, because pure JSON is not JavaScript. Say you try to include http://example.com/foo.json as an external resource, and that file contains the following:
{"foo":"bar"}
This will result in Uncaught SyntaxError: Unexpected token :, because the JSON object is not valid JavaScript by itself.
But if you assign the JSON object to a variable, like so:
var foo = {"foo":"bar"};
then no problem.
Solution: use a modified version of your file to initialize a variable for use in the jsFiddle.

Categories

Resources