Auto parsing and formatting JSON property names - javascript

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

Related

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

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.

How can I pass JavaScript variable value in php with same page using modal window

Here is my Javascript for fetching value to input box,
$('#edituserModal').on('show.bs.modal', function(e) {
var userid = $(e.relatedTarget).data('userid');
var u_id = document.getElementById('hdn_user_id').value = userid;
alert(userid);
});
I want this value to use for SQL query in modal window which is on same page.
I fetched value in modal window but unable to use it. What the format to use it.
You can pass js variable into php page using ajax.
$('#edituserModal').on('show.bs.modal', function(e) {
var userid = $(e.relatedTarget).data('userid');
var u_id=document.getElementById('hdn_user_id').value=userid;
$.ajax({ //create an ajax request to load page.php
type: "GET",
url: "page.php",
data:"varabletophp="+u_id, //Here is the value you wish to pass in to php page
dataType: "html", //expect html to be returned
success: function(response){
alert(response);
}
});
});
No you can get this variable into your page.php (php page) using
$fromjs=$_GET['varabletophp'];
echo $fromjs;
you can use input hidden and set userid value in on this input so , post form
Varying modal content based on trigger button :
http://getbootstrap.com/javascript/#modals-related-target
var data = new FormData($('form#' + formId)[0]);
$.ajax({
type: "POST",
url: url,
data: data,
cache: false,
processData: false,
contentType: false,
beforeSend: function () {
},
success: function (response) {
},
error: function (response) {
}
});

I am Unable to Parse a JSON in JQuery

I have My jquery function that is returning me data of the formatt:
{"Suggestions":[{"name":"RR Restaurant","category_id":"166","locality":"Gayathri Nagar","listing_info":"listing","random_id":"1ll0f0wJ"},{"name":"Oko Restaurant","category_id":"166","locality":"Kumara Krupa","listing_info":"listing","random_id":"0F7ZGV9p"},{"name":"H2O Restaurant","category_id":"166","locality":"Maratha Halli","listing_info":"listing","random_id":"0JNPOyuP"},{"name":"Taj Restaurant","category_id":"166","locality":"Shivaji Nagar","listing_info":"listing","random_id":"7GeA0Kfq"},{"name":"PSR Restaurant","category_id":"166","locality":"Peenya Industrial Area","listing_info":"listing","random_id":"cRvJCwQ3"},{"name":"ac restaurant","category_id":"166","listing_info":"keyword"},{"name":"Indian Restaurant","category_id":"166","listing_info":"keyword"},{"name":"goan restaurant","category_id":"166","listing_info":"keyword"},{"name":"thai restaurant","category_id":"166","listing_info":"keyword"},{"name":"andhra restaurant","category_id":"166","listing_info":"keyword"}],"ImpressionID":"test"}
I wish to parse the same to get multiple variables with The field "Name" and "Random Id" in different js variables
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
My JSON object seems to be nested with "Suggestions" as the parent. Please help.
If you add a property to $.ajax function you be ensure that is json parsing:
dataType: 'json'
EDIT
To iterate above the string you can use for(in) or each() jquery
json = "[{'key':'value'},{'key':'value']";
for(var i in json) {
console.log(json[i]);
//if you see in console [OBJECT Object] you are
//in a new object you must to iterate nested of this.
}
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
dataType: "JSON", //You need this to be inserted in your ajax call.
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
After insert dataType you can probably do this.
console.log(data.Suggestions);
Also take a look at the API Doc at below url regardless of dataType.
http://api.jquery.com/jquery.ajax/
The data object you are specifying is what will be sent as the arguments to your success method, if you use the GET method.
$("#what).on("keypress", function() {
$.get("/AutoComplete.do", function(response) {
var data = JSON.parse(response);
//data.suggestions = [lots of objects];
//data.suggestions[0].locality = "Gayathri Nagar"
});
});

Ajax query string not being posted to ASP.NET controller

I have this Ajax function:
UpdateFIConfig: function ($appForm) {
var valid = $appForm.valid();
//if not valid the validate plugin will take care of the errors
if (valid) {
$appForm.serialize();
$.ajax({
url: '/IdentifiConfig/DefaultConfiguration/UpdateFIConfig',
data: $appForm,
dataType: 'application/json',
cache: false,
type: 'POST',
success: function (data) {
if (data.Error) {
cc.jqUtils.openDialog(data.ErrorDescription, 'Error', 'OK', null, null, null);
} else {
window.location.href = '/IdentifiConfig/DefaultConfiguration';
}
}
});
}
},
Which serializes data sent from my view into a query string. I know the data is serialized correctly because I have viewed the string with console.log($appForm), and it's correct.
However, my controller never receives the query string. I have removed a lot of code, but this is basically what the controller function looks like:
[HttpPost]
public ActionResult UpdateFIConfig(string query)
{
NameValueCollection nvc = HttpUtility.ParseQueryString(query);
System.Diagnostics.Debug.WriteLine(nvc);
}
I receive a null pointer on the line which tries to parse the query string, and I don't know why. Any help?
i have the same thing ajax in my project the only different is i don't use dataType
but contentType: "application/json; charset=utf-8"
data: "{'query' : '" + $appForm + "'}"
This bit:
$appForm.serialize();
Returns a string that you're never using. serialize won't actually modify the form. You should assign it to a variable and pass that up instead:
var data = $appForm.serialize();
$.ajax({
url: '/IdentifiConfig/DefaultConfiguration/UpdateFIConfig',
data: data,
/* etc */
});
There is probably a better way, but I get around this annoyance by accepting an Object with a string property instead of just a string. So do something like:
[HttpPost]
public ActionResult UpdateFIConfig(MyTypeWithQry query)
{ ...
and
$.ajax({ url: '/IdentifiConfig/DefaultConfiguration/UpdateFIConfig',
data: { 'query' : $appForm },
dataType: 'application/json',
...

How can I pass hidden values through an ajax call using jQuery?

I have a form that uses google docs and when you submit it will go to googles default thank you page. What I want to do is use ajax instead to send the data so the user won't leave the site. Google requires certain hidden fields for their end. How can I pass hidden fields in ajax? Below is the code I wrote.
$.ajax({
type: "post",
url: "https://spreadsheets.google.com/formResponse?formkey=HEREISWHEREMYKEYGOES",
data: "name=entry.1.group&value=24",
success: function() {
alert("yay")
},
error: function(e) {
console.log(e);
}
});
If you want to add fields to a string in javascript, you can use below code. Make sure to replace Whateverfield to the actual field, but I would need to see the HTML to provide a full answer.
formKey = $('Whateverfield').val();
$.ajax({
type: "post",
url: "https://spreadsheets.google.com/formResponse",
data: "name=entry.1.group&value=24&formkey=" + formKey,
success: function() {
alert("yay")
},
error: function(e) {
console.log(e);
}
});
Ideally, you use something like this for the data:
data: {
name: "entry.1.group",
value: "24",
formKey: $('Whateverfield').val()
},
You just need to pass its value through data parameter as in code below:
$.ajax({
type: "post",
url: "https://spreadsheets.google.com/formResponse?formkey=HEREISWHEREMYKEYGOES",
data: { name="entry.1.group", value= "24", hidden1 = $('#hidden_id').val(), hidden2 = $('#hidden_id2').val() },
success: function() {
alert("yay")
},
error: function(e) {
console.log(e);
}
});
Just pass the hidden fields in the data parameter. e.g.
..
data: {
..
hiddenField1: "hiddenValue1",
hiddenField2: "hiddenValue2",
..
}

Categories

Resources