Splicing and then saving json array via ajax - javascript

I'm having trouble getting my json array to accept changes. I'm trying to remove an object from the array, and it appears to work but then when I look at the json array on the server it remains unchanged. What am I missing here?
Here is the function I'm using:
$(function() {
$("#rectangle-delete").click(function() {
var selection = $('#templateSelection > option:selected').text();
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'type': 'POST',
'contentType':"application/json",
'url': 'server/php/data/' + selection,
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
var ID_clicked = $(".rectangle.selected.targeted").attr('id');
console.log('initial array is ' + json);
json.some(function(e) {
if (e.ID === ID_clicked) {
var values = json.map(function(e) { return e.ID; });
var index = json.map(function(e) { return e.ID; }).indexOf(ID_clicked);
var data = JSON.stringify(json[index]);
json.splice(index, 1);
return true; // stop the array loop
}
});
console.log('new array is ' + json);
});
});
The console shows:
initial array is [object Object],[object Object],[object Object]
and then
new array is [object Object],[object Object]
but I'm still not changing the actual json file on the server.

When you pull down the json from the server you are not getting a reference to the object on the server but you are getting a copy of the data.
So you are just modifying data on your client.
To update the object on the server you should notify the change to the server (or reverse the logic letting the server do the computation and retrieve directly the result on the client).

Related

Data received from ajax get request

I've got flask app and I'm trying to make a request from the client to backend and the other way round to validate ReCaptcha.
JS:
var onloadCallback = function() {
var captchaCallback = function(param) {
return $.get( "gettoken/" + param, function( data ) {
window.console.log(data.toString())
if (!data.success) {
window.alert("something went wrong" + data.error);
}
else {
$(".submitBtn").prop("disabled", false);
}
});
};
grecaptcha.render('html_element', {
'sitekey' : 'secret_key',
'callback' : captchaCallback
});
};
PYTHON:
#app.route('/gettoken/<g_recaptcha_response>')
def verify_recaptcha(g_recaptcha_response):
with urllib.request.urlopen('https://www.google.com/recaptcha/api/siteverify?secret=secret_key&response=' + g_recaptcha_response) as url:
data = json.loads(url.read().decode())
print(data)
return data
Data printed in python method is correct {'success': True, 'challenge_ts': '2019-11-07T11:07:22Z', 'hostname': 'localhost'}. But then data printed back in js shows: [object Object]. How should I correctly read the data return from python verify_recaptcha method?
.toString applied for an object will return [object Object]
var myObj = {};
console.log(myObj.toString());
//returns [object Object]
Try to use object attributes directly, like this:
console.log(data.success);
And just as advice: never show your API keys on public
Your code is correct. The problem is calling .toString() on an object will return that. If you want to see a log with your object try with:
window.console.log(data)
or:
window.console.log(JSON.stringify(data, null, 2))

array is empty even if it was successfully mapped

I'm running into issues with _.map (using underscore.jshttp://underscorejs.org).
getCalories: function() {
var encode = "1%20";
var calSource = "https://api.edamam.com/api/nutrition-data?app_id=#&app_key=#";
_.map(ingArray, function(elem)
{
return $.ajax(calSource, {
dataType: "json",
jsonp: "jsonp",
data: "ingr=" + encode + elem,
complete: function(r) {
var obj = JSON.parse(r.responseText);
var calorie = obj.calories;
calArray.push(calorie);
console.log(calArray);
}
});
});
},
I need to use the latest iteration of calArray in another function. However, it always comes up as undefined. So I inserted a console.log above and this is what I get:
app.js:177 is the console.log
Is this a scoping issue? Also, if it's logging prior to the push then I can see why it's coming up as undefined. How do I get around it?
I believe underscore's map produces a new array, in your case the new array will contain a bunch promises (ajax-requests)
You may want to assign this to a variable first, something like below:
getCalories: function () {
var encode = "1%20";
var calSource = "https://api.edamam.com/api/nutrition-data?app_id=#&app_key=#";
var requests = _.map(ingArray, function(elem) {
return $.ajax(calSource, {
dataType: "json",
jsonp: "jsonp",
data: "ingr=" + encode + elem
});
});
$.when.apply($, requests).then(function(results) {
console.log(results); // can you take a screenshot of this output
var calories = _.map(results, function(result) {
return JSON.parse(result.responseText).calories;
});
calArray = calArray.concat(calories);
});
}

Symfony Ajax, Transmit Data Array to controller

I'm trying to transmit an array from my twig file to another controller using Ajax.
My Ajax Code:
$(window).scroll(function () {
if($(window).scrollTop() + $(window).height()>= $(document).height()){
getmoredata();
}
})
var page = 1;
function getmoredata(array_data_file) {
var array_data_file = { {{ announces }} } ;
var theurl = '{{ path('announce_page', {'id': "id", 'game': game}) }}';
theurl = theurl.replace("id", page);
$.ajax({
type: "GET",
data: {data_array:array_data_file},
url: theurl,
dataType: "json",
cache: false,
success: function (response) {
$("#content").append(response.classifiedList);
page = page + 1;
$('#spinner').hide();
console.log(response);
},
error: function (response) {
console.log(response);
}
});
}
</script>
Controller code:
public function pageAction(Request $request, $id, $game)
{
$em = $this->getDoctrine()->getManager();
//$announces = $em->getRepository('PlatformBundle:Announce')->byGame($game);
$announces = $request->request->get('data_array');
$list = $this->renderView('announce/result.html.twig', array(
'announces' => $announces,
'game' => $game
));
$response = new JsonResponse();
$response->setData(array('classifiedList' => $list));
return $response;
}
Two problem about my code:
First is about getting a javascript variable with my entity announce who contains a lot of thing.
var array_data_file = { {{ announces }} } ;
This don't work so i try something like that
var array_data_file ={{ announces|json_encode() }};
But when i make an alert(array_data_file);
I got something like that:
object Object],[object Object],[object Object],[object Object],[object
Object],[object Object],[object Object],[object Object],[object
Object],[object Object],[object Object],[object Object]
Second thing, i got always a variable NULL from my controller
$announces = $request->request->get('data_array');
This code is for infinite scrolling system for posting infinite announce in my page. I would like to transmit my announce from my index page for not making a new research in the database like this:
$announces = $em->getRepository('PlatformBundle:Announce')->byUser($user);
Any solution for this?
Thanks everybody
EDIT:
I almost finish to solved my problem.
I have install
and now i can use this command to have a variable format with json.
var contactsArray = "{{ announces|serialize('json') }}";
Now my variable contains a very long string string.
I have change the type"GET" to "POST" because my url was too long.
Now back to my controller, i take from POST my variable
$data = $request->request->get('data_array');
But it's still a very long string and i try to back to my entity with this:
$serializer = $this->container->get('jms_serializer');
$announces = $serializer->deserialize($data, 'Wolk\PlatformBundle\Entity\Announce', 'json');
but i have an error like that
"Could not decode JSON, syntax error - malformed JSON."
The thing is, i read some post and they said to insert in each variable of my entities
#JMS\Serializer\Annotation\Type("string")
But it's too long, i have a lot of variable and entity from my announce x/
Here i am

How to convert array in json format in jquery

I am trying to send ids(as array) in json format for that I used JSON.stringify(ids); and stored in variable z I am using array at server side to get values.
var ids = $("#infolist li div.No").map(function() {
return this.id;
}).get();
alert(ids);
console.log(ids);
if (ids) {
var z = JSON.stringify(ids);
alert(z);
$.ajax({
url: "UpdateNotification",
dataType: "json",
data: {ids: z},
success: function(data) {
console.log(z);
alert("success " + data.st);
}
});
}
console.log(ids) is showing ["25","27","28"].
console.log(z) is showing ["25","27","28"].
My problem is it is not calling server side method.
I may be due to not proper json format of data.
How to make it correct?
EDIT
At url If I use directly
http://localhost:8084/tt/UpdateNotification?ids=%5B%2225%22%2C%2227%22%2C%2228%22%5D
No server side method is called. This is the output of JSON.stratefy(ids).
But If I use below
http://localhost:8084/tt/UpdateNotification?ids=%2225%22&ids=%2226%22&ids=%2227%22
This calles ther serverside method
No need for var z = JSON.stringify(ids);.
Just do:
// ...
data: { ids: ids },
// ...

how to return array from jquery.ajax()

I have this piece of code:
var suggest=$.ajax({
cache: true,
type: 'GET',
url: solrServer + "suggest?q=" + valore + ec + "wt=json&omitHeader=true&json.wrf=?",
dataType: "jsonp",
success: function (data) {
data = parse();
function parse() {
var parsedQueries = [];
for (var i = 0; i < data.spellcheck.suggestions[1].suggestion.length; i++) {
console.log('i_esimo: ' + data.spellcheck.suggestions[1].suggestion[i]);
parsedQueries[i] = data.spellcheck.suggestions[1].suggestion[i];
}
return parsedQueries;
}
}
});
console.log('suggest: ' + suggest);
when i print in console:
console.log('i_esimo: ' + data.spellcheck.suggestions[1].suggestion[i]);
I visualize all element of response and after i assign it at array parsedQueries, finally return parsedQueries, that should be assigned to my var suggest, but when i print in console suggest, i have:
suggest: [object Object]
and not my array of value. The question is: how do I return an array of values (string) from 'success' of jQuery.ajax() ???
Since ajax is executed asynchronously it is not possible to return a value from ajax request.
One possible solution is to make the request synchronous using the async: false flag, but it is not recommended.
Another solution is to use a callback method, to handle the result of the ajax request
You should JSON encode your array at the server side which will transfer it back as JSON object and mention dataType :'JSON' in your ajax call for this purpose.

Categories

Resources