Store ajax response in json file with Mockjax - javascript

I am currently doing an exercise on jQuery, Mockjax, Ajax and JSON. but it seems that Mockjax doesn't work perfectly.
Here is what I am trying:
function mockJaxTest(param){
var url_pos = "http://localhost:8080/project/dashboard/"+param+".htm";
$.mockjax({
url: url,
dataType: 'json',
contentType: 'application/json',
proxy: "resources/mocks/data-pos.json"
});
$.getJSON(url_pos, function(data) {
if (data) {
alert('SUCCESS');
} else {
alert('FAILED');
}
});
}
What am I doing wrong?

Related

Send FormData through Ajax POST method return 403

I write an application with speech recognition. All I want is to record some speech and send it to server where I will convert it into text. And I have a problem with sending that sound file. I record voice using p5.js library and when I try to download it there is no problem.
The problem is when I try to send it to server using ajax.
script.js
function toggleRecording(e) {
if (e.classList.contains("recording")) {
recorder.stop();
e.classList.remove("recording");
sendAudioToServer(soundFile)
} else {
e.classList.add("recording");
recorder.record(soundFile);
}
}
function sendAudioToServer(soundFile)
{
var data = new FormData();
data.append('fname', 'test.wav');
data.append('data', soundFile);
console.log(soundFile);
console.log(data);
$.ajax({
type: 'POST',
url: '/recognizeCommand',
data: data,
dataType: 'jsonp',
processData: false,
contentType: false,
success: function(data) {
alert("works!");
},
error: function() {
alert("not works!");
}
})
Java controller
#PostMapping("/recognizeCommand")
public #ResponseBody String recognizeCommand(#RequestParam MultipartFile mpf) {
try {
byte[] bytes = mpf.getBytes();
SpeechRecognitionApplication.logger.info(bytes);
} catch (IOException e) {
e.printStackTrace();
}
return "finish";
}
When I stop recording regardless to toggleRecording function it should stop recording and send it to server. And there is a problem with sendAudioToServer function. Here is the result from Chrome console:
I'm not sure but there is probably problem with FormData. As you can see when I printed it in console it's empty. Founded some similar questions here but there is no solution to solve my problem.
EDIT:
After add dataType: 'jsonp'
There is that error:
EDIT 2:
After adding csrf token:
Please add csrf tokens as this.
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
In header:
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
Set headers.
$.ajax({
type: 'POST',
url: '/recognizeCommand',
data: data,
dataType: 'json',
processData: false,
contentType: false,
beforeSend: function(xhr) {
// here it is
xhr.setRequestHeader(header, token);
},
success: function(data) {
alert("works!");
},
error: function() {
alert("not works!");
}
})
Try adding debug point here.
SpeechRecognitionApplication.logger.info(bytes);
Try adding dataType: 'jsonp' to your $.ajax call like,
$.ajax({
type: 'POST',
url: '/recognizeCommand',
data: data,
dataType: 'jsonp',
processData: false,
contentType: false,
success: function(data) {
alert("works!");
},
error: function() {
alert("not works!");
}
})
Hope this helps!

Post AJAX API Javascript SAPUI5 failed

I want to use POST method with AJAX in SAPUI5 javascript but I found an error.
var url = "https://xxxx*xxxx.co.id:8877/TaspenSAP/SimpanDosirPunah";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({
nomorDosir: "01001961288",
kodeCabang: "A02"
}),
dataType: "json",
async: false,
contentType: 'application/json; charset=utf-8',
success: function(data, textStatus, xhr){
console.log("sukses: " + data + " " + JSON.stringify(xhr));
},
error: function (e,xhr,textStatus,err,data) {
console.log(e);
console.log(xhr);
console.log(textStatus);
console.log(err);
}
});
error:
I already did change code with dataType=text, or data: {nomorDosir: "01001961288", kodeCabang: "A02"} (without stringify), but I not yet find the solution. How to fix this problem?
Thanks.
Bobby
Not sure what your use case is but if you are trying to post to an oData service, it might be much easier to use SAPs createEntry method where the URL is the path to the model you want to post to and your JSON are the properties:
var oModel = new sap.ui.model.odata.v2.ODataModel("https://services.odata.org/V2/OData/OData.svc/");
//oModel should use your service uri
var url = "https://xxxx*xxxx.co.id:8877/TaspenSAP/SimpanDosirPunah";
oModel.createEntry(url, {
properties: {
nomorDosir: "01001961288",
kodeCabang: "A02"
}
}, {
method: "POST",
success: function(response) {
alert(JSON.stringify(response));
//do something
},
error: function(error) {
alert(JSON.stringify(error));
}
});
oModel.submitChanges();
What you have is wrong json format, you have:
data: JSON.stringify({nomorDosir: "01001961288", kodeCabang: "A02"}),
Which actually should be:
data: {"nomorDosir": "01001961288", "kodeCabang": "A02"},
Which then you don't need to do a json.stringify on, because it already IS a json format. Hope this will help you out.
Which you could also try is setting a variable outside like this:
var url = "https://xxxx*xxxx.co.id:8877/TaspenSAP/SimpanDosirPunah";
var json = {"nomorDosir": "01001961288", "kodeCabang": "A02"};
$.ajax({
type: "POST",
url: url,
data: json,
dataType: "json",
async: false,
contentType: 'application/json; charset=utf-8',
success: function(data, textStatus, xhr){
console.log("sukses: "+data+" "+JSON.stringify(xhr));
},
error: function (e,xhr,textStatus,err,data) {
console.log(e);
console.log(xhr);
console.log(textStatus);
console.log(err);
}
});

How to properly format data object that includes array of objects for jQuery ajax put request? [duplicate]

I would like to post Json to a web service on the same server. But I don't know how to post Json using JQuery. I have tried with this code:
$.ajax({
type: 'POST',
url: '/form/',
data: {"name":"jonas"},
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
But using this JQuery code the data is not received as Json on the server. This is the expected data at the server: {"name":"jonas"} but using JQuery the server receive name=jonas. Or in other words, it's "urlencoded" data and not Json.
Is there any way to post the data in Json format instead of urlencoded data using JQuery? Or do I have to use a manual ajax request?
You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param to serialize the object into name-value pairs.
If you pass the data as a string, it won't be serialized:
$.ajax({
type: 'POST',
url: '/form/',
data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Base on lonesomeday's answer, I create a jpost that wraps certain parameters.
$.extend({
jpost: function(url, body) {
return $.ajax({
type: 'POST',
url: url,
data: JSON.stringify(body),
contentType: "application/json",
dataType: 'json'
});
}
});
Usage:
$.jpost('/form/', { name: 'Jonh' }).then(res => {
console.log(res);
});
you can post data using ajax as :
$.ajax({
url: "url",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: 'value1', email: 'value2' }),
success: function (result) {
// when call is sucessfull
},
error: function (err) {
// check the err for error details
}
}); // ajax call closing
I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data
$.fn.postJSON = function(url, data) {
return $.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json'
});
The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.
var Data = {
"name":"jonsa",
"e-mail":"qwerty#gmail.com",
"phone":1223456789
};
$.ajax({
type: 'POST',
url: '/form/',
data: Data,
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Using Promise and checking if the body object is a valid JSON. If not a Promise reject will be returned.
var DoPost = function(url, body) {
try {
body = JSON.stringify(body);
} catch (error) {
return reject(error);
}
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: url,
data: body,
contentType: "application/json",
dataType: 'json'
})
.done(function(data) {
return resolve(data);
})
.fail(function(error) {
console.error(error);
return reject(error);
})
.always(function() {
// called after done or fail
});
});
}

Send headers in JQuery Ajax Get Request

Here is my code.
$.ajax(this.url, {
type: "GET",
//dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("x-token", token)
},
success: function (data) {
console.log(data);
},
error: function(){
console.log('error');
}
});
I am not able to send ajax request by that code. I also try hearder: {"x-token": token}, In place of beforeSend: but its also not working for me.

How to get the PHP var after Jquery $.ajax

I use $.ajax to send some data to testajax.phpenter code here where data are processing. Result of this proces is link. How to get access to this? I think about sessions or cookies. Set in session $test and get access in another files.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
success: console.log('success');
data: { json : jsonObj }
});
In testajax.php I have someting like this
echo "PDF: <a href=images/test.pdf>$dir.pdf</a>";
$test = "PDF: <a href=images/test.pdf>$dir.pdf</a>";
How to get the $test or output the echo after call $.ajax
You can use success' function to get request from PHP.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'html',
data: { json : jsonObj }
success: function(data) {
var request = data;
console.log(data);
$('#link_container').html(data);
}
});
Your console now holds PDF: <a href=images/test.pdf>($dir content).pdf</a>.
Also the variable request holds the same result that you can use anywhere in the script.
Result is appended to #link_container.
Use the success() method for display the result.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
success: function (data){ // <= define handler for manupulate the response
$('#result').html(data);
}
data: { json : jsonObj }
});
Use below code It may help you.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
data: { json : jsonObj },
onSuccess: successFunc,
onFailure: failureFunc
});
function successFunc(response){
alert(response);
}
function failureFunc(response){
alert("Call is failed" );
alert(response);
}

Categories

Resources