json response get data in div ajax - json

i get the json response in different div
json response
{"success":"you have not inserted","error":{"name":["The name field is required."],"detail":["The detail
field is required."]}}
ajax code
function postdata(){
var name=$('#name').val();
var detail=$('#detail').val();
var token=$('#_token').val();
$('#post').val('Submiting...');
$.ajax({
type: 'GET',
url: 'posts',
data: "name="+ name + "&detail="+ detail,
success: function(data){
} });
}
get json respons message in this div
<div class="alert alert-info col-ssm-12" id="detail"></div>
<div class="alert alert-info col-ssm-12" id="name"></div>

get Values by .text() or .html()
function postdata(){
var name=$('#name').text();
var detail=$('#detail').text();
var token=$('#_token').val();
$('#post').val('Submiting...');
$.ajax({
type: 'GET',
url: 'posts',
data: "name="+ name + "&detail="+ detail,
success: function(data){
} });
}

Related

Binding Ajax Response data into shipping description in Magento2.4.3

I want to bind Ajax response to knockout but I don't know how to do it? can you help me?
delivery: function (postcode) {
var self=this;
$.ajax({
url: url,
data: {postcode: postcode},
type: 'POST',
dataType: 'json',
context: this,
beforeSend: function () {
$(document.body).trigger('processStart');
},
success: function(response) {
console.log(response);
var res = '';
for(var i=0; i < response.data.length; i++){
res = response.data[i]['date'];
$(".test").html(res).trigger('contentUpdated');
}
$(document.body).trigger('processStop');
},error: function(xhr) {
console.log("Error occured.please try again");
},complete: function () {
$(document.body).trigger('processStop');
}
});
}
I am trying to binding data inside knockout html table.
<td class="col col-carrier"
attr="'id': 'label_carrier_' + method.method_code + '_' + method.carrier_code"
text="method.carrier_title" />
<!-- Column with collapsible trigger -->
<td class="col">
<span class="test" data-bind="text: 'here i want to bind'"></span>
</td>

how to pass serialize data and stringified data together in ajax

I have a ajax function where i am passing two objects:
1) serialize form data object
2) complex object
Ajax function:
var temp = sessionStorage.getItem('book');
var viewName = $.parseJSON(temp);
var ViewModel = $("#OffsetBookForm").serialize();
$.ajax({
contentType: "application/json; charset=utf-8",
type: "Post",
url: "#Url.Content("~/Estimate/CreateOrder")",
data: JSON.stringify({ 'OffsetCommonObj': ViewModel, 'obj': viewName }),
dataType: 'json',
success: function (data) {
}
});
And My ActionMethod:
public ActionResult CreateOrder(EstimationOffsetViewModel OffsetCommonObj,
OffsetCostCalculation obj)
{
// do something here..
}
My problem is, the first object in action method i.e-"OffsetCommonObj" is getting null. What am I doing wrong in the code? Please Help..Thanks.

How do I get input from an HTML form and find data?

I have a form like this;
<div id="employeeinfo" style="padding:40px" class="employee-body">
<form id="employeeform" title="" method="post">
<label class="title">First Name</label>
<input type="text" id="fname" name="first_name" >
<label class="title">Last Name</label>
<input type="text" id="lname" name="last_name" >
<input type="submit" id="submitButton" onclick="formSubmit()" name="submitButton" value="Submit">
</form>
</div>
I have a json url: "app.employee.com/employeedata"
I need to get fname and lname from html form and search through the json in above url and display it in
so far i have this:
<script type='text/javascript'>
function formSubmit(){
var formData = JSON.stringify($("#employeeform").serializeArray());
$.ajax({
type: "POST",
url: "serverUrl",
data: formData,
success: function(){},
dataType: "json",
contentType : "application/json"
});
}
</script>
How to proceed with this? I'm doing this in shopify.
You can start with use of the getElementById method.
function formSubmit(){
...
var fname=document.getElementById("fname").value;
var lname=document.getElementById("lname").value;
}
try this way
function formSubmit(){
var fname=$('#fname').val();
console.log('fname',fname);
var lname=$('#lname').val();
console.log('lname',lname);
}
The success function in your ajax call returns data from the server:
success
Type: Function( Anything data, String textStatus, jqXHR jqXHR )
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
Source: jQuery.ajax docs
So what you can do is:
<script type='text/javascript'>
function formSubmit(){
var formData = JSON.stringify($("#employeeform").serializeArray());
$.ajax({
type: "POST",
url: "serverUrl",
data: formData,
success: function(responseData){
// responseData contains the json from the server. You can search this for the firstname and lastname from the form.
},
dataType: "json",
contentType : "application/json"
});
}
</script>
In your case your serializeArray only will fetch all the form data and will return like
[
{
name: "fname",
value: "zydexo"
},
{
name: "lname",
value: "test"
}
]
Then in your back end file you can read the post data.
If you want to get each element value by your own then you need to use:
var fname=document.getElementById("fname").value;
or
var fname=$('#fname').val();
Then
function formSubmit(){
var fname= $("#fname").val();
var lname= $("#lname").val();
$.ajax({
type: "POST",
url: "serverUrl",
data: {fname:fname,lname:lname},
success: function(data){
//
},
dataType: "json",
contentType : "application/json"
});
}

JSON passed to controller has no value

I am unable to get my JSON to my controller, and I can't figure out why the value I get in javascript isn't being passed to the controller. Here is my ajax post in my javascript:
this.save = function () {
var data = ko.toJSON(this.Routines);
$.ajax({
type: 'POST',
url: "CreateJson",
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (!result.success)
alert("test")
else { }
}
})
}
now data contains
[{"routine_name":"new routine","duration":"20","rest":"10","rounds":1}]
which is what I want, but the controller shows nothing. Here is my controller
[HttpPost]
public JsonResult CreateJson(t_routine routine, string data)
{
var message = "success";
return Json(message);
}
As I understand it, MVC 3+ automatically receives JSON without any need for parameters like my string data, I just threw it in there to try and figure out if I'm getting anything at all. data is null and routine shows 0's and null for values. What am I missing?
If t_routine represents the server side type for
[{"routine_name":"new routine","duration":"20","rest":"10","rounds":1}]
Then it might be enough to call JSON.stringify on the ko.toJSON result like this
this.save = function () {
var data = JSON.stringify(ko.toJSON(this.Routines));
$.ajax({
type: 'POST',
url: "CreateJson",
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (!result.success)
alert("test")
else { }
}
})
}
the data parameter on your controller action is not needed then and you most likely need to change the t_routine parameter to t_routine[]

Jquery Autocomplete with json and using parameters

I am trying to do an autocomplete input field. Everytime a user type a letter in that field, the value of the field is sent to the server and the server answer with words that match.
var acOptions = {
source:function (request, response) {
$.ajax({
url: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw",
type: "GET", dataType: "json",
data: { expr: request.term},
success: function (data) {
response($.map(data, function (item) {
return item.value;
}))
}
})
},
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);
This is an example of data from the server:
[{"value":"Greater"},{"value":"great"},{"value":"greatly"},{"value":"Greater-Axe"}]
The previous code do the right request to the server (and the server answer right) but it does not display anything in the text field.
I tried to do the autocomplete without an explicit ajax object but then I couldn't send the current value of the field (parameter "expr" of the request) to the server:
var acOptions = {
source: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw&expr=",
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);
Thank you for your help!
You can use jQuery to pull the value of your field to add it to URL parameter string.
var acOptions = {
source: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw&expr=" + $('#ID_OF_YOUR_TEXTBOX').val(),
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);