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/
Related
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/
I am using a simple ajax call on load and onclick,I am using function for it.Here my ajax call url is different onload and onclick,I have used function and different parameter but its still showing previous json using onclick. Below is my code,
Updated in plunker https://plnkr.co/edit/YOeklbX5shZCnHVRktyK?p=preview
html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script.js"></script>
<div id="critical">
<span id="name1"></span> : <span id="value1"></span>
</div>
<div id="major">
<span id="name2"></span> : <span id="value2"></span>
</div>
<div id="minor">
<span id="name3"></span> : <span id="value3"></span>
</div>
<button>click</button>
javascript
$(document).ready(function(){
$.fn.reload_cart = function(){
$.ajax({
type: "GET",
url: "1.json",
success: function(result) {
$("#name1").text(result.critical[0].name);
$("#value1").text(result.critical[0].value);
$("#name2").text(result.major[0].name);
$("#value2").text(result.major[0].value);
$("#name3").text(result.minor[0].name);
$("#value3").text(result.minor[0].value);
}
});
}
$.fn.reload_cart();
$("button").click(function(){
var url2;
$.fn.reload_cart(url2);
url2: "2.json";
});
});
1.json
{
"critical": [{
"name": "critical",
"value": "50"
}],
"major": [{
"name": "major",
"value": "40"
}],
"minor": [{
"name": "minor",
"value": "20"
}]
}
2.json
{
"critical": [{
"name": "criticalnew",
"value": "53"
}],
"major": [{
"name": "majornew",
"value": "43"
}],
"minor": [{
"name": "minornew",
"value": "23"
}]
}
You need to pass the json file name in reload_cart() function and check if file name is passed then read from this file(1.json) else read from another file(2.json). Please your javascript code to following:
$(document).ready(function(){
$.fn.reload_cart = function(url){
if(!url){
url = "1.json"
}
$.ajax({
type: "GET",
url: url,
success: function(result) {
$("#name1").text(result.critical[0].name);
$("#value1").text(result.critical[0].value);
$("#name2").text(result.major[0].name);
$("#value2").text(result.major[0].value);
$("#name3").text(result.minor[0].name);
$("#value3").text(result.minor[0].value);
}
});
}
$.fn.reload_cart();
$("button").click(function(){
var url2 = "2.json";
$.fn.reload_cart(url2);
});
});
I have updated your Plunker
You need to make your reload_cart function accept a parameter url.
$(document).ready(function() {
$.fn.reload_cart = function(url) {
$.ajax({
type: "GET",
url: url,
success: function(result) {
$("#name1").text(result.critical[0].name);
$("#value1").text(result.critical[0].value);
$("#name2").text(result.major[0].name);
$("#value2").text(result.major[0].value);
$("#name3").text(result.minor[0].name);
$("#value3").text(result.minor[0].value);
}
});
}
$.fn.reload_cart("1.json");
$("button").click(function() {
$.fn.reload_cart("2.json");
});
});
I wanted to learn how to use JSON with jQuery so I followed a simple video tutorial on it. However, after following all the steps and using the exact same code as in the video, I still don't see anything in the console after a console.log. What am I doing wrong?
Here is the HTML page:
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$.ajax({
url: 'articles.json',
dataType: 'json',
type: 'get',
cache: false,
succes: function(data) {
$(data.articles).each(function(index, value) {
console.log("success");
});
}
});
</script>
</body>
</html>
And here is my JSON file (articles.json) from which I am trying to use the data:
{
"articles": [
{
"id": 1,
"name": "Article 1"
},
{
"id": 2,
"name": "Article 2"
},
{
"id": 3,
"name": "Article 3"
}
]
}
Thanks in advance!
Here is correct way to read json data in javascript using jquery
<script>
$.ajax({
url: 'articles.json',
dataType: 'json',
type: 'get',
cache: false,
succes: function(data) {
var jsonData = JSON.parse(data);
$.each(jsonData.articles, function(i, v) {
console.log("id = "+ v.id);
console.log("name = " + v.name);
});
}
});
</script>
Use $.getJSON
example
$.getJSON( "articles.json", function( data ) {
$.each( data.articles, function( key, val ) {
console.log(val);
});
});
http://api.jquery.com/jquery.getjson/
This is success part of my jquery ajax call:
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
response($.map(data.d, function (item) {
return {
label: item.ItemName,
val: item.ItemId
}
}))
},
And this is data that I get in this success block from server:
[{"ItemId":1095,"ItemName":"Double Axe"},{"ItemId":1096,"ItemName":"Helm"},{"ItemId":1097,"ItemName":"Armor"},{"ItemId":1098,"ItemName":"Gloves"},{"ItemId":1099,"ItemName":"Boots"}]
Error that I am getting is:
Uncaught TypeError: Cannot read property 'length' of undefined
Problem is that response($.map(data.d, function (item) { is never executed.
What should I do to make this work?
You're currently passing a json string to the $.map() method which expects an array or object. parsing the response you're getting using JSON.parse().
Following seems to be working fine:
var data = [{
"ItemId": 1095,
"ItemName": "Double Axe"
}, {
"ItemId": 1096,
"ItemName": "Helm"
}, {
"ItemId": 1097,
"ItemName": "Armor"
}, {
"ItemId": 1098,
"ItemName": "Gloves"
}, {
"ItemId": 1099,
"ItemName": "Boots"
}];
$("#tags").autocomplete({
"source": function(request, response) {
response($.map(data, function(item) {
return {
label: item.ItemName,
val: item.ItemId
}
}));
}
});
<link href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<div class="ui-widget">
<label for="tags">Tags:</label>
<input id="tags" />
</div>
I have been trying to populate my input with select2 using the JSON provided.
Here's the JSON:
{
"airports":
[
{
"id": "1",
"code": "AMQ",
"city": "Ambon",
"country": "Indonesia"
},
{
"id": "2",
"code": "BJW",
"city": "Bajawa",
"country": "Indonesia"
}
]
}
And the html code:
<input class="" type='hidden' value="192" data-init-text='Departing City' name='input' id='depart-airport' style="width: 300px"/>
And the js code:
$(document).ready(function() {
$('#depart-airport').select2({
minimumInputLength: 1,
ajax: {
url: "http://localhost:4000/api/airports.json",
dataType: 'json',
results: function (data) {
return { results: data};
}
}
});
});
There's no error in console, but whether I try to input them it's always saying that "searching failed" or there's not even anything. The data from json never showed.
Do you have anything to fix this around? Thanks's before :)
You have a minor error in your jQuery:
$(document).ready(function() {
$('#depart-airport').select2({
minimumInputLength: 1,
ajax: {
url: "http://localhost:4000/api/airports.json",
dataType: 'json',
results: function (data) {
// You had { results: data }, but your actual information is in data.airports
return { results: data.airports };
}
}
});
});