CakePHP: Send current model ID to another controller via AJAX - javascript

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:
Include the JS files as you would normally do
Create a variable in a script tag in the controller
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.

Related

Writing to file on github pages using javascript

Is there any way of writing to a file on github pages using javascript? I want to save some info that i wanna use elsewhere to a json file (preferably, but txt would also work), and was wondering if it was possible.
Step-by-step guide
If you are less of a JavaScript maven, then you might want to follow use step-by-step.
Embedded JavaScript
In the first example we create a Markdown file called js.md In that Markdown file we put an HTML div element with an id "text". Later in that file we add a script tag and inside we write some simple JavaScript code. This code will locate the element that has the id "text", or div element, and inside the element it will put the text that appears on the right-hand side of the assignment.
The main thing you need to remember here is that the JavaScript code must come at the end so by the time it is executed the DOM is ready. Otherwise the JavaScript code will not find the HTML element.
examples/github/js.md
<div id="text"></div>
<script>
document.getElementById("text").innerHTML = "Text added by JavaScript code";
</script>
jQuery loaded from external file
Our next step is to use jQuery instead of vanilla JavaScript. For this we only need to load jQuery from its CDN. If we are already loading an external JavaScript file, I though we can also move our code to an external file. So I created the demo.js file loaded it using another script tag.
This time we can put the script tags anywhere we like as the jQuery callback function will be only executed when the DOM is ready. The only limitation is that we need to load our code after we have loaded jQuery itself.
examples/github/jquery.md
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="/demo.js"></script>
<div id="text"></div>
In our jQuery code we have an anonymous callback function that will be called when the HTML was loaded and the DOM is ready. That's what $().ready does. Inside the function we use the $("#text") expression to locate the element with id "text" and then we use the html method to set the content of the element. (It is the same as innerHTML in vanilla JavaScript.)
examples/github/demo.js
$().ready(function() {
$("#text").html("Text added by jQuery code.");
});
Loading JSON data from server
Finally, we would like to get some data from the server. As we cannot run anything on the server we cannot get dynamic data, but we can store the data in JSON files and load them using the Ajax methods provided by jQuery.
In this example the Markup file is effectively the same as in our previous examples.
examples/github/json.md
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="/json.js"></script>
<div id="text"></div>
In the jQuery code we use the getJSON method to fetch the data.json file from the server. This means, first the HTML file that was generated from the Markdown file will be loaded. Then the browser will load jQuery followed by our code. Then, once everything is ready, our code runs and loads the JSON file from the server.
The first parameter of getJSON is the URL of the JSON file we would like to load. The second parameter is an anonymous callback function that will be executed when we get the response from the server. Then the jQuery will call our anonymous function and it will pass the content of the JSON file after it was converted to a JavaScript object.
console.log(data); was only added for debugging.
In the last JQuery code, in $("#text").html(data["text"]); the first part $("#text") will locate the element with the id "text". The html method will set the content of the element to the value we pass to it which in our case is data["text"], the value of the "text" key that arrived from the JSON file.
examples/github/json.js
$().ready(function(){
$.getJSON( "/data.json", function( data ) {
console.log(data);
$("#text").html(data["text"]);
});
});
This is the data.json
examples/github/data.json
{
"text" : "Text supplied in the JSON file"
}
Hope this helped!

Echo the src value of an iframe on a page

If I have a file called 'index.php' and this file contains a lot of HTML lines...
Also (index.php) have this iframe:
<iframe src="http://test.com" />
How I can use PHP to get the src which is "http:/test.com" ... so it will be like that:
$getiframesrc=THE_CODE_WHICH_I_WANT_SOMEONE_TO_TELL_ME_ABOUT_IT;
And I can easily echo the src of the iFrame by echo $getiframesrc;
For example: If I want to make a browser using PHP, I want the URL Address Box's text to be the value of the iframe src (THIS IS ONLY AN EXAMPLE!!!)
So, please guys tell me what should be :
"THE_CODE_WHICH_I_WANT_SOMEONE_TO_TELL_ME_ABOUT_IT" .
EDIT: $getiframesrc will be in index.php too!
And thanks :-)
you can use ajax and jquery to get the src value then send it to the php file
Jquery
$(document).ready(function(){
var vidsrc = $("#iframeid").attr("src");
$.post( "index.php", { videosource: vidsrc });
});
index.php
if (isset($_POST["videosource"]))
{
$videosource = $_POST["videosource"];
// code to be excuted
}
Here's a working example -- and make sure you close your <iframe> tag.
$('button').click(function(){
var src = $('iframe').attr('src');
alert( src );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button>Read iframe src</button>
<iframe src="http://test.com"></iframe>
To re-use the src variable elsewhere on the page, just declare it outside the $('button').click(function() function -- or even outside the $(document).ready() fn.
EDIT:
To get the variable data to PHP... By the time the javascript runs, the DOM has been rendered. PHP has finished execution and will not run again on that page.
So, what to do? How to get the variable into PHP? You have two choices:
(1) Use a form - When submitting a form, the data is sent to the PHP file specified in the action= attribute on the <form> opening tag:
<form action="your_secondary_php_file.php" method="post">
Downside to a form is that user is navigated away from the page, or (at the very least) the page is refreshed.
(2) Use AJAX. AJAX (very simple, not to worry) will send your data to a back-end PHP file, the PHP file can do something with that data, and then it can (optionally) send new data/HTML/text/whatever back to the AJAX code block.
Advantage of using AJAX - will not refresh or move away from the current page. All user-entered data remains as is, and you can pro-grammatically receive data back from the PHP side and dynamically update the page with the new data. Magic by another name.
This answer contains some simple examples of AJAX.
Firstly, thank you very much #gibberish ( gibberish ) for your answer, it's the best answer for me and I'm using it now :-) .
I figured out how to do that with PHP (thanks for #gibberish to help, because his example helped me.) - But sorry :/ I can't say how I did that because it's very hard coded (everything is manual in that) ... so I will simplify it and post the answer :-)
Next to the #gibberish answer, we can use PHP GET variable and set the iFrame src with it.
Example:
PHP Part in index.php :
<?php
$iframesrc=$_GET['iframesrc'];
?>
HTML Part in index.php :
<iframe src=<?php echo $iframesrc; ?>></iframe>
And then we can access http://Mysite.tld/index.php?iframesrc=http://test.com ;)
So now, I can code well - like that:
if($iframesrc !=="http://test.com")
{
//code
}

jQuery.ajax replace PHP code

I'm trying to update a REST search result with ajax to not reload a new page.
right now search result is shown within:
<div id="searchtable"><?php include 'hotels/hotelList.php';?></div>
On click on button I want to reload this div element so it includes a new php file.
Button:
<button onclick="myFunction()">LOAD</button><br /><br />
jQuery
<script>
function myFunction() {
$.get( "/hotels/hotelSortBy.php" );
$('#searchtable').replaceWith('<?php include 'hotels/hotelSortBy.php';? >');
}
</script>
I'm not able to replace the div element "searchable" - with replaceWith - Am I doing this right ?
There's no need for inline PHP if you're using AJAX. Try using jQuery's .load AJAX method:
function myFunction() {
$('#searchtable').load('/hotels/hotelSortBy.php');
}
Note that this is slightly different than .replaceWith -- using .load will preserve #searchtable and put the new content inside of it, rather than replacing it.
You're misunderstanding a key element here. Your javascript is running on the client side, while the php runs on the server side (at least usually). Javascript doesn't interpret php and php doesn't interpret javascript either (except json). What you probably want to do is an ajax request to call the url that serve this php file, so that your webserver interpret php and return a response. Check http://api.jquery.com/jquery.ajax/ probably?
Try using .html instead of replaceWith.
So it would look like
function myFunction(){
$('#searchtable').html('<? php include 'hotels/hotelSortBy.php'; ?>');
}

pass variables through html files

I would like to know if there is any approach to pass vars through .html files.
For example in my index.html an <a> click sets this:
var value = 'some text here';
and links to other.html.
The first executed script in my other.html is:
console.log(value);
Is this somehow that HTML files can pass variables through?
You can send any data from one page to another by passing it as queryString like host/other.html?value=something
In first page append your data with the url using javascript or jquery and in second page retrieve it using javascript or jquery

Perform jQuery operations on an HTML page that was retrieved via Ajax?

Let's say you're retrieving a complete HTML page using Ajax. You now have a page of HTML in a variable.
Assuming you need to find and extract some data from that page, how do you do it?
Traditionally I've done this using regular expressions, but I'm wondering if there's a way to perform jQuery operations on that retrieved source code instead. It would simplify things tremendously, as jQuery is built for parsing HTML DOM trees.
I'm thinking maybe appending the retrieved source to the current page DOM in hidden form...? Is there a better way?
jQuerys parseHTML might be what you are looking for: http://api.jquery.com/jquery.parsehtml/
If I understand you well, you have the html code of the page loaded through ajax in a variable (let's call it data), and then you want to search through it using jquery operations.
You could create a container in your first html page, and then fill it with the content returned by Ajax. You can then handle it normally with jQuery
So:
<body>
<div id="first_page">
<h3>First page</h3>
<p>This the page that makes the Ajax call</p>
</div>
<div id="ajax_container"></div>
</body>
Now, after you Ajax call, you fill the container with data
$("#container").html(data);
Then, you can use .find(), or simply write an appropriate jquery selector.
var a = $("#container").find("#my_id").html;
var b = $("#container #my_id").html();
Now a and b should contain the content from the element with id my_id from the page loaded with Ajax
PS: I'm not sure if you want to append the data to you current page. You don't have to, if that's not what you are trying to achieve.

Categories

Resources