call to symfony action from jQuery

Forum to discuss ExtJS and other JS plugins

call to symfony action from jQuery

Postby extremlife » Thu Oct 14, 2010 12:11 pm

Hi,
I use no plugins, just jquery as it is with symfony. I would like to call an action in my jquery script after a click() function. I tried $.get('person/showSuccess.php'); that doesn't work and actually one needs to use the url_for() code. Can anybody help me with that?

Thanks
extremlife
Junior Member
 
Posts: 22
Joined: Mon Nov 16, 2009 12:10 am
Location: Germany

Re: call to symfony action from jQuery

Postby halfer » Fri Oct 15, 2010 11:37 am

Do something like this:

Code: Select all
$(document).ready(function() {
  $('#myid').click(function() {
    $.get('person/show');
  });
});

Points to note:

* You can only set up event handlers after the DOM ready event has fired
* You don't have to use url_for - the module and action are fine.
* If you want to pass parameters, just send 'person/show?param1=x'

Do read up on the jQuery docs though - they are excellent, IMO. Since I don't do jQuery AJAX every day I will always look at the ajax section whilst writing this sort of code.
halfer
Faithful Member
 
Posts: 10148
Joined: Mon Jan 30, 2006 1:16 pm
Location: West Midlands, UK

Re: call to symfony action from jQuery

Postby extremlife » Fri Oct 15, 2010 12:37 pm

Thank you for your fast reply, but unfortunately it doesn't work.
I tried to use alert() at the same place:
Code: Select all
$(document).ready(function() {
  $('#myid').click(function() {
    alert('TEST');
  });
});


it works fine. But the action call seems not working, because there is nothing happening. I'm so desperate, i need to get that working...
extremlife
Junior Member
 
Posts: 22
Joined: Mon Nov 16, 2009 12:10 am
Location: Germany

Re: call to symfony action from jQuery

Postby Bart00 » Fri Oct 15, 2010 1:28 pm

extremlife wrote:Thank you for your fast reply, but unfortunately it doesn't work.
I tried to use alert() at the same place:
Code: Select all
$(document).ready(function() {
  $('#myid').click(function() {
    alert('TEST');
  });
});


it works fine. But the action call seems not working, because there is nothing happening. I'm so desperate, i need to get that working...


Do you use a JavaScript debugger like FireBug? You can use it to see if and what AJAX calls are being made on your page. Is it firing a request? If yes, what is the result status?
Bart00
Member
 
Posts: 72
Joined: Tue Jan 19, 2010 9:26 pm

Re: call to symfony action from jQuery

Postby halfer » Fri Oct 15, 2010 1:29 pm

Have you got something to watch the AJAX call being made? Firebug + Firefox is a good choice.

Also check the $.get() api - make sure you are supplying all the params it needs, in the correct order.

(Happy to receive emails btw, but please ask thread questions in the thread - thanks.)
halfer
Faithful Member
 
Posts: 10148
Joined: Mon Jan 30, 2006 1:16 pm
Location: West Midlands, UK

Re: call to symfony action from jQuery

Postby extremlife » Fri Oct 15, 2010 2:31 pm

ok I tried to use the Firebug and can see the following in the console:
Code: Select all
GET http://easy.localhost/frontend_dev.php/de/userProfile/show  200OK 169ms

Header

Antwort-Header
Date   Fri, 15 Oct 2010 12:19:54 GMT
Server   Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1
X-Powered-By   PHP/5.3.1
Content-Length   5018
Keep-Alive   timeout=5, max=90
Connection   Keep-Alive
Content-Type   text/html; charset=utf-8
Anfrage-Header
Host   easy.localhost
User-Agent   Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10 ( .NET CLR 3.5.30729)
Accept   */*
Accept-Language   de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding   gzip,deflate
Accept-Charset   ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive   115
Connection   keep-alive
X-Requested-With   XMLHttpRequest
Referer   http://easy.localhost/frontend_dev.php/de/
Cookie   symfony=qtf0renn716asplhquvekeskv5


Well I don't understand much about it, but it seems generating the request! Why doesn't it show the showSuccess.php template then?
extremlife
Junior Member
 
Posts: 22
Joined: Mon Nov 16, 2009 12:10 am
Location: Germany

Re: call to symfony action from jQuery

Postby halfer » Fri Oct 15, 2010 3:49 pm

Yes, it's run the action OK, but I think you've misunderstood what AJAX does. It won't display the results on the page unless you ask it to.

AJAX is a background technology, so will let you grab data from the server without disturbing the current page. If you want, you get insert the results of the $.get() into a <div> - if that's what you want then you need to do that in JavaScript. The first thing I would do is to get the results of the $.get() and print them with alert.

If that's not what you want, then could you explain what you're trying to do?
halfer
Faithful Member
 
Posts: 10148
Joined: Mon Jan 30, 2006 1:16 pm
Location: West Midlands, UK

Re: call to symfony action from jQuery

Postby extremlife » Fri Oct 15, 2010 5:16 pm

well I just want the code in the action to execute... for example:

Code: Select all
public function executeShow(sfWebRequest $request) {
        echo "test";
}


It should show "test".

What i actually want is to get the value from a jquery combobox, save it to the database and make some other adjustions. the combobox gives me the param as well when I do it the way you said:
Code: Select all
temp = $("#combobox").val();
$.get("profile/show?id=temp");


the code in action doesn't really seem to be executed for me, although in the firebug console under the point "response" i see the complete code of showSuccess.php. Do I missunderstand something?
extremlife
Junior Member
 
Posts: 22
Joined: Mon Nov 16, 2009 12:10 am
Location: Germany

Re: call to symfony action from jQuery

Postby halfer » Fri Oct 15, 2010 10:06 pm

extremlife wrote:well I just want the code in the action to execute...

It should be doing this already.

extremlife wrote:the code in action doesn't really seem to be executed for me, although in the firebug console under the point "response" i see the complete code of showSuccess.php. Do I missunderstand something?

This sounds like your action hasn't started with a php tag (<?php) - does the code work OK if you visit http://localhost/person/show in a browser? Fix this first.

extremlife wrote:
Code: Select all
public function executeShow(sfWebRequest $request) {
        echo "test";
}


It should show "test".

Not with the javascript code you've got. As I said before, you need to read the jQuery API for $.get(). Really, please read it now! :)

Then, try something like this, and then work out how it works, rather than just using it:

Code: Select all
$(document).ready(function() {
  $('#myid').click(function() {
    $.get(
      'person/show',
      // You may be able to use the query string syntax, but this looks like the preferred way
      { id: temp },
      // This is your 'ajax query finished' event
      function(data, textStatus, XMLHttpRequest) {
        // Insert the returned data into a specific place in the document (empty it first, then append it)
        $('#yourdiv').empty().append(data);
      },
      'html'
    );
  });
});
halfer
Faithful Member
 
Posts: 10148
Joined: Mon Jan 30, 2006 1:16 pm
Location: West Midlands, UK

Re: call to symfony action from jQuery

Postby halfer » Fri Oct 15, 2010 10:09 pm

extremlife wrote:
Code: Select all
temp = $("#combobox").val();
$.get("profile/show?id=temp");

This wouldn't work anyway - I think you meant to send this url:

Code: Select all
"profile/show?id=" + temp

;)
halfer
Faithful Member
 
Posts: 10148
Joined: Mon Jan 30, 2006 1:16 pm
Location: West Midlands, UK

Re: call to symfony action from jQuery

Postby extremlife » Sat Oct 16, 2010 11:13 am

Thank you very much! I studied the jQuery API for $.get(). 8-) Having your example I think I understand it a little bit. And it works!

But I have still 2 more questions:
1) the action is executed, the echo "test"; works also fine and "test" is appended to "#yourdiv". As I understand the $.get() gives the data back and you can do something with it in a callback function. In this case it is
Code: Select all
$('#yourdiv').empty().append(data);

What if I have in my action a redirect() call? It is not redirected to the called action, although I can see the call in the Firebug console
Code: Select all
GET http://easy.localhost/frontend_dev.php/group/show/id/2

What can one do here?

2)the call works if calling it from the currently being at url: localhost/frontend_dev.php/ or localhost/frontend_dev.php/person or localhost/frontend_dev.php/group
but if I try it from f.e.
Code: Select all
localhost/frontend_dev.php/group/new
in the firebug console I see
Code: Select all
GET http://localhost/frontend_dev.php/group/person/show?id=3 404 Not Found 120ms
It adds 'group' before 'person'. How can I fix that? Maybe with routing?
extremlife
Junior Member
 
Posts: 22
Joined: Mon Nov 16, 2009 12:10 am
Location: Germany

Re: call to symfony action from jQuery

Postby defaka » Wed Oct 20, 2010 1:33 pm

extremlife wrote:What if I have in my action a redirect() call? It is not redirected to the called action

If you want to redirect to another action in an ajax request, you can do this in the ajax itself.
Code: Select all
jQuery.ajax({
  ...
  success: function (data) {
    //redirect to another action
    window.location.href = "<?php echo url_for('@yourlink') ?>"
  }
   
})
defaka
Senior Member
 
Posts: 148
Joined: Mon Feb 19, 2007 5:56 am

Re: call to symfony action from jQuery

Postby halfer » Sun Oct 31, 2010 4:21 pm

What if I have in my action a redirect() call? It is not redirected to the called action, although I can see the call in the Firebug console

I would say your action should avoid doing that for AJAX requests. However, you could send a value back, such as "location", and the javascript could then test for its existence. If it exists, then redirect in javascript, as per @defaka's approach.

Again, having output or a redirect in an action does not determine how an ajax caller will respond. You need to get the results of the request, and take deliberate action accordingly.
halfer
Faithful Member
 
Posts: 10148
Joined: Mon Jan 30, 2006 1:16 pm
Location: West Midlands, UK

Re: call to symfony action from jQuery

Postby extremlife » Tue Nov 02, 2010 1:59 pm

defaka wrote: //redirect to another action
window.location.href = "<?php echo url_for('@yourlink') ?>"
[/code]

This is exactly what I need but unfortunately it doesn't work completely. The url which ist returned is
Code: Select all
localhost/<?php echo url_for('group/show') ?>
Its not parsed correctly. If I do
Code: Select all
window.location.href = 'group/show';
it shows the correct url
Code: Select all
localhost/group/show
But I need to use somehow the url_for() construction, because it works only from the index action which is not shown by default: f.e. If I'm currently at
Code: Select all
localhost/user
make a call it returns
Code: Select all
localhost/group/show
That's fine. If I try to call it from
Code: Select all
localhost/user/test
it returns
Code: Select all
localhost/user/group/show
And this is a problem...
extremlife
Junior Member
 
Posts: 22
Joined: Mon Nov 16, 2009 12:10 am
Location: Germany

Re: call to symfony action from jQuery

Postby defaka » Tue Nov 02, 2010 6:11 pm

extremlife wrote:
Code: Select all
localhost/<?php echo url_for('group/show') ?>


You don't have to prefix the url path with 'localhost'. The url_for helper generate relative path by default. So, if you want to get the absolute path, set the absolute option to true
Code: Select all
window.location.href = "<?php echo url_for('@yourlink', true) ?>"

If you don't mind, can you post your script here?

Sorry for my poor english, it's not my mother tounge :)~:-)~:smile:
defaka
Senior Member
 
Posts: 148
Joined: Mon Feb 19, 2007 5:56 am

Re: call to symfony action from jQuery

Postby extremlife » Wed Nov 03, 2010 6:00 pm

I use jquery UI. here is the complete code. Interesting is the $get() function
Code: Select all
(function( $ ) {
      $.widget( "ui.combobox", {
         _create: function() {
            var self = this,
               select = this.element.hide(),
               selected = select.children( ":selected" ),
               value = selected.val() ? selected.text() : "";
            var input = $( "<input>" )
               .insertAfter( select )
               .val( value )
               .autocomplete({
                  delay: 0,
                  minLength: 0,
                  source: function( request, response ) {
                     var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
                     response( select.children( "option" ).map(function() {
                        var text = $( this ).text();
                        if ( this.value && ( !request.term || matcher.test(text) ) )
                           return {
                              label: text.replace(
                                 new RegExp(
                                    "(?![^&;]+;)(?!<[^<>]*)(" +
                                    $.ui.autocomplete.escapeRegex(request.term) +
                                    ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                 ), "<strong>$1</strong>" ),
                              value: text,
                              option: this
                           };
                     }) );
                  },
                  select: function( event, ui ) {
                     ui.item.option.selected = true;
                     self._trigger( "selected", event, {
                        item: ui.item.option
                     });
                                                 var temp = $( "#combobox" ).val();

                       $.get(                             
                         'group/change',
                         { id: temp },
                         // This is your 'ajax query finished' event
                         function(data, textStatus, XMLHttpRequest) {
                            window.location.href = 'user/show';
                         },
                         'html'
                       );
                     //alert("Your chosen combobox is : " + $( "#combobox" ).val());
                  },
                  change: function( event, ui ) {   
                     if ( !ui.item ) {
                        var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
                           valid = false;
                        select.children( "option" ).each(function() {
                           if ( this.value.match( matcher ) ) {
                              this.selected = valid = true;
                              return false;
                           }
                        });
                        if ( !valid ) {
                           // remove invalid value, as it didn't match anything
                           $( this ).val( "" );
                           select.val( "" );
                           return false;
                        }
                     }
                  }
               })
               .addClass( "ui-widget ui-widget-content ui-corner-left" );

            input.data( "autocomplete" )._renderItem = function( ul, item ) {
               return $( "<li></li>" )
                  .data( "item.autocomplete", item )
                  .append( "<a>" + item.label + "</a>" )
                  .appendTo( ul );
            };

            $( "<button>&nbsp;</button>" )
               .attr( "tabIndex", -1 )
               .attr( "title", "Show All Items" )
               .insertAfter( input )
               .button({
                  icons: {
                     primary: "ui-icon-triangle-1-s"
                  },
                  text: false
               })
               .removeClass( "ui-corner-all" )
               .addClass( "ui-corner-right ui-button-icon" )
               .click(function() {
                  // close if already visible
                  if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
                     input.autocomplete( "close" );
                     return;
                  }

                  // pass empty string as value to search for, displaying all results
                  input.autocomplete( "search", "" );
                  input.focus();
               });
         }
      });
   })( jQuery );

if I do it as you say
Code: Select all
window.location.href = "<?php echo url_for('@yourlink') ?>"
It doesn't generate the relative path, it shows just the php code in the url:
Code: Select all
http://mySite/<?php echo url_for('@yourlink') ?>

but I have an idea of solving this: I'll get the current url with
Code: Select all
myurl = document.URL;
and cut off the action if its there...
Thank you guys for your help!
extremlife
Junior Member
 
Posts: 22
Joined: Mon Nov 16, 2009 12:10 am
Location: Germany

Re: call to symfony action from jQuery

Postby alxkn » Thu Nov 29, 2012 2:21 am

Hi,

I try to use jquery load for ajax call. The call is very simple
Code: Select all
$(document).ready(function() {
  $('input[name=properties]').live('change', function(){
    var property_div=$('#property_div');
    var selected_value=$("input[name='properties']:checked").val();
      $('#loader_bd').show();
       property_div.load('myacton/show',{
      property:selected_value
    }, function(){
        $('#loader_bd').hide('slow');
    });

   });
});


loader_bd shows and hides and after a while the content of showSuccess.php appears inside the property_div. I expected that loader_bd will be hidden immediately after new content comes but not before it.

Any ideas what is wrong here.

Thanks.
Alex.
alxkn
Senior Member
 
Posts: 141
Joined: Mon Jun 25, 2007 10:21 pm


Return to Javascript plugins

Who is online

Users browsing this forum: Google [Bot] and 1 guest