How to iterate with javascript a json response from symfony2 - javascript

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

Related

Passing data from javascript to PHP via POST not working

Im trying to send an array, populated using javascript on client-side, to a php file in the backend.
MAIN.JS
var list = iterateItems();
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", list)
.done(function(list){});
});
function _ajax(url,data) {
var ajax = $.ajax({
type : "POST",
datatype : "string",
url : url,
data : data
})
return ajax;
}
function iterateItems() {
// array is an array populated in this function, returned to be sent to ticket.php
return JSON.stringify( array );
};
TICKET.PHP
<?php
var_dump(json_decode($_POST['list']));
?>
And executing this, I'm getting this result:
Notice: Undefined index: list in D:\127.0.0.1/prog1/final/class/ticket.php on line 2
NULL
Im not understanding why im getting an undefined index.
I tried googling this, but most responses seem to point in the direction of using some kind of HTTPS method, which is what I'm trying to achieve via POST.
Any help will be greatly appreciated. Thank you.
The 'list' undefined issue might be due to the structure of the JSON array you pass.
Try the below code and check if it works. If not let's check further :)
var list = {'list': iterateItems()};
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", list)
.done(function(list){});
});
function _ajax(url,data) {
var ajax = $.ajax({
type : "POST",
datatype : "json",
url : url,
data : data
})
return ajax;
}
function iterateItems() {
// array is an array populated in this function, returned to be sent to ticket.php
return JSON.stringify( array );
};
Your PHP Code:
<?php
var_dump(json_decode($_POST['list']));
PHP can't parse JSON parameters automatically. $_POST will only be filled in from a URL-encoded string or a FormData object.
$.ajax will URL-encode an array automatically for you.
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", array)
.done(function(list) {});
function _ajax(url, data) {
var ajax = $.ajax({
type: "POST",
dataType: "string",
url: url,
data: {list: data}
})
return ajax;
}
In PHP you then don't need to call json_decode(). The value of $_POST['list'] will be the array.

Empty Array AJAX

So I have searched around a bit in hopes of finding a solution to my problem, but have had no luck.
I am basically trying to pass data into the ajax function, but when it passes it to my php file it only returns an empty array (Yes there are a few topics on this, couldn't find any to fit my needs) , here is the console output: Array ()
Its odd because just before the ajax function I log the data, and it prints out each section with no problems.The posting URL is accurate, works fine straight from my form. I have tried to use response instead of data passed through the function, but no luck their either.
Thanks in advance!
Here is the JS file
$(document).ready(function() {
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = [];
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(data); /////THIS LINE HERE ACTUALLY PRINTS DATA
$.ajax({
url: url,
type: type,
data: data,
success: function(data) {
console.log(data);
}
});
return false;
});
});
And here is my PHP
<?php //removed the issets and other checkers for ease of readability
print_r($_POST);
?>
UPDATE: I have tried to add method:"POST" to my ajax function and it still seems to be printing out blank arrays... Maybe I should convert everything to GET?
jQuery ajax() uses GET as default method. You need to mention method: POST for POST requests.
method (default: 'GET')
$.ajax({
url: url,
method: "POST",
type: type,
data: data,
success: function(data) {
console.log(data);
}
});
Or you can also use post().
EUREKA!!! Wow, the mistake was much simpler than I thought, figured it out solo! Thank you everyone for the tips! Finally got it
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {}; // THIS NEEDS TO BE CHANGED TO BRACKETS!!

AJAX/JS/PHP: How to replace text in file sent to PHP file, and pass successful attribute?

I have this button by ID of genPDF, which if clicked has this function:
$('#genPDF').click(function () {
var str = "headingText=" + jQuery("#headingText").val();
$.ajax({
url: 'indexpdf.php',
data: str,
dataType: "json",
type: 'post',
success: function () {
console.log("Success!");
}
});
})
It's supposed to take the text from input "headingText" and send to the php file indexpdf.php.
Then here's my indexpdf.php:
<?
$headingText = trim(isset($_POST['headingText']) ? $_POST['headingText'] : '');
$initialpdf = file_get_contents('file_html.php');
$initialpdf = str_replace(array(
'%headingText%'
), array (
$headingText,
), $initialpdf);
file_put_contents($fp, $initialpdf);
?>
This file is supposed to decalre the headingtext variable from the previous page, and replace each "%headingText%" in file_html.php, then save this html/php file as "file_html2.php"
The problems are, I don't think I'm saving the finalized php file right, and for some reason, while passing the "str" into the ajax php call, it doesn't succeed. If I get rid of the line, "data: str,", it succeeds.
How can I pass in these string variables, replace them in the php file, and save that file as a different file succesfully? What's wrong here?
An Alternative Way
<script>
$('#genPDF').click(function () {
var str = $("#headingText").val();
$.ajax({url:"indexpdf.php?headingText="+str,cache:false,success:function(result){
console.log("Success!");
}});
})
</script>
Use _GET
<?
$headingText = trim(isset($_GET['headingText']) ? $_GET['headingText'] : '');
$initialpdf = file_get_contents('file_html.php');
$initialpdf = str_replace(array(
'%headingText%'
), array (
$headingText,
), $initialpdf);
$initialpdf->saveHTMLFile("file_html2.php");
?>
You want to pass an object to data. For this, replace:
data: str
with:
data: { headingText: jQuery("#headingText").val() },
This should pass the value correctly
First Part
You are forcing ajax request to json type and trying to post data as string thats why its not working, try posting your headingText in JSON format i.e.
data: {headingText: jQuery("#headingText").val()}
this will make sure you receive data in PHP
Second Part
After making all the changes you can use alternate function to file_get_contents to store file once manipulation is done i.e. file_put_contents
Use it like
$initialpdf = file_get_contents('file_html.php');
$initialpdf = str_replace(array(
'%headingText%'
), array (
$headingText,
), $initialpdf);
file_put_contents("file_html2.php", $initialpdf);
this should address your both issues.
Try sending it as a json object instead of a string.
str = {headingText:'blabla'}

Cant get PHP variables using AJAX

I can't seem to figure out what's the problem. For my next little project I'm creating dynamic web page with database and etc. I need to get all the necessary variables from PHP file. But for some reason I cannot do it if I include another PHP file. (I need it for database queries).
main.php
include ('databaseQueries.php');
if (isset($_POST["points"])){
$points = json_decode($_POST["points"]);
if($_POST["execute"] == 1){
}
}
$advert= array(
'Hello' => 'Hello world!',
'bye' => 'Why bye?',
);
echo json_encode($advert, $another);
pageJs.js
$.ajax({
url : 'php/main.php',
type : 'POST',
dataType : 'json',
success : function (result) {
console.log(result);
},
error : function (err) {
console.log("Failed");
}
})
databaseQueries.php
$another = "another string";
If I remove the include and $another variable from json_encode. Everything works and I get object in console log. But if I leave the those two things, Ajax call fails.
What I'm doing wrong and how can I get both the $test array and $another variable?
Thank's in advance!
You are using json_encode incorrectly. From the documentation:
string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
You are trying to send $another to the function as the options parameter.
You could do something like this:
$ret = array($advert, $another);
echo json_encode($ret);
Unless I'm completely wrong, I can't see where you're sending anything TO your post
$.ajax({
url : 'php/main.php',
type : 'POST',
dataType : 'json'
// I would expect a data call here, something like:
data: $(form).serialize(), // OR { points: 3, execute: 1 }
success : function (result) {
console.log(result);
},
error : function (err) {
console.log("Failed");
}
})
I assume that you want to spit back some results with the format of result->key;
So Keeleon's answer above is good:
$ret = array($advert, $another);
echo json_encode($ret);
But you can also do:
//Adding everything to array, and asking json_encode to encode the array is the key. Json_encode encodes whatever is in the first argument passed to it.
$ret = array('advert'=>$advert, 'another'=>$another,'test'=>$test);
echo json_encode($ret);
Hopefully, this answers your questions.

How to access AJAX returned data with PHP?

I hava data structure like this which is then returned to another file with AJAX:
$data = array();
$data['message'] = "You are searching: $domain!";
$data['domain:name'] = "domain.tld";
$data['domain:registrar'] = "Registrar Ltd.";
$data['domain:creation'] = "2015-26-05";
$data['domain:expiry'] = "2016-26-05";
$data['ns'] = "ns1.somedns.tld";
$data['owner']['name'] = "Owner Name";
$data['owner']['type'] = "Org";
echo json_encode($data);
That data is then append to html with AJAX like this:
$.ajax({
type: 'POST',
url: 'carnetEpp.php',
data: $(this).serialize(),
success: function (data) {
dataType: 'json',
//console.log(data);
$('#response').html(data);
$("#myModal").modal();
}
});
Now I want to pass that returned JSON object to PHP variable, so I can easy manipulate date with PHP. How do I do that? Or is best practice to do it with JS? Basically I want to print every key:pair value, so maybe for in is good choice.
And, I am not sure, should, or must I echo data in my script so AJAX can pick it up, or can I just pass data to variable and then fetch it in AJAX?
You need to add this code in success.
var obj = jQuery.parseJSON(data);
alert(obj.message);
OR
var obj = $.parseJSON(data);
alert(obj.message);
You will get the message sent from PHP.
before sending data in php, setup header for response:
$data = [
'key' => 'value',
'key2' => 'vlue2'
];
header('Content-Type: application/json');
echo json_encode($data);
then if u use jquery, $.getJson() it really cool solution for handle input json data.

Categories

Resources