简体   繁体   中英

CakePHP: Send current model ID to another controller via AJAX

So I'm in my edit view... let's says it's posts/edit/1

That page loads some Javascript which makes a $.get call that pulls data from a different action on the same controller (posts/foo).

How can I simply send the current model's ID to AJAX, and on to the other controller?

In this case, both actions are in the same controller, but I'm not sure that helps in this case.

if you are using jquery you can have something like this

$(document).ready(function(){
  //ajax call here
});

The thing is that once your document has loaded you just send this id to the other controller.

I hope that helps

If you only need to get the Post ID from your edit view, this is the variable you need:

$this->Form->fields['Post.id']

If its not "Post", just replace it with the model name you are using and trying to get the ID for.

UPDATED: Based on the clarification: you are right; for what you are trying to do, you need to generate the link or just the unique ID in a script tag, and then somehow use that variable in your included script. Take a look at how I did it for a CakePHP plugin . A quick summary:

  1. Include the JS files as you would normally do
  2. Create a variable in a script tag in the controller
  3. Use that variable in the included JS files

Something like this:

<script type="text/javascript">
id = '<?php echo $this->Form->fields['Post.id'] ?>;
</script>

and then use this id variable in your included Javascript file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM