Uable to send POST data to JSON file via JQuery/AJAX, Why? - javascript

I am learning to process JQuery/Ajax from this video on YouTube, click here..
I'm not having any problem in receiving data from order.json file but when I am trying to POST data. I am always getting Error.
The code structure with screenshot and code is below, please help me.
Project folder screenshot:
HTML code:
<div class="wrapper">
<h1>Jquery Ajax Tutorial</h1>
<h3>Coffie Orders</h3>
<ul id="orders"></ul>
<h4>Add a Coffie Order</h4>
<p> Name: <input type="text" id="name"> </p>
<p> Drink: <input type="text" id="drink"> </p>
<button id="add-order">Add!</button>
JQuery/Ajax code:
$(document).ready(function () {
var $orders = $('#orders');
var $name = $('#name');
var $drink = $('#drink');
function addOrder(order){
$orders.append('<li>Name: '+ order.name +', Drink: '+ order.drink +'</li>');
}
$.ajax({
type: 'GET',
url: '/api/orders.json',
success: function (orders) {
$.each(orders, function(i, orders) {
addOrder(orders);
});
},
error: function(){
alert('Error Loading Page');
}
});
$('#add-order').click(function(){
var order = {
name: $name.val(),
drink: $drink.val(),
}
$.ajax({
type: 'POST',
url: '/api/orders.json',
data: order,
success: function(newOrder) {
addOrder(newOrder);
},
error: function(){
alert('Error Adding Orders');
}
});
});
});
JSON: order.json
[{
"id": 1,
"name": "James",
"drink": "Coffiee"
}, {
"id": 2,
"name": "John",
"drink": "Latte"
}]

Client side scripting languages are used to send and retrieve data which resides on server side. We can't use them to write/edit data on server side.
For doing so, we have to use server side scripting languages like PHP or ASP or any other which you prefer.
The video you referred was an API written in Core PHP used for retrieving / writing data from / to a json file which resides on server.
In my below code i have used PHP to write submitted data to a json file via jQuery/AJAX.
Check this out..
api/process.php
if (isset($_POST['params'])) {
$params = $_POST['params'];
$oldData = file_get_contents('orders.json');
$tmp = json_decode($oldData);
array_push($tmp, $params);
$newData = json_encode($tmp);
if (is_writable('orders.json')) {
file_put_contents('orders.json', $newData);
echo $newData;
} else {
echo "file is not writable, check permissions";
}
}
index.html
<h1>Jquery Ajax Tutorial</h1>
<h3>Coffie Orders</h3>
<ul id="orders"></ul>
<h4>Add a Coffie Order</h4>
<p> Name: <input type="text" id="name"> </p>
<p> Drink: <input type="text" id="drink"> </p>
<button id="add-order">Add!</button>
<script src='js/jquery.min.js'></script>
<script src='js/main.js'></script>
js/main.js
let $orders = $('#orders');
let $name = $('#name');
let $drink = $('#drink');
function addOrder(order) {
$orders.append('<li>Name: '+ order.name +', Drink: '+ order.drink +'</li>');
}
$('#add-order').click(function(){
let order = {
name: $name.val(),
drink: $drink.val()
};
$.ajax({
type: 'POST',
url: '/api/process.php',
data: { params: order },
success: function(resp) {
addOrder(resp);
},
error: function(){
alert('Error Adding Orders');
}
});
});
$.ajax({
type: 'GET',
url: '/api/orders.json',
success: function (orders) {
$.each(orders, function(i, orders) {
addOrder(orders);
});
},
error: function(){
alert('Error Loading Page');
}
});
api/orders.json
[
{
"id": 1,
"name": "James",
"drink": "Coffiee"
},
{
"id": 2,
"name": "John",
"drink": "Latte"
}
]
Note: Here, i am not writing id to json file for new orders.
Hope, this piece of code works fine for you. :) :)

Related

Illegal invocation error when tranfering file

//HTML
<td><input type="file" name="product_image" id="product_image" required ></td>
//JavaScript
$(document).on("click", "#submit", function() {
console.log(validproductname, validproductprice, validdescription, validimage);
if (validproductname && validproductprice && validdescription && validimage) {
var send_data = new FormData();
var file_data = $('#product_image').prop('files')[0];
send_data.append("file", productimage.files[0]);
$.ajax({
url: "retrivedata.jsp",
type: "POST",
data: {
pagename: "index",
action: "insert",
productname: productname.value,
productprice: productprice.value,
productdescription: productdescription.value,
productcategory: productcategory.value,
productimage: $('#product_image').prop('files')[0]
},
success: function(data) {
load_data();
}
});
} else {
console.log("Invalid Details");
}
});
I have to trying to send file with data but it will through following error:
I apply one of solution processData:false
but it will send data as a [object Object] which i can't able to access
What i want is that i need to send file as a data parameter and access in a backend side

Sending Array Object Data in Javascript to ASP.NET Core Controller using AJAX ()

I've tried all other solutions pertaining to the problem, but still can't find what i'm missing for my code. Here's my AJAX() Code.
var group = JSON.stringify({ 'listofusers': listofusers });
console.log("listofusers : " + JSON.stringify({ 'listofusers': group }));
(Assuming I have my listofusers object ready, and yes i've checked the console and it has data inside.)
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: "POST",
url: url,
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
//doSend(JSON.stringify(data));
//writeToScreen(JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
Here's my Server Side Controller.
[HttpPost]
public IActionResult GetMesssage(List<UserModel> listofusers)
{
var g = listofusers;
}
Just a simple fetch from the controller, so I could verify that the data from client side has really been sent.
I've tried the [FromBody] attribute, but still no luck in fetching the data from the server-side.
Here is a working demo like below:
1.Model:
public class UserModel
{
public int Id { get; set; }
public string Name { get; set; }
}
2.View(remove Content-type):
<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = { 'listofusers': listofusers };
console.log(group);
$.ajax({
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>
3.Console.log(group):
4.Result:
Update:
Another way by using json:
1.View(change group from JSON.stringify({ 'listofusers': listofusers });
to JSON.stringify(listofusers);):
<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = JSON.stringify(listofusers);
console.log(group);
$.ajax({
contentType:"application/json",
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>
2.Controller(add FromBody):
[HttpPost]
public IActionResult GetMesssage([FromBody]List<UserModel> listofusers)
{
//...
}
You can try this one.
First stringify the parameter that you want to pass:
$.ajax({
url: url,
type: "POST",
data: {
listofusers: JSON.stringify(listofusers),
},
success: function (data) {
},
error: function (error) {
}
});
Then in your controller:
[HttpPost]
public IActionResult GetMesssage(string listofusers)
{
var jsonModel = new JavaScriptSerializer().Deserialize<object>(listofusers); //replace this with your deserialization code
}
What we're doing here is passing your object as a string then deserializing it after receiving on the controller side.
Hope this helps.
I found the solution to my problem guys, but I just want a clarification that maybe there's a work around or another solution for this one.
I've studied the data passed by "JSON.stringify();" from AJAX() and it's somehow like this.
"[[{\"ID\":0,\"UserID\":1014,\"Level\":\"support\",\"Department\":\"\",\"Facility\":\"Talisay District Hospital\",\"Firstname\":\"Joseph\",\"Middlename\":\"John\",\"Lastname\":\"Jude\",\"LoginStatus\":false,\"IPAddress\":\"192.168.110.47:12347\"},{\"ID\":0,\"UserID\":1014,\"Level\":\"support\",\"Department\":\"\",\"Facility\":\"Talisay District Hospital\",\"Firstname\":\"Joseph\",\"Middlename\":\"John\",\"Lastname\":\"Jude\",\"LoginStatus\":false,\"IPAddress\":\"192.168.110.47:15870\"}]]"
to which I was wondering that if the JSON format is a factor in parsing the data from the controller side. (Which of course is stupid since there's only one JSON format. (or maybe there's another, if there is, can you please post some source for reference.))
so I tried Serializing a Dummy Data in my model in "JsonConvert.Serialize()" Method and the output JSON data is like this.
[{"ID":0,"UserID":1014,"Level":"support","Department":"","Facility":"Talisay District Hospital","Firstname":"Joseph","Middlename":"John","Lastname":"Jude","LoginStatus":false,"IPAddress":"192.168.110.47:12347"},{"ID":0,"UserID":1014,"Level":"support","Department":"","Facility":"Talisay District Hospital","Firstname":"Joseph","Middlename":"John","Lastname":"Jude","LoginStatus":false,"IPAddress":"192.168.110.47:16709"}]
and I tried sending the output JSON Data from JsonConvert.Serialize() Method to controller via AJAX() and it worked! And I feel so relieved right now as this problem was so frustrating already.
If there's something wrong with what I found, please respond with what might be wrong or correct. Thank you!

I didn't get required input and output on Azure Cognitive services

Code
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
// Request parameters
};
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/linguistics/v1.0/analyzers?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","fa5a4445a080414d95610f74fa3e5626");
},
type: "GET",
// Request body
data: "{body}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
Documentation Help
https://westus.dev.cognitive.microsoft.com/docs/services/56ea598f778daf01942505ff/operations/56ea59bfca73071fd4b102ba
input json is below
{ "language" : "en", "analyzerIds" : ["4fa79af1-f22c-408d-98bb-b7d7aeef7f04", "22a6b758-420f-4745-8a3c-46835a67c0d2"], "text" : "Hi, Tom! How are you today?" }
required output is below json
[
{
"analyzerId" : "4fa79af1-f22c-408d-98bb-b7d7aeef7f04",
"result" : ["NNP",",","NNP","VBP","PRP","NN","."]
},
{
"analyzerId" : "22a6b758-420f-4745-8a3c-46835a67c0d2",
"result" : ["(TOP (S (NNP Hi) (, ,) (NNP Tom) (. !)))","(TOP (SBARQ (WHADVP (WRB How)) (SQ (VP (VBP are)) (NP (PRP you)) (NN today) (. ?))))"]
}
]
Looks like you're mixing up the 'List Analyzers' and 'Analyze Text' calls. Your input/output combination suggests you want the latter. If so, the code should be roughly as follows:
var request = {
"language": "en",
"analyzerIds": [
"4fa79af1-f22c-408d-98bb-b7d7aeef7f04",
"22a6b758-420f-4745-8a3c-46835a67c0d2"
],
"text": "Hi, Tom! How are you today?"
}
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/linguistics/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","fa5a4445a080414d95610f74fa3e5626");
},
type: "POST",
// Request body
data: JSON.stringify(request),
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
The four differences are:
The URL is /analyze, not /analyzers
The type is POST, not GET
The Content-Type needs to be specified
The data object needs to contain the request JSON.

Ajax firing success event but not getting to the web method

I'm using ajax to call a server side function. for some reason, the success is firing but it doesn't get to the function
here is the javascript
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: "Server.aspx/sendEmail",
data: { name: "foo", company: "bar", country: "foo", email: "bar", msg: "bla" },
async: false,
success: function (data) {
var a = 3;
},
error: function (a, b) {
alert("error");
var a = 43;
}
});
});
here is the c#
[WebMethod]
public static string sendEmail(string name, string company, string country, string email, string msg)
{
//somecode here
}
the data message(for some reason it is breaking)
<form method="post" action="./sendEmail?%7b%22name%22%3a%22foo%22%2c%22company%22%3a%22bar%22%2c%22country%22%3a%22foo%22%2c%22email%22%3a%22bar%22%2c%22msg%22%3a%22bla%22%7d" id="form1">
<div>
</div>
<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="368A1591" />
Take the following points into account when you are calling an ASP.NET AJAX page methods:
To use ASP.NET AJAX page methods, you need to make a POST request. This is to prevent CSRF
Ensure that the contentType is set to application/json.
Use JSON.stringify to convert the JavaScript object into JSON text.
Your JS code could be something similar to this:
$(document).ready(function () {
var data = { name: "foo", company: "bar", country: "foo", email: "bar", msg: "bla" };
$.ajax({
url: "Server.aspx/sendEmail",
type: "POST",
data: JSON.stringify(data),
async: false,
contentType: 'application/json',
success: function (data) {
//Do something
},
error: function (xhr) {
alert('Request Status: ' + xhr.status
+ ' Status Text: ' + xhr.statusText
+ ' ' + xhr.responseText);
}
});
});
If it still doesn't work, check the statusText for the error.

SharePoint 2013 Send Email from Contact Us Form via REST/JS

and thanks in advance for your answers.
I am trying to send an email from a contact us form. It appears to work but I don't receive any emails. I don't have any experience with REST and would like someone who does to see if they can spot any problems.
This is on a SharePoint 2013 Enterprise Publishing Site.
I have changed some variables and IDs for privacy purposes.
The HTML is in a custom page layout, and the JS is being called successfully in the same page layout after jQuery.
JS:
$.noConflict();
jQuery( document ).ready(function( $ ) {
// Code that uses jQuery's $ can follow here.
function submitForm() {
var toAddress = "email#domain.com";
var fromAddress ="email#domain.com";
var emSubject = "Public Contact Us Form Entry";
var lblName = "Name: ";
var valName = document.getElementById('form-name').value;
var lblEmail = "Email: ";
var valEmail = document.getElementById('form-email').value;
var lblMessage = "Message: ";
var valMessage = document.getElementById('form-message').value;
var emBody = lblName.concat(valName,lblEmail,valEmail,lblMessage,valMessage);
var data = {
properties: {
__metadata: { 'type': 'SP.Utilities.EmailProperties' },
From: fromAddress,
To: toAddress,
Body: emBody,
Subject: emSubject
}
}
var urlTemplate = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.Utilities.Utility.SendEmail";
$.ajax({
contentType: 'application/json',
url: urlTemplate,
type: "POST",
data: JSON.stringify(data),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
alert('User(s) notified')
},
error: function (err) {
alert("Unable to send email -- " + JSON.stringify(err));
}
});
}
});
HTML:
<div class="label">Name</div>
<input name="Name" type="text" id="form-name" size="40">
<div class="label">Email</div>
<input name="E-mail" type="text" id="form-email" size="40">
<div class="label">Message</div>
<textarea name="Message" cols="55" rows="5" id="form-message"></textarea>
<div class="form-button">
<button onclick='submitForm()'>Submit</button>
</div>
You code has one mistake:
I changed To: toAddress to To: { 'results': [toAddress] }.
Now every thing is working fine and I am also getting the emails.
var data = {
properties: {
__metadata: { 'type': 'SP.Utilities.EmailProperties' },
From: fromAddress,
To: { 'results': [toAddress] } ,
Body: emBody,
Subject: emSubject
}
}

Categories

Resources