2

I'm developing a web application, where I use jQuery to make Ajax calls to the server.

I'm using the url view helper to insert the URL to be called. The code inside my view scripts looks like the following:

$.ajax({
        type: "POST",
        url: "<?php echo $this->url(array('action' => 'myaction', 'controller' => 'mycontroller'), null, true); ?>",
        dataType: "html",
        data: { id: myId, format: 'xml' },
        beforeSend: function() {
            // Show pseudoprogress
        },
        success: function(html) {
            // Process response
        },
        error: function() {
            // Show an error message
        }
    });

The system is working fine, but because of this approach I can't extract the Javascript code to separate files, because I always need to run it through the PHP interpreter first.

I wonder if there is a better way to do it, so that I can keep the Javascript code as "PHP-clean" as possible (and eventually, in separate files).

Thanks in advance.

1
  • I think you can store data in JSON format and then you can use it. Commented Sep 21, 2011 at 14:33

2 Answers 2

6

Provide the url in a hidden input field or any other hidden markup element you like and get it from there with jQuery.

Example:

In the view:

<input type="hidden" id="myActionUrl" value="<?php echo $this->url(array('action' => 'myaction', 'controller' => 'mycontroller'), null, true); ?>" />

In the javascript:

url : $('#myActionUrl').val(), 
Sign up to request clarification or add additional context in comments.

1 Comment

Simple and effective. Thanks a lot!
1

I would do this:

<script type="text/javascript">
   var url = "<?php echo $this->url(array('action' => 'myaction', 'controller' => 'mycontroller'), null, true); ?>";
</script>

4 Comments

It's the same as my solution but creates clutter outside the js files.
if he use an form sure, but then he could altough use: $("#myForm").attr('action'); or?
The point is not whether or not he uses a form. As I wrote, my solution works with any hidden element (form or not). The difference is that your solution, which also works, needs additional script tags in the <head> while mine doesn't.
Ok :-) Thanxs for the details!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.