I'd like to toggle between 2 ajax data objects on click of a link. Its not possible to do this with the method below, can anyone suggest a way I can do this? Thanks!
jQuery.ajax({
url: "/somefile.php",
dataType: 'JSON',
type: 'POST',
jQuery(".togglesearch").toggle(
function () {
data: JSON.stringify({
"Name": jQuery("#searchfield").val(),
"Number": ""
}),
},
function () {
data: JSON.stringify({
"Name": "",
"Number": jQuery("#searchfield").val()
}),
}
);
var data = ["Name", "Number"];
var obj = {"Name":"", "Number":""};
var val = jQuery("#searchfield").val();
var n = 0;
var res;
$("button").click(function() {
obj[data[n]] = val;
obj[data[n === 0 ? n + 1 : n- 1]] = "";
res = JSON.stringify(obj);
$("label").text(JSON.stringify(res));
// do ajax stuff
/*
jQuery.ajax({
url: "/somefile.php",
dataType: "JSON",
type: "POST",
data: res
})
*/
n = n === 0 ? 1 : 0
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<button>click</button>
<input type="text" id="searchfield" value="123" /><label></label>
I think you'll have to put each different ajax call inside the toggles:
jQuery(".togglesearch").toggle(
function () {
jQuery.ajax({
url: "/somefile.php",
dataType: 'JSON',
type: 'POST',
data: JSON.stringify({
"Name": jQuery("#searchfield").val(),
"Number": ""
})
});
},
function () {
jQuery.ajax({
url: "/somefile.php",
dataType: 'JSON',
type: 'POST',
data: JSON.stringify({
"Name": "",
"Number": jQuery("#searchfield").val()
})
});
}
});
Try this:
jQuery(".togglesearch").toggle(function() {
var data = { "Name": "", "Number": jQuery("#searchfield").val() };
callAjax(data);
}, function(){
var data = { "Name": jQuery("#searchfield").val(), "Number": "" };
callAjax(data);
});
function callAjax(data) {
jQuery.ajax({
url: "/somefile.php",
dataType: 'JSON',
type: 'POST',
data: JSON.stringify(data),
success: function(response) { }
)};
}
In toggle finally call a function with ajax call. Let me know if it works for you.
Related
Not getting array of data from ajax to controller.
$.ajax({
type: "POST",
url: "/Home/List",
traditional: true,
contentType: 'application/json',
data: {
"Query": JSON.stringify(Query) //change this
success: function() {}
});,
And array of Query :
0: {label: "abc:", value: "123", type: "Select"} 1: {label: "xyz",
value: "Hum", type: "text"}
Can anyone help ?
Try something like this
<script type="text/javascript">
var query=[{label: "abc:", value: "123", type: "Select"},{label: "abc:", value: "1232", type: "Select"} ];
$.ajax({ type: "POST",
url: "/Home/List",
traditional: true,
contentType: 'application/json',
data: JSON.stringify(query),
success: function (){
} });
</script>
I think something along this may work for you.
function sendarray() {
var arr = [];
var json = {
"label": 'abc',
"value": 1234,
"Name": 'Name'
};
arr.push(json);
json = {
"label": 'abc2',
"value": 1234,
"Name": 'Name2'
};
arr.push(json);
var myarray = JSON.stringify(arr);
$.ajax({
url: '/controller/GetArray',
type: 'POST',
data: { array: myarray },
success: function (data) {
//Do something
},
error: function () {
//Do something
}
});
}
then in the controller
public JsonResult GetArray(string array)
{
var obj = JsonConvert.DeserializeObject<object>(array);
return Json("");
}
This will send an string with all the data in the array to the controller, then you turn string with json format into an object list
I'm using ajax and javascript for a game and I created a server using json-server where I keep a db.json file with words that the user can input and become available in the game.
db.json
This is what the json file looks like
{
"words": [
{
"cuvant": "cuvant",
"id": 1
},
{
"cuvant": "masina",
"id": 2
},
{
"cuvant": "oaie",
"id": 3
},
{
"cuvant": "carte",
"id": 4
},
{
"cuvant": "fmi",
"id": 5
},
{
"cuvant": "birou",
"id": 6
},
{
"cuvant": "birou",
"id": 7
},
{
"cuvant": "canapea",
"id": 8
},
{
"cuvant": "pasare",
"id": 9
I managed to get the POST request (adding the words to the db.json) using this:
function addWord() {
var word = document.getElementById("input-name").value;
var info = {
cuvant: word
}
$.ajax({
url:'http://localhost:3000/words',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(info),
succes: function(info) {
console.log(info)
},
error: function(error) {
console.log(error);
}
})
}
This is what I tried for the GET request
But I'm not sure if it's correct.
And I also need a way to get only the value hold by the cuvant key and add it into an array.
window.onload = function() {
function gett() {
$.ajax({
url: 'http://localhost:3000/words',
type: 'GET',
dataType: 'json',
contentType: "application/json",
succes: function(data) {
console.log(data);
},
error: function(data) {
console.log(data)
}
})
.done(function(){
console.log("Over")
})
}
}
I think your code is correct. It was just missing the "s" on "success":
window.onload = function() {
function gett() {
$.ajax({
url: 'http://localhost:3000/words',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data)
}
})
.done(function(){
console.log("Over")
})
}
}
I cannot get ajax to do a 'PUT' operation.
$('.thetest').click(function() {
console.log("Script executed");
$.ajax({
url: 'redacted for obvious reasons',
contentType: 'application/json',
success: function(result) {
alert("success?");
},
type: 'PUT',
data: {
"userId": "also redacted",
"data": {
"userSettings": {
"notificationSettings": {
"Marketing": false,
"Newsletters": true
}
}
}
},
});
});
<button class="thetest"> PRESS ME</button>
Once the button is pressed, the console.log does trigger. So I know the script is being used, it just doesn't send to the API.
Any ideas?
change type to method
$('.thetest').click(function () {
console.log("Script executed");
$.ajax({
url: 'redacted for obvious reasons',
contentType: 'application/json',
success: function (result) {
alert("success?");
},
method: 'PUT',
data: {
"userId": "also redacted",
"data": {
"userSettings": {
"notificationSettings": {
"Marketing": false,
"Newsletters": true
}
}
}
},
});
});
I am firing an ajaxcall on page load and getting an array back. Now for each element called groupId present in the array, I have to fire another ajaxcall to get the group name and group notes.
Now I need to create a final array that would have the array returned from the first ajaxcall and merged with the corresponding group name and info returned from the second call.
This is the array returned from the first ajaxcall:
[{
"customMessage": "THis is the first message",
"groupIdx": 13
}, {
"customMessage": "This is the second message",
"groupIdx": 14
}]
Which I am getting by doing:
$.ajax({
type: "GET",
url: '<html:rewrite page="/rest/pre-visit-instruction/list"/>',
dataType: "json"
}).done(function(data) {
vueInst.preVisitInstructions = data;
});
Now to this I am appending a .each function and calling another ajaxcall.
This is the final code:
$.ajax({
type: "GET",
url: '<html:rewrite page="/rest/pre-visit-instruction/list"/>',
dataType: "json"
}).done(function(data) {
vueInst.preVisitInstructions = data;
}).each(dataObj, function(j, data) {
$.ajax({
type: "GET",
url: '<html:rewrite page="/rest/group/"/>' + data.groupIdx + '/info',
dataType: "json"
}).
My question is: How do I get the data returned from the .each function and append it to the original object?
$.each() function must be inside of .done() function.
Update: According to the last comment:
You should use Array#filter.
data.data = response2.filter(function(x) {
return x.groupId === data.groupIdx;
});
Something like this:
$(function() {
var vueInst = {
preVisitInstructions: []
};
var result = [];
$.ajax({
type: "GET",
url: "https://gist.githubusercontent.com/dannyjhonston/17455e3ef90fb3cf096d1f051d4331e5/raw/ad51c85e7722a83e7085ad63e26a524b769efe50/firstData.json",
dataType: "json"
}).done(function(response1) {
$.each(response1, function(j, data) {
$.ajax({
type: "GET",
url: "https://gist.githubusercontent.com/dannyjhonston/e610dd23f830b108bc1e24c78f66b3b6/raw/54851535eedd1e94a1a944ddf3d63412e83349f8/secondData.json",
dataType: "json"
}).done(function(response2) {
data.data = response2.filter(function(x) {
return x.groupId === data.groupIdx;
});
result.push(data);
});
vueInst.preVisitInstructions = result;
});
});
$("#btnCheck").on("click", function() {
console.log(JSON.stringify(vueInst.preVisitInstructions));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="btnCheck">Check data</button>
The result should be:
[{
"customMessage": "THis is the first message",
"groupIdx": 13,
"data": [
]
},
{
"customMessage": "This is the second message",
"groupIdx": 14,
"data": [{
"groupId": 14,
"groupName": "Test 1",
"groupNotes": "THis is a note"
},
{
"groupId": 14,
"groupName": "Test 2",
"groupNotes": "THis is a note"
},
{
"groupId": 14,
"groupName": "Test 3",
"groupNotes": "THis is a note"
}
]
}
]
I'm making an API call with this code:
$.ajax({
type: "GET",
url: "https://example/example.json",
beforeSend: function(xhr) {
xhr.setRequestHeader("apikey", "user")
},
success: function(data){
alert(data.folder.item);
}
})
That returns nothing, except for an error in the console saying:
"Uncaught TypeError: Cannot read property 'item' of undefined"
The JSON data looks like this when I use the url in the browser:
{
"folder": {
"item": 123123,
"item 2": false,
"item 3": "content",
"item 4": [
{
"subitem": "content"
},
{
"subitem": "content2"
}
]
}
}
I was expecting "123123" in the alertbox, but nope. So what am I doing wrong?
If its a JSON string you are getting it will need to be parsed. Try this:
$.ajax({
type: "GET",
url: "https://example/example.json",
beforeSend: function(xhr) {
xhr.setRequestHeader("apikey", "user")
},
success: function(data){
var parsed = JSON.parse(data);
alert(parsed.folder.item);
}
});
Or to force jquery to parse it for you:
$.ajax({
type: "GET",
url: "https://example/example.json",
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader("apikey", "user")
},
success: function(data){
alert(data.folder.item);
}
});