I'm very new to symfony2 and I'm getting some problems to load a view using ajax when the user clicks on a div. Using firebug I can see the data is returned but I can not append the result in the page.
My Code:
//Default Controller
public function indexAction($num, Request $request)
{
$request = $this->getRequest();
if($request->isXmlHttpRequest()){
$content = $this->forward('PaginationBundle:Default:ajax');
$res = new Response($content);
return $res;
}
return $this->render('PaginationBundle:Default:index.html.twig', array('num' => $num));
}
public function ajaxAction()
{
return $this->render('PaginationBundle:Default:page.html.twig');
}
}
My Js:
When clicking on #target, I'd like to load page.html.twig in my div
$("div#target").click(function(event){
t = t +1;
$.ajax({
type: "POST",
cache: "false",
dataType: "html",
success: function(){
$("div#box").append(data);
}
});
});
I'm using isXmlHttpRequest() in my controller to detect if it's an ajax request to load ajaxAction. I get that view on firebug but it's not appended in my div#box. div#box exists in index.html.twig
Thanks everybody in advance
In your
$("div#target").click(function(event) event you didn't specify the url parameter in ajax call, and another thing is you must specify an argument inside the 'success'
parameter of ajax call.
$("div#target").click(function(event){
t = t +1;
$.ajax({
type: "POST",
url: "{{path('yourpath-means header name in routing.yml')}}",
cache: "false",
dataType: "html",
success: function(result){
$("div#box").append(result);
}
});
});
Hope this helps...
Happy coding
This has nothing to do with symfony but with your ajax options. Pece is right though: You can use the return from §this->forward directly as it is a Response object.
The problem lies within your ajax options. You must pass the data object within your inner function or data is simply null. Try this:
success: function(data){
$("div#box").append(data);
}
I don't get your forward to treat AJAX call. Try this :
if($request->isXmlHttpRequest()){
return $this->forward('PaginationBundle:Default:ajax');
}
Controller::forward() already returns a Response object ;)
Related
I have a javascript function that sends to a Controller some information (mostly vars like arrays and ids) to be inserted in a table, the problem is after the insertion is completed I want to return to a different view with a data array and i cant seem to do this (I think its because of the ajax request)
Javascript Code
$('#importar').submit(function(e) {
e.preventDefault();
fdata=preparePostData();
$.ajax({
type:'POST',
url: $(this).prop('action'), // url, from form
data:fdata,
processData: false,
contentType: false,
success:function(data) {
window.location.replace(data.url);
}
});
}); // end form.submit
Function Prepare PostData()
var file_data=$('input:file')[0].files;
var postdata=new FormData();
postdata.append('_token',token);
postdata.append('startFrom',startFrom);
postdata.append('idList',idList);
postdata.append('nomeCampos',nomeCampos);
postdata.append('posicaoCampos',posicaoCampos);
postdata.append('file',file_data[0]);
return postdata;
Controller Expected Code
Do all inserts and functions and in the end
$data = array('listNome' => $listName, 'contacts' => $contacts, 'errors' => $erro);
return view("XPTO", $data);
You should not return a view from an ajax call, because you'd get the view processed code as a parameter to the ajax callback. Think of an ajax call as an async 'behind the scenes' call to the server in which you pass parameters and get some other parameters back
You should instead return a JSON response from the controller with all the parameters you'll need to call the route from JS, and parse it in your success callback. For example:
Controller
//here you should store all the parameters you need in your JS calback
$data = array('status' => 'ok', 'url' => $redirect_url );
JS
success:function(data)
{
//data will contain the parameters you set in the controller, so you can use them to call the route
if ( data.status == 'ok' )
window.location.replace(data.url);
}
Just elaborating previous answer , Ajax call controllers are used to supply some data behind the scenes and standard controllers are used to control the view so best practise is to return data (JSON) form Ajax controller to the same view which requested the data. while the standard controller should be used to control the views.
SOLVED
Not the most elegant solution but what I did was set the array with errors as an session variable and get that session var in the specific controller I need.
Controller
$request->session()->put('importErrors',$erro);
$response = array('status' =>'success','url' => '/ListarContactos/'.$idList);
return response()->json($response);
JavaScript
$('#importar').submit(function(e) {
e.preventDefault();
fdata=preparePostData();
$.ajax({
type:'POST',
url: $(this).prop('action'), // url, from form
data:fdata,
processData: false,
contentType: false,
success:function(data) {
if(data.status=='success'){
window.location.replace(data.url);
}
}
});
}); // end form.submit
XPTOController
$errorArray= $request->session()->get('importErrors');
After using it you can destroy the session variable or keep it(depending if you need it or not).
I'm using ajax to validate a from without reloadind the page.
Script Ajax
function updateResult(tab){
$.ajax({
url:"requeteSpecimen.php",
data:{datas:tab},
dataType: 'text',
async:false,
success: function(data){
document.getElementById('resultat').innerHTML = '<p>'+data+'</p>';
},
error: function(data){
document.getElementById('resultat').innerHTML = '<p>ERROR</p>';
}
});
}
$("#filtre").submit(function(){
<?php $tab=$this->request->data; ?>
updateResult(<?php json_encode($tab);?>);
});
</script>
requeteSpecimen.php
<?php echo "Success"; ?>
My problem is that ajax do not call the sucess function, I always have the "ERROR" text appearing ...
For the moment I don't have yet the code of my requeteSpecimen.php file and I just would like the success function to be called. Don't know if it can help but I'm using cakePHP 3.0.
Many thanks in advance.
You do not call actions like that in Cakephp.
First set up an Action in one of your Controllers call the url from your $.ajax function like this.
function updateResult(tab){
$.ajax({
url:"/controller/request_specimen",
data:{datas:tab},
dataType: 'text',
async:false,
success: function(data){
document.getElementById('resultat').innerHTML = '<p>'+data+'</p>';
},
error: function(data){
document.getElementById('resultat').innerHTML = '<p>ERROR</p>';
}
});
}
You could later on add a route for request_specimen and make it prettier.
In your Controller there should be a method called: public function request_specimen() {} Wich will handle the ajax request like so: if($this->request->is(['ajax']) { /* Handle request */}
The data sent to the function will be in $this->request->data;
Hi I'm trying to pass a php variable from produto.php to another file descProduto.php it ajax but without success. Please someone can tell me what I'm doing wrong? The ajax is working but I can't get the value on descProduto.php
This is where I click produto.php
<img class="btn-details" src="plus.png" data-idproduto="'.$idproduto.'"/>
My ajax ( diferent file ajax.js)
$(function(){
$(".btn-details").on('click', function(){
var idproduto = $(this).data('idproduto');
$.ajax({
type: "POST",
url: "descProduto.php",
async: false,
dataType: "html",
data: {'idproduto': idproduto},
success: function(result){
console.log("success");
},
error: function(){
console.log("error");
}
});
return false;
});
});
Where I get the variable descProduto.php
if(isset($_POST['idproduto'])){
$idproduto = $_POST['idproduto'];
echo $idproduto;
}
Thanks
Why using AJAX ? .You can't use for this matter.just use session
In page1.php
<?php
session_start();
$_SESSION['var'] = 'foo'
In Page2.php
echo $_SESSION['var']; //foo
First of all check whether your $idproduto actually prints on produto.php (Developer Tools/ FireBug/ View Source).
Then console.log(idproduto) before sending the ajax post to see whether it sets correctly.
I want to pass an array from a HTML site to a PHP script using AJAX
JS
function selectPictures() {
//selected Pictures is my JS array
var jsonArray = JSON.stringify(selectedPictures);
var request;
request = $.ajax({
url: "selectedPictures.php",
type: "POST",
data: {
data: jsonArray
},
cache: false
success: function () {
alert('OK');
}
});
}
HTML
href="selectedPictures.php" onclick="selectPictures();"
PHP
if (isset($_POST['data'])) {
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d) {
echo $d;
}
}
Actually I want to send the data to another HTML page and then include the PHP script, but I don't understand why this example does not even work. The $_POST['data'] is not set.
UPDATE
Ok, the Ajax post is actually working, as I see the HTTP request is successful BUT: I cannot access the variable instantly. I need to access the values of the passed array at once to execute another PHP script. When I want to do this, I get an undefined index error. Also at the time when the isset function is executed, it returns false (despite the successful HTTP request).
HTML
click
JS
$(function(){
$('#selectPictures').click(function(){
var jsonArray = JSON.stringify(selectedPictures);
var request = $.ajax({
url: "selectedPictures.php",
type: "POST",
data: {data: jsonArray},
cache: false,
success: function(data){alert(data);}
});
});
});
Use f12 in chrome to see errors, you forgot to add a comma after the "cache: false"
When a form sends variable with GET Method, the URL changes, putting the variables that you are passing in this way
url?variable=....
How can I get the same result with jQuery Ajax? Is it possible? Thank you
set path in your php layout/view file where you include this code
<script>
var path="<?php echo $this->webroot;?>";
</script>
and add following jquery code to post the data through ajax.
$.ajax({
type: 'POST',
url: path+'homes/createEvent',
data: {eventname:eventname,manager:manager},
async: false,
success: function(resulthtml)
{
alert(resulthtml);
},
error: function(message)
{
alert('error');
}
});
and on homes_controller.php, u will get this ajax data in createEvent function,
<?php
function createEvent()
{
$eventName=$_POST['eventname'];
$manager=$_POST['manager'];
}
?>