How to use dynamic data name with jQuery.post? - javascript

I have 2 basic form used to convert data (type 1 <-> type 2).
I want to do my .post request using only 1 form.
I'm having issue with the [data] parameter for jquery.post
Here's my code :
$('form').submit(function(){
var a = $(this).parent().find("input").attr('name');
var b = $(this).parent().find("input").val();
var url = $(this).attr('action')
$.post(url, { a:b },function(data) {
$(data).find('string').each(function(){
$('.result').html($(this).text());
});
});
return false;
});
The problem lies within {a:b}.
b is interpreted as my var b, but a isn't, making my post parameters something like [a:1] instead of [param:1].
Is there a way to have a dynamic a?

Try this:
var data = {};
data[a] = b;
$.post(url, data, function(data) {
So like this:
$('form').on('submit', function (e) {
e.preventDefault();
var data = {};
var el = $(this);
var input = el.parent().find('input');
var a = input.attr('name');
var b = input.val();
var url = el.attr('action');
data[a] = b;
$.post(url, data, function(data) {
$(data).find('string').each(function(){
$('.result').html($(this).text());
});
});

Yes, use something else for the data post:
$.post(url, a+"="+b,function(data) {
$(data).find('string').each(function(){
$('.result').html($(this).text());
});
});

Related

Sending json via ajax in wordpress using Vanilla JS

I am sending a json in my server using vanilla JS and it returns a bad request, it seems the server only wants a key value pair like 'page=pageData&action=act', when i do this it works, but i would want to send data that way. Is there a way to make it possible?
When i try to make it in jquery it works fine.
$('.more-headlines').on('click', function() {
var pageData = $(this).data('page');
var pageURL = $(this).data('url');
var act = 'load_more';
var jsondata = {
page : pageData,
action : act
}
var xhr = new XMLHttpRequest();
xhr.open('POST', pageURL, true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onload = function() {
if (xhr.status >=200 && xhr.status < 400) {
var data = JSON.parse(xhr.responseText);
console.log(data);
} else {
console.log('sad');
}
};
xhr.send(JSON.stringify(jsondata));
});
This is my code in jquery
$('.more-headlines').on('click', function () {
var that = $(this);
pageData = $(this).data('page');
newPage = pageData+1;
pageURL = $(this).data('url');
act = 'load_more';
that.addClass('icon-spin');
that.find('span').html('loading headline');
jsondata = {
page : pageData,
action : act
}
$.ajax ({
type: 'POST',
url: pageURL,
data: jsondata,
success: function(response) {
setTimeout( function () {
that.data('page', newPage);
$('#featureOnDemand ul').append(response);
that.removeClass('icon-spin');
that.find('span').html('See more headlines');
}, 500);
}
});
});
I looked at the network tab in chrome and i saw that the send request becomes a key value pair like 'page=pageData&action=act'.
I am stuck in this part because i want to make a vanilla js ajax request in my project. Any idea would be much appreaciated. Many thanks!
You want to serialize your object data. Here's a helper function you can pass your object into:
var serializeObject = function (obj) {
var serialized = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
serialized.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}
}
return serialized.join('&');
};

Passing URL query strings into HTML form fields using Javascript

I have always used PHP for passing query strings into forms, but I am looking to move to a static site scenario and need the query data from a URL to populate the form fields.
I have the code with no console errors, but the data is not passing into the form fields. Does anyone know how this can be done that works across all modern and legacy browsers?
function getQueryString() {
var result = {};
if(!window.location.search.length) return result;
var qs = window.location.search.slice(1);
var parts = qs.split("&");
for(var i=0, len=parts.length; i<len; i++) {
var tokens = parts[i].split("=");
result[tokens[0]] = decodeURIComponent(tokens[1]);
}
return result;
}
$(document).ready(function() {
$("#theForm").submit(function(e) {
//var that = this;
var qs = getQueryString();
for(var key in qs) {
var field = $(document.createElement("input"));
field.attr("name", key).attr("type","hidden");
field.val(qs[key]);
$(this).append(field);
}
});
});
https://formpopulate.netlify.com/index.html?name=john&email=john#aol.com
https://formpopulate.netlify.com/
You should use URL seachParams:
var params = (new URL("https://example.com/?name=Jonathan&age=18&test=a%20long%20string")).searchParams;
var name = params.get("name"); console.log(name); // is the string "Jonathan"
var age = parseInt(params.get("age")); console.log(age);// is the number 18
var test = params.get("test"); console.log(test); // is a long string

Get closest tr inside function js

I have this js code :
$(".contenteditable").keyup(function(){
var data = $(this).text();
var domId = document.activeElement.id;
var userId = $(this).closest('tr').find('[type="hidden"]:first').val();
$.post
(
"/users/"+userId,
{
data,domId,userId,'_method':'patch'
},
function(data)
{
console.log(data);
}
)
});
Its working ok. However, now I want to make it as function and use it for any page I tried like this:
function keyUpUpdate()
{
var data = document.activeElement.textContent;
var domId = document.activeElement.id;
var userId = $(this).closest('tr').find('[type="hidden"]:first').val();
console.log(userId);
}
The userId is not working inside this function.
How can I get the closest tr and then the first input type hidden value from the active element inside function.
this has no context inside your function you should send the current object to the keyUpUpdate() as parameter then get userId based on this object :
$(".contenteditable").keyup(function(){
keyUpUpdate($(this));
//Other code
})
function keyUpUpdate(_this)
{
var data = document.activeElement.textContent;
var domId = document.activeElement.id;
var userId = $(_this).closest('tr').find('[type="hidden"]:first').val();
console.log(userId);
}
Or if you've just this function to execute on keyup you could call it directly then the this object will be passed dynamically :
$(".contenteditable").keyup(keyUpUpdate);
function keyUpUpdate()
{
var data = document.activeElement.textContent;
var domId = document.activeElement.id;
var userId = $(this).closest('tr').find('[type="hidden"]:first').val();
console.log(userId);
}
Hope this helps.

Run Javascript function before jQuery functions

I am trying to be able to get my form to check if the 2 input boxes have any data input into them before it submits. The reason I am having trouble with this is because I am using the following -
$('form.ajax').on('submit', function () {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function (index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: method,
data: data,
})
this.reset();
return false;
});
This makes it so the form is submitted without the page having to refresh, I also have an image appear for a few seconds when the submit button has been pressed -
$(".bplGame1Fade").click(function(){
$("#bplGame1ThumbUp").fadeIn(1000);
$("#bplGame1ThumbUp").fadeOut(1000); });
I don't want these to run unless both the input boxes have data in them. I have tried using OnClick() and OnSubmit(). When using these the message appears saying it isn't a valid entry as I want but once you click OK the form continues to submit.
Is there anyway I can run a JS function to check the input boxes and if one of the boxes is empty, cancel the submission.
Any help with this would be appreciated,
Thanks.
Why dont you just add an if condition to check if you ever get an empty input? You can return the function if it's not valid.
$('form.ajax').on('submit', function () {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
var context = this;
var valid = true;
var total = that.find('[name]').length;
that.find('[name]').each(function (index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
if (!value) {
valid = false;
return;
}
data[name] = value;
if (index === total - 1) { //last item
if (valid) {
$.ajax({
url: url,
type: method,
data: data,
});
context.reset();
}
}
});
});
EDIT: You could put the ajax call inside of the foreach. So on the last item, you would make the ajax call if every input had a value.

Json stringify double quotes

I can't seem to get around this issue... Json I'm trying to pass to an MVC Controller keeps coming out like this
"\"{MaterialQuantity: { MaterialID :18, Quantity:1}}\""
This is the code that generates it:
function CreateJsonForQuantities() {
var inputs = $('input[name=MaterialQuantity]');
var total = inputs.length;
var data = "";
inputs.each(function (index) {
data = data + $(this).val();
if (index != total -1)
data = data + ',';
});
return data;
}
And this is the hidden which it reads data from (of course this is auto-generated as well)
<input name="MaterialQuantity" type="hidden" value="{MaterialQuantity: { MaterialID :12, Quantity:5}}" />
What am I doing wrong?
UPDATE
Ok so now I'm properly getting json object and my ajax requests looks like this. Problem now is that it does pass proper objects but all values are null in the controller action :(
var form_data = CreateJsonForNorm();
var quantity_data = CreateJsonForQuantities();
var data = { norm: form_data, mqvm: quantity_data };
$.ajax({
type: "POST",
url: form.attr("action"),
data: data,
success: function () {
location.href = "#Url.Action("Index")";
('#addDialog').dialog("close");
},
error: function () {
alert("Error");
}
});
Try using JSON.stringify(data) in your request

Categories