I have an ajax response with data extracted from a sql query. It has this structure:
Response
id:"id"
titulo:"title"
url:"url"
What I am trying to do is to find the position within the ajax response where a given unique id is.
$.ajax({
url: 'select.php',
type: 'get',
data: {
"id": id
},
dataType: "json",
beforeSend: function() {},
success: function(response) {
console.log(response);
console.log(response.indexOf(27188964));
}
});
The second log prints -1, knowing that the number should be at the first position.
EDIT:
I need the position in order to start moving through the array by increasing 'index'
response[index].url
If your response is an array of objects you can use Array.prototype.filter():
$.ajax({
url: 'select.php',
type: 'get',
data: {
"id": id
},
dataType: "json",
beforeSend: function() {},
success: function(response) {
var resultIndex;
var result = response.filter(function(obj, index) {
if (obj.id === '27188964') {
resultIndex = index;
return true;
}
return false;
});
console.log('resultIndex:', resultIndex);
console.log('result:', result);
}
});
Related
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);
}
});
}
I want to regex JSON response value in AJAX without losing the structure of JSON.
Here is the ajax
$.ajax({
url: "date.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
dataType: "json",
headers: {
"X-Requested-With": "XMLHttpRequest",
},
success: function(data) {
var formDatax = new FormData();
var date = data.results;
var res = date.map(function(item) {
return {
"images": item.images
};
});
$.ajax({
url: "json.php",
type: "POST",
data: JSON.stringify(res),
processData: false,
contentType: false,
dataType: "json",
headers: {
"X-Requested-With": "XMLHttpRequest",
},
success: function(data) {
},
error: function() {}
});
},
error: function() {}
});
Here is an example of JSON Response
{
"part_number_key":"DDASDAS",
"name":"ASD",
"description":"asd",
"price":12,
"general_stock":12,
"brand":"ASD",
"category_id":2776,
"images":[
{
"url":"https://asd.com/asd/asd/1241.jpg",
"display_type":1
},
{
"url":"https://asd.com/asd/asd/73223.jpg",
"display_type":0
},
{
"url":"https://asd.com/asd/asd/214121.jpg",
"display_type":0
}
],
"warranty":24
},
I want to get the link of the image where the display_type is having value 1, so I thought it's ok if I regex the first url before "display_type":1 but I'm not able because this is not string to regex.
/(https?\:\/\/[^\" ][^]).*("display_type":1)/i
The regex, it's not complete because I saw the problem about the string I didn't tried to complete the regex...
You could parse the JSON and use filter and map to get the images URL
success: function(data) {
var response = JSON.parse(data)
var imagesURL = response.images.filter(image => image.display_type).map(image => image.url)
}
The response type is always parsed JSON. You can just access the images which have display_type: 1 like so:
let fileterImages = data.data.images.map((image) => {
if(image.display_type === 1) return image.url;
}
i have two ajax call in my script. one is working other is not. but both are working individual. they are not nested and there is no dependicy on each other.
only first ajax call is working second one is not.
my script is:
$('textarea').mentiony_user({ //#
onDataRequest: function (mode, keyword, onDataRequestCompleteCallback) {
$.ajax({
url: "search_user_list.php",
method: "post",
data: {keyword: keyword},
dataType: "json",
success: function (response) {
var data = response;
// console.log(data);
data = jQuery.grep(data, function( item ) {
return item.name.toLowerCase().indexOf(keyword.toLowerCase()) > -1;
});
onDataRequestCompleteCallback.call(this, data);
// setTimeout(data, 1000);
}
});
},
timeOut: 500, // Timeout to show mention after press #
});
// item list
$('textarea').mentiony_item({ //#
onDataRequest: function (mode, keyword, onDataRequestCompleteCallback) {
$.ajax({
url: "search_item_list.php",
method: "post",
data: {keyword: keyword},
dataType: "json",
success: function (response) {
var data = response;
console.log(data);
data = jQuery.grep(data, function( item ) {
return item.name.toLowerCase().indexOf(keyword.toLowerCase()) > -1;
});
onDataRequestCompleteCallback.call(this, data);
// setTimeout(data, 1000);
}
});
},
timeOut: 500, // Timeout to show mention after press #
});
</script>
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,
});
I have this script that adds elements with data by a get json function.
$(document).ready(function() {
ADD.Listitem.get();
});
It basicly adds a bunch of html tags with data etc. The problem I have is following:
$(document).ready(function() {
ADD.Listitem.get();
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
-
get: function(web) {
AST.Utils.JSON.get("/_vti_bin/AST/ListItem/ListitemService.svc/GetListItem", null, AST.Listitem.renderListitem);
},
renderListitem: function(data) {
$("#Listitem-template").tmpl(data["ListItemResults"]).prependTo(".ListItem-section-template");
}
and here is the json get:
ADD.Utils.JSON.get = function (url, data, onSuccess) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
async: true,
url: url,
data: data,
cache: false,
dataType: "json",
success: onSuccess,
error: ADD.Utils.JSON.error,
converters: { "text json": ADD.Utils.JSON.deserialize }
});
}
The array each loop is not running beacuse the get method is not finished with rendering the Listitem-section-item-title selector so it cant find the selector.
Is there any good solutions for this?
You could change your functions to return the promise given by $.ajax :
ADD.Utils.JSON.get = function (url, data) {
return $.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
async: true,
url: url,
data: data,
cache: false,
dataType: "json",
converters: { "text json": ADD.Utils.JSON.deserialize }
}).fail(ADD.Utils.JSON.error);
}
get: function(web) {
return AST.Utils.JSON.get("/_vti_bin/AST/ListItem/ListitemService.svc/GetListItem", null).done(AST.Listitem.renderListitem);
},
So that you can do
$(document).ready(function() {
ADD.Listitems.get().done(function(){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
});
Callback:
$(document).ready(function() {
ADD.Listitem.get(url,data,function(){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
});
Without callback:
If you cant get the get method to take a callback or return a promise then I think the best way will be to check when its done.
$(document).ready(function() {
ADD.Listitem.get();
var timer = setInterval(function(){
if ($("#thingWhichShouldExist").length>0){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
clearInterval(timer);
}
},50);
});
Retrieve the values and on success, call a function which will push the values into the array.
Also, arr.push($(this.text())); should be arr.push($(this).text());.