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'; ?>');
}
Related
I have a web service that returns a string.
https://localhost:5001/mywebservice
Now, I made a HTML page with a text input.
I'd like to use to JavaScript or JQuery to call my webservice.
Then update the text input with whatever returns from my web service
https://localhost:5001/mywebservice
I tried to use the following JQuery code snippet.
But it won't work.
$('button').on('click', function (e) {
var str = $('https://localhost:5001/mywebservice').val();
$("#MyString").prop('value', str);
});
I'd appreciate it if someone can give me a hint.
Thank you for your help.
ok, so first of all, you did the event listener right.
If this script runs within the HTML file, then you can select elements from the document. Use
$("<select your input>").val()
if it is a text box or .html() if it is an element.
To request the return info of your service, do not use jquery $. it was not built to ajax.
make sure it is always up and running when you use the platform
Instead of hosting it on localhost, try running it on whatever platform this js is on.
make the localhost only display the info you are sending back
send an ajax call to your localhost website, use
$.ajax({
url:"https://localhost:5001/mywebservice",
success:function(d){
//d is your data
}
})
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!
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
}
EDIT: I have followed the advice of Happy and Bart Friederichs and it has been really helpful. Instead of using php i am using javascript and the code is now working, but i still have an issue. When I click the button on the page it displays the pic that i want but the button disappears, so i cant cycle though the rest of the pictures in the array. What going on? Any help would be appreciated.
<html>
<head>
<script type="text/javascript">
var picArray=["images.jpg","customLogo.gif.png"];
var count=0;
function changePic(){
document.write("<img src='"+ picArray[count] +"' />");
count++;
}
</script>
</head>
<body>
<button type="button" onclick="changePic()">Click Me!</button>
</body>
</html>
Your changePic() function is a PHP function however when you call onclick="changePic()" you are using HTML to call a Javascript function. If you looked at your debug window in your browser you would see an error saying that changePic does not exist.
You can not use html's onClick to call a PHP, not without either redirecting or calling 'wrapper' function in JS that loads your PHP file with arguments via AJAX and so forth.
You have a few options here.. either put your images into a Javascript array and use the onclick call to grab them from that, if your doing that, you do not even need your iframe you can just print the image directly to the page using document.write. Or, why not just set the source of the iframe to your PHP script with an argument for the array index. So where you have
src=$picArray[count]
Change to
src=whatever.php?image=1
For example. This way would only need to render the iframe once rather than on every click like you are attempting to know, you would just be changing the iframe content.
There are a heap of ways to do what you are trying, let me know if either of the above suggestions work for you.
You need to use ajax to handle the onClick event, this in turn would run a PHP page in the background which could return it a filenmae.
Then ajax / jQuery would change the actual pic
Here is a tutorial covering ajax with php:
http://www.tizag.com/ajaxTutorial/ajaxxmlhttprequest.php
Alternatively you can output all the filenames to a java script array:
echo '<script> var picarray = array() ;';
foreach($arrayPic as $pic) ...
Then just access it using js
So, I see so many people wondering how to execute JS code returned via ajax. I wish I had that problem. My JS executes, but I don't want it too!
Using jQuery 1.4.2, I'm making a GET request:
$.ajax({
url:'/myurl/',
type:'GET',
success:function(response){
$('body').html(response);
}
});
The response looks something like:
<p>Some content</p>
<script>alert("hi!");</script>
Whenever the success callback fires and the response is injected into the DOM, the alert code fires! I don't want that to happen. What can I do to prevent this?
If you can't modify the response, try to "replace" <script> tags:
"<script>alert('hi');</script>".replace(/<(\/?script)/gi, "<$1");
This should escape the tags, making they appear as plain text instead of executing.
Related links
jQuery: Parse/Manipulate HTML without executing scripts
XSS Cheat Sheet
did you try returning function() snippets like
<script>
function Hello(){
alert('Hello');
}
</script>
This way the your JS doesn't execute right away but can be called later when required. But, again it depends what you actually want to do.
Depends. Do you need the JavaScript, or can you just get rid of it? If you don't need it at all, you could do something like
response = response.replace(/<script.*?<\/script>/gi, "");
However, if you need it, you're going to need to figure out how to kill just the function call(s) that you don't want. Using your example of an alert:
response = response.replace(/alert\(.*?\)/gi, "alert");
By getting rid of the trailing parens, and whatever they contain, you stop the function call from happening. Obviously, what you'll need in your regex will depend on the actual code that's causing the problem.
$('body').html(response.replace(/(<script)[^\>]*/g,'$1 src="emptyfile.js"'));
where emptyfile.js exists but has no content.
The problem you have is that jQuery strips script tags from the html and creates a document fragment.
To elaborate
var e = $("<div>Hello</div><script>alert('hi')</script>")
e.html(); // will not display script tags as script tags are now in a document fragment
$("body").append(e); // will execute the script tags in the fragment
See John Resig's explanation and another forum post on this topic.
So, what you can do is
var e = $("<div>Hello</div><script>alert('hi')</script>")
e.filter("script").each(function(){this.text='';});
That would basically make all the scripts empty and now you can
$("body").append(e);
See this post for the fragment creating routine.