Need help logging errors from Ajax form submission - javascript

I am working on a simple form that is sending data to a customers lead management database via their API. The form returns a 400 error when their is a duplicate email entered into the system. When this or other issues happen I need to be able to throw an error in the console and log the error in a text file within my Wordpress Child theme. I can not seem to get the error to report in the console as well as how to send the error to a txt file. If the form submits okay then everything works, I get a 200 and the lead goes in. Here is what I have so far:
<form class="mbform" id="base_form" action="<?php echo admin_url('admin-ajax.php'); ?>" method="post">
<div class="field">
<input for="base_form" id="first-name" type="text" name="base_fname" placeholder="First Name*" required><br>
</div>
<div class="field">
<input for="base_form" id="last-name" type="text" name="base_lname" placeholder="Last Name*" required><br>
</div>
<div class="field">
<input for="base_form" id="email" type="text" name="base_email" placeholder="Email*" required><br>
</div>
<div class="field">
<input for="base_form" id="phone" type="tel" pattern="[(]\d{3}[)][\s]\d{3}[\-]\d{4}" name="base_phone" placeholder="Mobile*" required><br>
</div>
<input type="hidden" name="action" value="custom_action">
<div class="field submit-button">
<button class="button mbgo" for="base_form" type="submit" name="base_submit">Claim Offer</button>
</div>
</form>
<script>
jQuery(document).ready(function($) {
$('#base_form').on('submit', function(e) {
e.preventDefault();
var $form = $(this);
var settings = {
"url": "https://apiendpoint.com/api/WorkOrder/PostAllWorkOrder",
"method": "POST",
"timeout": 0,
"headers": {
"Authorization": "Bearer jTs1OCFtj5HRhYJmqRjbO35F0x0BnAmyV05hTLUzZjTbXWbfvmhhDXCp4oU8Zg9_Ec6z34n5nkCQOLRMPsK4JnM_NZiVFJGf6DRxkWQt4DzOfFhT06q2KalQrrmA5WoykVLLIE5RR8A1m34TUK37gh4E08zwC3hwW4rnQfIhez30MLDCR-PWEXTfhP5DugjzCrzoR05B15ggXt3OxoRNKxeWgcCw6Q6-E5Cl6Wlkge5iiH3DKoUqAn2tJ1m2UlXobWXSG86o3yfQsPfI7966Uy5zGU7UGB4RTD-Cz8I2U2PC7a4L-TK6UbAem2d2zfusYor81iuMcHfRCsZm60YCtGfbatuYxGXe7HCHmH6mtU8S-aGPJFhpdcyjsa7lx44_KhYzR6EsnKixgu26Wu-qnHmbKaBBKDdqZBMxrJo4tNVM9772WfjdNQpKIDfytZCWQj-iyhmerqdg9mIt3v9Ez79LKliPXXhFkgoESECKhMaHUNLX",
"Content-Type": "application/json",
"Cookie": ".AspNet.Cookies=3iF1xtlsAqyPyTxheHIYgFkvYtepDaZk8UnqLYbkezCdSGVSFCaQwl_9JqTJ8UJ8ytHZ5zrS-vwc3bkbwbJjjZdjn6gRKAMuUG6S2ANvUX94GoIC0-RGW_gXbr2aA-Qle4f8KnPRFKF0BEIBV0Kacxk51u7wBOyJiR7XGSVfrNq5F-fVTAnkrX4o8S0YLm7HC8WhyLgGMlpy6IhmXUplvwMbeQ7y9ZkSizGl9ETrYSr4vYP3tj7hAS-JCvsXm_UaI705bl_lo_iFdbrKaTAN9CONVV-KV1WpmGx-n3J__731wyr20_V1pBy4szbZ2rXych_Ik-b2kiVhj3zikE7q4iiL4k8wD8DiFHYQC_DnqbwFG0hKqs-YU5EEb-0TYSW3mChFUbVVJpEiJ5wxYpmO8Lni9JsNTf_baf-_QYWVRXaE5P5vnfN9gJHIm3Me6oFdvpo3YIPSm6Yci--LDUVeiLtTg10"
},
"data": {
"FRANCHISEID": 1,
"WSTicketNumber": "487260",
"SERVICETYPEID": 0,
"LeadSourceId": "1",
"Note": "N/A",
"IsLeadOnly": true,
"Customer": {
"FirstName": jQuery("#first-name").val(),
"LastName": jQuery("#last-name").val(),
"Address": null,
"Address2": null,
"City": null,
"State": null,
"PostalCode": null,
"Email": jQuery("#email").val(),
"Phone": jQuery("#phone").val(),
"PhoneType": "Cell Phone",
"PreferredCommunicationType": "phone",
"MemberSecondaryIndexCode": "50"
}
}
};
var allData = settings.data.Customer;
$.ajax(settings).done(function (response) {
console.log(response);
$("#error").html("<div id='message'></div>");
$("#message")
.html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
});
$.ajax(settings).fail(function (response) {
console.log(response);
console.log(allData);
var message = allData.FirstName;
$("#error").html("<div id='message'></div>");
$("#message")
.html("<h2>There was an issue with your recent submission</h2>")
.append("<p>" + message + "</p>")
});
});
$("input[name='base_phone']").keyup(function() {
$(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d+)$/, "($1) $2-$3"));
});
});
</script>

Consider the following.
jQuery(document).ready(function($) {
$('#base_form').on('submit', function(e) {
e.preventDefault();
var $form = $(this);
var settings = {
"url": "https://apiendpoint.com/api/WorkOrder/PostAllWorkOrder",
"method": "POST",
"timeout": 0,
"headers": {
"Authorization": "Bearer jTs1OCFtj5HRhYJmqRjbO35F0x0BnAmyV05hTLUzZjTbXWbfvmhhDXCp4oU8Zg9_Ec6z34n5nkCQOLRMPsK4JnM_NZiVFJGf6DRxkWQt4DzOfFhT06q2KalQrrmA5WoykVLLIE5RR8A1m34TUK37gh4E08zwC3hwW4rnQfIhez30MLDCR-PWEXTfhP5DugjzCrzoR05B15ggXt3OxoRNKxeWgcCw6Q6-E5Cl6Wlkge5iiH3DKoUqAn2tJ1m2UlXobWXSG86o3yfQsPfI7966Uy5zGU7UGB4RTD-Cz8I2U2PC7a4L-TK6UbAem2d2zfusYor81iuMcHfRCsZm60YCtGfbatuYxGXe7HCHmH6mtU8S-aGPJFhpdcyjsa7lx44_KhYzR6EsnKixgu26Wu-qnHmbKaBBKDdqZBMxrJo4tNVM9772WfjdNQpKIDfytZCWQj-iyhmerqdg9mIt3v9Ez79LKliPXXhFkgoESECKhMaHUNLX",
"Content-Type": "application/json",
"Cookie": ".AspNet.Cookies=3iF1xtlsAqyPyTxheHIYgFkvYtepDaZk8UnqLYbkezCdSGVSFCaQwl_9JqTJ8UJ8ytHZ5zrS-vwc3bkbwbJjjZdjn6gRKAMuUG6S2ANvUX94GoIC0-RGW_gXbr2aA-Qle4f8KnPRFKF0BEIBV0Kacxk51u7wBOyJiR7XGSVfrNq5F-fVTAnkrX4o8S0YLm7HC8WhyLgGMlpy6IhmXUplvwMbeQ7y9ZkSizGl9ETrYSr4vYP3tj7hAS-JCvsXm_UaI705bl_lo_iFdbrKaTAN9CONVV-KV1WpmGx-n3J__731wyr20_V1pBy4szbZ2rXych_Ik-b2kiVhj3zikE7q4iiL4k8wD8DiFHYQC_DnqbwFG0hKqs-YU5EEb-0TYSW3mChFUbVVJpEiJ5wxYpmO8Lni9JsNTf_baf-_QYWVRXaE5P5vnfN9gJHIm3Me6oFdvpo3YIPSm6Yci--LDUVeiLtTg10"
},
"data": {
"FRANCHISEID": 1,
"WSTicketNumber": "487260",
"SERVICETYPEID": 0,
"LeadSourceId": "1",
"Note": "N/A",
"IsLeadOnly": true,
"Customer": {
"FirstName": jQuery("#first-name").val(),
"LastName": jQuery("#last-name").val(),
"Address": null,
"Address2": null,
"City": null,
"State": null,
"PostalCode": null,
"Email": jQuery("#email").val(),
"Phone": jQuery("#phone").val(),
"PhoneType": "Cell Phone",
"PreferredCommunicationType": "phone",
"MemberSecondaryIndexCode": "50"
}
}
};
var allData = settings.data.Customer;
var request = $.ajax(settings).done(function(response) {
console.log(response);
$("#error").html("<div id='message'></div>");
$("#message")
.html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
});
request.fail(function(response) {
console.log(response);
console.log(allData);
var message = allData.FirstName;
$("#error").html("<div id='message'></div>");
$("#message")
.html("<h2>There was an issue with your recent submission</h2>")
.append("<p>" + message + "</p>")
});
});
$("input[name='base_phone']").keyup(function() {
$(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d+)$/, "($1) $2-$3"));
});
});
This will Assign handlers immediately after making the request, and remember the jqXHR object for this request.
See More: https://api.jquery.com/jquery.ajax/

Related

Display json data in html table using jQuery

How to display json data in html table using jQuery ? and How can i remove case sensitive while searching the result?
expected output
How can i display the result in my table? How can i achieve this?
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}
];
/* Get Result */
function getResult() {
/* Read value from input fields */
var skills = $("#skills").val() || '',
email = $("#email").val() || '',
username = $("#username").val() || '';
var result = [],
i;
for (i = 0; i < data.length; i++) {
if ((skills !== '' && data[i]["skills"].indexOf(skills) !== -1) || (data[i]["email"] === email) || (
data[i]["username"] === username)) {
result.push(data[i]);
}
}
return result;
};
$('#submit').click(function onClick() {
var output = getResult();
console.log(output);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="skills" type="text" placeholder="skills">
<input id="email" type="email" placeholder="mail id">
<input id="username" type="text" placeholder="username">
<input id="submit" type="submit" value="submit">
You need to create a table and need to append coming data to this table using below code:-
$('#submit').click(function onClick() {
var output = getResult();
var html = '';
$.each(output,function(key,value){
html +='<tr>';
html +='<td>'+ value.username + '</td>';
html +='<td>'+ value.email + '</td>';
html +='<td>'+ value.skills + '</td>';
html +='</tr>';
});
$('table tbody').html(html);
});
To do case-insensitive comparison use .toUpperCase()
Working snippet:-
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}
];
/* Get Result */
function getResult() {
/* Read value from input fields */
var skills = $("#skills").val() || '',
email = $("#email").val() || '',
username = $("#username").val() || '';
var result = [],
i;
for (i = 0; i < data.length; i++) {
if ((skills !== '' && data[i]["skills"].toUpperCase().indexOf(skills.toUpperCase()) !== -1) || (data[i]["email"].toUpperCase() === email.toUpperCase()) || (
data[i]["username"].toUpperCase() === username.toUpperCase())) {
result.push(data[i]);
}
}
return result;
};
$('#submit').click(function onClick() {
var output = getResult();
var html = '';
$.each(output,function(key,value){
html +='<tr>';
html +='<td>'+ value.username + '</td>';
html +='<td>'+ value.email + '</td>';
html +='<td>'+ value.skills + '</td>';
html +='</tr>';
});
$('table tbody').html(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="skills" type="text" placeholder="skills">
<input id="email" type="email" placeholder="mail id">
<input id="username" type="text" placeholder="username">
<input id="submit" type="submit" value="submit">
<br>
<table>
<thead>
<tr>
<th>Username</th>
<th>Email ID</th>
<th>Core Skills</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
You can use Data-table jQuery plugin to generate table from jsondirectly like
$('#tableId').DataTable({
data: jsonData,
columns: [
{ data: 'username',title:'Username'},
{ data: 'emailId',title:'EmailId'},
{ data: 'skils',title:'Core Skills'}
],
"search": {
"caseInsensitive": false
}
});
For More detail follow Data-table jQuery Plugin.
Here is the code
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}
];
function BindDataToTable(d,obj){
var keys=Object.keys(d[0]);
var table=document.createElement("table");
var trHead=document.createElement("tr");
jQuery(keys).each((index,item)=>{
var th=document.createElement("th");
th.innerHTML=item;
trHead.appendChild(th)
})
table.appendChild(trHead)
for(var i=0;i<d.length;i++){
var tr=document.createElement("tr");
jQuery(keys).each((index,item)=>{
var td=document.createElement("td");
td.innerHTML=d[i][item];
tr.appendChild(td)
})
table.appendChild(tr)
}
jQuery(obj).append(table);
}
BindDataToTable(data,"#tableElement")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="skills" type="text" placeholder="skills">
<input id="email" type="email" placeholder="mail id">
<input id="username" type="text" placeholder="username">
<input id="submit" type="submit" value="submit">
<div id="tableElement">
</div>

How to display the JSON data in a table depending on search?

I'm trying to display the data in the table depending on search. How can I achieve this?
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}
]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="skills">
<input type="email" placeholder="mail id">
<input type="text" placeholder="username">
<input type="submit" value="submit">
Expected o/p:
search any field ex:
input: java,
output :john and jane profiles
input:sql
output: only jane profile //he is the person who has sql skill
if nothing matches show 0 results
User can search using any one field, if any one item matches that profile should be displayed in my table. How can I do this? Can anyone please help me sort it out?
/* Dataset*/
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}];
/* Get Result */
function getResult() {
/* Read value from input fields */
var skills = $("#skills").val() || '',
email = $("#email").val() || '',
username = $("#username").val() || '';
var result = [],
i;
for(i = 0; i < data.length; i++) {
if ((skills !== '' && data[i]["skills"].indexOf(skills) !== -1) || (data[i]["email"] === email) || (data[i]["username"] === username)) {
result.push(data[i]);
}
}
return result;
};
$('#submit').click(function onClick() {
console.log(getResult()); // print expected data
});
<script
src=
"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input id="skills" type="text" placeholder="skills">
<input id="email" type="email" placeholder="mail id">
<input id="username" type="text" placeholder="username">
<input id="submit" type="submit" value="submit">
in ES6 you can do it :
results = array.filter (x=>x.username.search(search_txt));
let my_list = [{"username":"John Doe","email":"jn#gmail.com","skills":"java,c,html,css"},{"username":"Jane Smith","email":"js#gmail.com","skills":"java,sql"},{"username":"Chuck Berry","email":"cb#gmail.com","skills":"vuejs"}];
results = my_list.filter (x => x.skills.search('java')!=-1);
console.log(results);
//result is : [{"username":"John Doe","email":"jn#gmail.com","skills":"java,c,html,css"},{"username":"Jane Smith","email":"js#gmail.com","skills":"java,sql"}]
<!DOCTYPE html>
<html>
<head>
<title>SEARCH</title>
</head>
<body>
<input type="text" placeholder="skills" id="skills">
<input type="email" placeholder="mail id" id="email">
<input type="text" placeholder="username" id="username">
<input type="submit" value="submit" id="submit">
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Skills</th>
</tr>
<tr id="search">
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}];
$('#submit').click(function(){
var skills = $('#skills').val();
var email = $('#email').val();
var username = $('#username').val();
if(username){
search(username);
}
});
function search(username){
var name = username;
var html ;
data.forEach(function(currentValue, index, array){
if(currentValue.username == name){
html = "<td>"+currentValue.username+"</td>"+
"<td>"+currentValue.email+"</td"+
"<td>"+currentValue.skills+"</td>"
;
}else{
html = "Result Not Found";
}
});
return $('#search').html(html);
}
</script>
</body>
</html>
You can make a search function for skills like this:
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}];
var skills = "java,c";
function search(){
result = [];
var setSkills = skills.split(","); console.log(setSkills);
data.map((current,index)=>{
let currentSkills = current.skills.split(","); //console.log(currentSkills);
// currentSkills = ["java", "c", "html", "css"]
// setSkills = ["java", "c"] ;
// length of set currentSkills == length of set (currentSkills + setSkill) --> mean setSkills is subset of currentSkills
let bool = Array.from(new Set(currentSkills) ).length == Array.from(new Set(currentSkills.concat(setSkills)) ).length;
if(bool)
console.log(data[index]);
});
}
<input type="text" placeholder="skills">
<input type="email" placeholder="mail id">
<input type="text" placeholder="username">
<input type="submit" onclick="search();" value="submit">

How can I able to display the JSON data in an inner array by using vueJS?

My vueJS code is:
<script>
new Vue({
el: '#feed' ,
data: {
data: [],
},
mounted() {
this.$nextTick(function() {
var self = this;
var id = window.location.href.split('=').pop();
console.log(id);
$.ajax({
url: "https://n2s.herokuapp.com/api/post/get/5",
method: "GET",
dataType: "JSON",
success: function (e) {
if (e.status == 1) {
self.data = e.data;
console.log(e.data)
} else {
console.log('Error occurred');
}
}, error: function(){
console.log('Error occurred');
}
});
});
},
})
</script>
This is my html code to display values
<div class="m-single-article" id="feed">
<p>{{details.bussinessName}}</p> //already printed
<p>{{details.pid}}</p> //already printed
<p>{{details.inventory}}</p> //////NOT PRINTING
<p>{{details.sub_category}}</p> ////// NOT PRINTING
</div>
I AM ABLE TO PRINT ALL THE DATA expect INVENTORY AND SUBCATEGORY. please
The url will provide the json data as:
{"status": true, "data": {"pid": 10, "bussinessName": "Ey technology", "services": "1, 3, 4, 2", "inventory": ["specs", "Eye Testing", "Lens", "Doctors"], "workHr": "Monday :9:00AM to 5:00PM,Thuesday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM to 5:00PM", "description": "Good technology company for software", "category": 1, "sub_category": ["Homeo pathy", "Web development"], "lat": 9.5274336, "lon": 76.8224309, "contactName": "simon", "contactEmail": "simon#gmail.com", "contactOfficeAddress": "korno solutions", "contactNumber": "1236547859", "contactOfficeNumber": "858547896", "state": "Canada", "city": "Oranto", "place": "Orania", "pincode": 895621, "referer": 24, "link": 24, "views": 0, "package": 1, "listing_pic": "default", "website": "www.ey.com"}}
By trying this I am not able to display the values of inventory [] and subcategory []. Can anybody please help me to solve my issue.
Also I am getting services as 1,2,3,4. Is there any way to map to the another json data giving name of the services. https://n2s.herokuapp.com/api/post/get_all_services/
You need v-for.
new Vue({
el: '#feed' ,
data: {
details: [],
},
mounted() {
this.$nextTick(function() {
var self = this;
var id = window.location.href.split('=').pop()
console.log(id)
$.ajax({
url: "https://n2s.herokuapp.com/api/post/get/5",
method: "GET",
dataType: "JSON",
success: function (e) {
if (e.status == 1) {
self.details = e.data;
console.log(e.data)
}
else
{
console.log('Error occurred');}
}, error: function(){
console.log('Error occurred');
}
});
})
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="m-single-article" id="feed">
<p>{{details.bussinessName}}</p>
<p>{{details.pid}}</p>
<p v-for="inv in details.inventory">{{inv}}</p>
<p v-for="sub in details.sub_category">{{sub}}</p>
</div>

Autocomplete search box

I followed a video tutorial but I failed to output the result regardless many hours works. The output I expect is when user type some name to search for a company for example, companies' name will be show as a suggestion list. After select a certain company, more details of the company will be shown such as location, opening hours. I attach my HTML, JavaSCript and example JSON file here.
<body>
<div id="searcharea">
<label for="search">Ajax search</label>
<p> enter the name </p>
<input type="search" name="search" id="search" placeholder="company
name" />
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src="script.js"></script>
</body>
</html>
$(#search).keyup(function() {
var searchFiled = $('#search').val();
var myExp = new RegExp(searchField, "i");
$.getJSON('mylist.json', function(data) {
var output = '<ul class="searchresults">';
$.each(data, function(key, val) {
if (val.user.search(myExp) != -1) {
output += '<li>';
output += '<h2>' + val.company + '</h2>';
output += '</li>';
}
});
output += '</ul>';
$('$update').html(output);
});
});
{
"data": [{
"user_id": "1",
"name": "Lala",
"address": "somewhere on the world",
"company": "big company",
}, {
"user_id": "2",
"name": "Tom",
"address": "USA",
"company": "CocaCola",
}]
"reminds": 0,
"message": "this is a message",
"myID": 0
}

JQuery POST in javsascript

I want to post some data in JSON in a server, but I am having problem . I have done with this way which is working:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<h2>Create Sensor</h2>
<form id="form">
<form enctype='application/json'>
<input name='version' value='1.0.1'>
<input name='sensors_sensor' value=''>
<input name='sensors_name' value=''>
<input name='sensors_type' value=''>
<br>
<input id="input" type="submit" name="submit" value="Create Sensor" />
</form>
<script>
$(document).ready(function() {
$('#input').click(function() {
var fromData = {
"version": $('input[name=version]').val(),
"sensors": [{
"sensor": $('input[name=sensors_name]').val(),
"output": [{
"name": $('input[name=sensors_name]').val(),
"type": $('input[name=sensors_type]').val()
}]
}],
};
var fromDatan = JSON.stringify(fromData);
alert(fromDatan);
$.ajax({
url: "abc.com",
headers: {
"x-api-key": "abcd=",
"content-type": "application/json"
},
type: "POST",
data: fromDatan,
success: function(fromData, status, jqXHR) {
alert(JSON.stringify(fromData));
},
error: function(jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
return false;
});
});
</script>
</body>
</html>
But I am trying to do this in another way but it is not happening. Please help me out.
This is the code not working:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<h2>Create Sensor</h2>
<form id="form">
<form enctype='application/json'>
<input name='version' value='1.0.1'>
<input name='sensors_sensor' value=''>
<input name='sensors_name' value=''>
<input name='sensors_type' value=''>
<br>
<button onclick="postSOS();">Create</button>
</form>
<script>
function postSOS() {
postSEN();
}
function postSEN() {
// $('#input').click(function() {
var fromData = {
"version": $('input[name=version]').val(),
"sensors": [{
"sensor": $('input[name=sensors_name]').val(),
"output": [{
"name": $('input[name=sensors_name]').val(),
"type": $('input[name=sensors_type]').val()
}]
}],
};
var fromDatan = JSON.stringify(fromData);
alert(fromDatan);
$.ajax({
url: "abc.com",
headers: {
"x-api-key": "abcd=",
"content-type": "application/json"
},
type: "POST",
data: fromDatan,
success: function(fromData, status, jqXHR) {
alert(JSON.stringify(fromData));
},
error: function(jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
return false;
//});
}
</script>
</body>
</html>
By placing your script in the head I got it working on this FIDDLE
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function postSOS() {
postSEN();
}
function postSEN() {
// $('#input').click(function() {
var fromData = {
"version": $('input[name=version]').val(),
"sensors": [{
"sensor": $('input[name=sensors_name]').val(),
"output": [{
"name": $('input[name=sensors_name]').val(),
"type": $('input[name=sensors_type]').val()
}]
}],
};
var fromDatan = JSON.stringify(fromData);
alert(fromDatan);
$.ajax({
url: "abc.com",
headers: {
"x-api-key": "abcd=",
"content-type": "application/json"
},
type: "POST",
data: fromDatan,
success: function(fromData, status, jqXHR) {
alert(JSON.stringify(fromData));
},
error: function(jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
return false;
//});
}
</script>
</head>
<body>
<h2>Create Sensor</h2>
<form id="form">
<form enctype='application/json'>
<input name='version' value='1.0.1'>
<input name='sensors_sensor' value=''>
<input name='sensors_name' value=''>
<input name='sensors_type' value=''>
<br>
<button onclick="postSOS();">Create</button>
</form>
</body>
</html>
JSFIDDLE
Can you please try if this works (just add your API key and URL): http://jsfiddle.net/gqLgf4vx/
var sensorForm = $("#form");
sensorForm.on("submit", postSen());
function postSen() {
var formData = {
"version": $('input[name=version]').val(),
"sensors": [{
"sensor": $('input[name=sensors_name]').val(),
"output": [{
"name": $('input[name=sensors_name]').val(),
"type": $('input[name=sensors_type]').val()
}]
}],
},
formDataStr = JSON.stringify(formData);
sendAjax(formDataStr);
}
function sendAjax(formDataStr) {
$.ajax({
url: "abc.com",
headers: {
"x-api-key": "abcd=",
"content-type": "application/json"
},
type: "POST",
data: formDataStr,
success: function (fromData, status, jqXHR) {
//alert(JSON.stringify(fromData));
},
error: function (jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
}
I think your first code has extra form tag.
So I updated your code.
<form id="form">
<form enctype='application/json'>
https://jsfiddle.net/Jinthakur/0ne485u9/2/

Categories

Resources