i have some code and request from multiple url, and result data is array , if i use result.push(data) the result will give [[{Data1:a,Data2:b}],[{Data1:c,Data2:d}]] how to merged data become array like [{Data1:a,Data2:b},{Data1:c,Data2:d}]
var url_api = [<?=$urlapi;?>];
var responses = [];
for(var i = 0; i < url_api.length; i++){
getTarif(url_api[i]);
}
function getTarif(link){
$.ajax({
type: 'GET',
url: link,
dataType: 'json',
error: function () {
alert('Unable to load url :'+link+', Incorrect path or invalid url');
},
success: function (data) {
responses.push(data.data);
}
});
}
You can use the spread syntax - responses.push(...data.data); - to add individual items to the responses arrays:
function getTarif(link){
$.ajax({
type: 'GET',
url: link,
dataType: 'json',
error: function () {
alert('Unable to load url :'+link+', Incorrect path or invalid url');
},
success: function (data) {
responses.push(...data.data);
}
});
}
Related
// something defined deleteArr and pass values to it
var postData = { deleteArr: deleteArr };
if(deleteArr.length > 0)
{
$.ajax({
url: "#Url.Action("Delete", "ASZ01")",
type: "POST",
data: postData,
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("success.");
},
error: function (response) {
alert(deleteArr[0]);
}
});
deleteArr.length = 0;
}
The above code is javascript.
Until $.ajax begin I can confirm that values in array is correct in immediate window,but when it comes to error: I got "undefined".
And the following is my function in controller
public void Delete(List<string> deleteArr)
{
service.Delete(deleteArr);
}
The second question is that I set breakpoint on that function but it can't stop.
I think maybe my ajax form is wrong?
Stringify to JSON, add the dataType: 'json' and then pass and also correct your ""
var postData = JSON.stringify({ deleteArr: deleteArr });
if(deleteArr.length > 0)
{
$.ajax({
url: #Url.Action("Delete", "ASZ01"),
type: "POST",
data: postData,
dataType: 'json'
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("success.");
},
error: function (response) {
alert(deleteArr[0]);
}
});
deleteArr.length = 0;
}
Small change to your postData
var postData = { deleteArr: JSON.stringify(deleteArr) };
Idea is to convert your array data into string format ie:JSON and posting to the server, The default Model binder of MVC framework will handle the part to convert them into List<string> for you
When I try to retrieve the File path it's shows me the result like this: "C:\fakepath\amine.jpeg" so the upload in the server is not working as a result of that problem.
$('input[type=file]').change(function () {
var filePath=$('#file-input').val();
$.ajax({
url : "{{path('upload_file')}}",
type : 'POST',
data: {
filePath : filePath,
method: 'post',
params: {
action: "uploadFile"
}
},
success : function(data, textStatus, jqXHR) {
alert(data);
}
});
});
You are doing this all wrong.
You have to create a form object and send it via $.ajax.
And I assume you have written the correct serverside code to save the image.
var f = new FormData();
f.append('img',document.getElementById("file-input").files[0]);
var url= "{{Your URL}}";
$.ajax({
url: url,
type:"post",
data: f,
dataType:"JSON",
processData: false,
contentType: false,
success: function (data, status)
{
console.log(data);
},
error: function (data)
{
if (data.status === 422) {
console.log("upload failed");
} else {
console.log("upload success");
}
});
Your file by default upload to a temporary folder. You need to move it to an actual location to get access to it like in php:
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)
For reference, see http://www.w3schools.com/php/php_file_upload.asp
So I am doing some testing with the food2fork api.
I seem to be getting a 404 forbidden.
Have looked and cannot find anything that has worked.
http://food2fork.com/about/api
Code below
$(document).ready(function() {
$("#button").click(function(event) {
event.preventDefault();
var searchTerm = $("#input").val();
showResults(searchTerm);
});
function showResults(searchTerm) {
$.ajax({
key: "xxxx",///api key
type: "GET",
dataType: 'jsonp',
url: "http://food2fork.com/api/search",
q: searchTerm,
success: function (data) {
alert('success');
}
});
}
});
The q and key properties of the object you're passing to $.ajax are ignored because they're invalid. It should be part of the request data.
Try this instead:
$.ajax({
type: "GET",
data: { q: searchTerm, key: 'yourKey' },
dataType: 'jsonp',
url: "http://food2fork.com/api/search",
success: function (data) { alert('success'); }
});
See Documentation
In a AJAX request to the server in MVC, how can I pass a list of id's to the controller's action function?
I accept with or without use of Html helpers.
I know MVC's model binder has no problem when it comes to simple types like int, string and bool.
Is it something like I have to use and array instead in the action?
I don't care if I have to use an array or List and even if the strings I int or strings I can always convert them. I just need them on the server.
My List ids gives null at the moment.
Javascript:
var ids= [1,4,5];
// ajax request with ids..
MVC Action:
public ActionResult ShowComputerPackageBuffer(List<int> ids) // ids are null
{
// build model ect..
return PartialView(model);
}
EDIT: Added my AJAX request
$(document).ready(function () {
$('#spanComputerPackagesBuffer').on('click', function () {
var ids = $('#divComputerPackagesBuffer').data('buffer');
console.log('bufferIds: ' + bufferIds);
var data = {
ids: ids
};
var url = getUrlShowComputerPackageBuffer();
loadTable(url, "result", data);
});
});
// AJAX's
function loadTable(url, updateTargetId, data) {
var promise = $.ajax({
url: url,
dataType: "html",
data: data
})
.done(function (result) {
$('#' + updateTargetId).html(result);
})
.fail(function (jqXhr, textStatus, errorThrown) {
var errMsg = textStatus.toUpperCase() + ": " + errorThrown + '. Could not load HTML.';
alert(errMsg);
});
};
// URL's
function getUrlShowComputerPackageBuffer() {
return '#Url.Action("ShowComputerPackageBuffer", "Buffer")';
};
SOLUTIONS: // Thanks to #aherrick comment. I missed the good old "traditional"
$.ajax({
type: "POST",
url: '#Url.Action("ShowComputerPackageBuffer", "Buffer")',
dataType: "json",
traditional: true,
data: {
bufferIds: bufferIds
}
});
Use the traditional parameter and set it to true.
$.ajax({
type: "POST",
url: "/URL",
dataType: "json",
traditional: true,
data: {}
});
Try this one (I've checked it):
$(function () {
var ids = [1, 4, 5];
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '#Url.Action("YourAction", "YourController")',
data: JSON.stringify( { ids: ids })
}).done(function () {
});
});
You have to make sure your contentType is application/json and your data is stringified.
public ActionResult SaveSomething(int[] requestData)
//or
public ActionResult SaveSomething(IEnumerable<int> requestData)
Using Action Result you cannot receive JSON object:
Using Controler:
[HttpPost]
[Route( "api/Controller/SaveSomething" )]
public object SaveTimeSheet( int[] requestData )
{
try
{
doSomethingWith( requestData );
return new
{
status = "Ok",
message = "Updated!"
};
}
catch( Exception ex )
{
return new
{
status = "Error",
message = ex.Message
};
}
}
java script:
var ids = [1,4,5];
var baseUrl: 'localhost/yourwebsite'
$.ajax({
url: baseUrl + '/api/Controller/SaveSomething',
type: 'POST',
data: JSON.stringify(ids),
dataType: 'json',
contentType: 'application/json',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
if (result != undefined) {
window.location.href = window.location.href;
}
},
async: false,
});
Basically I am trying to extract JSON returned from servlet in JavaScript. I have tested my servlet class already and it did returned some JSON so I guess I no need to post the code for that class. Here is my returned JSON format:
[{"mrtpopAmt":"7000","mrtpopX":"17854.99820","mrtpopY":"35056.35003"},{"mrtpopAmt":"6300","mrtpopX":"29798.58427","mrtpopY":"37036.56434"}]
And in my JavaScript, I am trying to extract mrtpopAmt, mrtpopX and mrtpopY as one object. Then I will add all object into an array:
function getAllMRTPop(time){
var jsonArray;
var Data = JSON.stringify({ time: time });
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time="+ Data + "",
type: "GET",
data: Data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var parsed = JSON.parse(data.d);
console.log(data.d);
$.each(parsed, function (i, jsondata) {
var jsonObject;
jsonObject.put("mrtpopAmt", jsondata.mrtpopAmt);
jsonObject.put("mrtstationX", jsondata.mrtstationX);
jsonObject.put("mrtstationY", jsondata.mrtstationY);
alert(jsonObject);
jsonArray.push(jsonObject);
});;
},
error: function (request, state, errors) {
}
});
}
However, I am getting error message like Unexpected token: u at this line:
var parsed = JSON.parse(data.d);
My URL for the servlet contains two parameter, one is action and the other one is time:
http://localhost:8080/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time=8:00
So I wonder am I passing the parameter correctly by passing it in url and as well as data from the code above?
I wonder which part went wrong? Thanks in advance.
EDIT
So I have updated my JavaScript part to this:
function getAllMRTPop(time){
var jsonArray = [];
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time=8:00",
type: "GET",
data: time,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
//var parsed = JSON.parse(data.d);
$.each(data, function (i, jsondata) {
var jsonObject;
console.log(mrtpopAmt);
jsonObject.put("mrtpopAmt", jsondata.mrtpopAmt);
jsonObject.put("mrtstationX", jsondata.mrtstationX);
jsonObject.put("mrtstationY", jsondata.mrtstationY);
jsonArray.push(jsonObject);
});;
},
error: function (request, state, errors) {
}
});
}
I tried to print out the mrtpopAmt and it did returned something. But there is an error message:
Cannot call method 'put' of undefined
Any ideas?
By specifying dataType: "json", jQuery already knows you will be getting a JSON response, there is no no need to do var parsed = JSON.parse(data.d)
Just do:
var parsed = data.d
Edit:
function getAllMRTPop(time){
var jsonArray = [];
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time=8:00",
type: "GET",
data: time,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
$.each(data, function (i, jsondata) {
var jsonObject = {};
jsonObject.mrtpopAmt = jsondata.mrtpopAmt;
jsonObject.mrtstationX = jsondata.mrtstationX;
jsonObject.mrtstationY = jsondata.mrtstationY;
jsonArray.push(jsonObject);
});;
},
error: function (request, state, errors) {
}
});
}
I think what is happening is that data.d is undefined, so you are getting the odd message about unexpected u.
Try this instead:
var parsed = JSON.parse(data);
Edit And I think you are probably not formatting your request right:
var Data = JSON.stringify({ time: time });
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time="+ Data + "",
Seems to me that would make the final bit: &time={"time":"time"}, so you probably want to look at how you construct Data. Maybe just pass time directly?
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time="+ time + "",