Symfony Ajax, Transmit Data Array to controller - javascript

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

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))

Splicing and then saving json array via ajax

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).

Unable to receive POST body from Ajax request using Play Framework

I am trying to send a POST request to my backend with some JSON data. The call from the frontend looks like this:
function register() {
var user = $("#form_reg_username").val();
var pass = $("#form_reg_password").val();
var referal = $("#form_reg_referal").val();
var postbody = {};
var url = "http://" + location.host + "/api/admin/register";
postbody.username = user;
postbody.password = pass;
postbody.referal = referal;
var jsonbody = JSON.stringify(postbody);
console.log(jsonbody);
$.ajax({
type: "POST",
url: url,
data: jsonbody,
dataType: "json",
success: registerHandler()
});
}
The generated log looks like this:
{"username":"jakob","password":"11111","referal":"urgotislove"}
Which is fine.
Here is the start of how I handle the request on the backend (I am using play 2.4)
public Result adminRegister() {
// Generate JSON from postbody
ObjectNode json = Json.newObject();
Logger.info("Body: " + request().body().asText());
JsonNode body = request().body().asJson();
String username = body.get("username").asText();
String password = body.get("password").asText();
String referal = body.get("referal").asText();
...
}
Looking at my application log the Info log looks like this:
[info] application - Body: null
I am then getting a Nullpointer Exception in first line of trying to get the json values.
So for some reason the POST body seems not to be received correctly.
Thanks for any help in advance.
Turns out the Postbody was transferred correctly but for some reason the .asText() as well as the .asJson() method, did not work correctly and returned null.
I fixed my issue with this little workaround:
Http.RequestBody requestBody = request().body();
Map<String, String[]> body = requestBody.asFormUrlEncoded();
String username = body.get("username")[0];
String password = body.get("password")[0];
String referal = body.get("referal")[0];

How to iterate with javascript a json response from symfony2

i want to itarate a json response from symfony and put it in a table td>
my action :
$search = $this->getDoctrine->...;
$serializer = $this->get('serializer');
foreach ($search as $key => $value) {
$search[$key] = $serializer->serialize($value, "json");
}
$reponse = new JsonResponse($search);
return $reponse;
this is what i have in my twig ( i examine it with Firebug ):
i have a to display at least something but sometimes i have undefined or nothing ... this my javascript function
$(document).ready(function () {
var dataString = $("form").serialize();
var typerequest = $("form").find('input[name="typerequest"]').val();
$('#filtreperseance').ajaxForm({
type: "POST",
url: Routing.generate('myroute'),
data: dataString,
success: function (response) {
$.each(response, function (cle, valeur) {
$("#test").html(valeur);
});
}
});
});
EDIT 1 : Console.log
EDIT 2 :
I'd try to cut down the problem. First make sure, the JSON is valid and looks the way you expect. Don't use jQuery at this point. Call the symfony controller in your browser directly. Then check the json. http://jsonviewer.stack.hu might be of use.
Once you verfified that the JSON itself is valid and contains what you need, we can look at the jQuery part. Then we'd need the code and the errors you get.
i have done a mistake when i returned the JSOn from Controller . its Ok now

javascript: use ajax string to create object

In a javascript function, if I set:
var listnames = {
"lista": {name: "ListA"},
"listb": {name: "ListB"},
"listc": {name: "ListC"},
};
console.log(listnames);
the console shows: [object Object].
However, if I build the same text in php and retrieve it using ajax like this:
function set_listnames() {
$.ajax({
type:"POST",
url: form_handler, // a php script
data: '&action=get_listnames',
dataType: 'json'
})
.done(function (data) {
listnames = JSON.parse(data);
console.log('listnames (after parse): ' + listnames);
})
.fail(function() {
console.log ('failed');
});
the response text from the post in the console shows: "{\"lista\":{name:\"ListA\"},\"listb\":{name:\"ListB\"},\"listc\":{name:\"ListC\"}}"
and after parsing the console shows the string (same as the hardcoded values above):
{"lista":{name:"ListA"},"listb":{name:"ListB"},"listc":{name:"ListC"}}
I need the returned string to be evaluated as [object Object] in order for a plugin function I'm using to work.
How do I transform the ajax returned string into an object?
In response from server the key "name" without quotes.
Should be
{"name": "LisaA"}
You're 100% sure the first example shows [object Object]? In which browser(s) are you testing?
If you really need the parsed response to be [object Object], you can do this:
console.log( Object.prototype.toString.call( listnames ) );
But as far as wanting listnames to be an object... it already is.

Categories

Resources