Changing page with AJAX using JS - javascript

I have the following problem. I want to move the user to another page when a certian condition is met. For example, I have a text input field where a user enters a URL. I want to move the user to this url, without him pressing any kind of submit form. I'm using AJAX to achive this. I have a function that checks for the pattern the user entered, if it is found to be a valid url, the page will change to this url. and if it's not a valid url, it will write error.
I have a <div id='url'></div> that the AJAX updates with error message (on 1st load, before user entered anything) and this message continues until it a valid url was entered. when a valid url was entered, the following will be written to this DIV:
<script type="text/javascript">
window.location.href="http://google.com"; // google.com is just an example
</script>
this doesn't seem to work. but if I put the page change code instead of the error message, it is working.
Why doesn't it work after a valid URL was entered?

I don't see any need for AJAX, just normal javascript. When you find that the entered text is a valid website and you want to load it, just use window.location = "http://google.com"; // google.com is just an example directly - no need to insert it into the document.

Why do you write JS to DIV instead of just calling window.location.href="http://google.com"; ?
For example
$.ajax({
url: 'answercheck.php',
success: function( data ) {
if (data=="correct"){
window.location.href="http://google.com";
}
else
{
//show error message
}
}
});

Related

I don't want the user to get the file directly from the url

For example:
url(`https://example.com/file.exe`)
If a user visits this website directly, the user will be redirected to https://example.com/getfile.html
but allow the user to get the file if the user gets the file from <a> tag of https://example.com/getfile.html
You can achieve this by removing href attribute in anchor tag and adding onclick function to the anchor tag. In onclick function send some parameter in url to get that value in your html page when user visits the page.
Click here to know how to send parameter in url.
Click here to know how to get post parameter from the url .
Still you have any confusion, you can comment your questions to this answer.
If you are using php you can get post parameter from url in a single line of code by using $_REQUEST["your post parameter name"];
I am adding a simple example for this to achieve with simple html and jquery.
with jquery document.referrer method on document ready(when user opens a page), you can get the previous url of user visited. like bellow example. for this you need to include jquery in your page by following line inserting in your page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
console.log(document.referrer);
if(document.referrer == "your url") {
your code to allow user if comes from the url you mentioned //user will get download button or you can write direct download option;
} else {
window.location = "some url"; //you can redirect user to specific url
}
});
<script>

How to redirect URL when php get string is in current url

Here is my HTML button:
<button class="button-brightgreen" onclick="cancelbutton();">Cancel</button>
Here is my JavaScript redirect:
function cancelbutton() {
var cancelURL = 'http://localhost:51937/php/searchUsers.php';
$(location).attr('href', cancelURL);
}
This is on my editUser.php page. This code works fine for me, except when there is a php GET string in the current URL such as ?user_id=19
When there is a GET in the URL and I click the cancel button, it takes me back to the same page (editUser.php) and displays ""
How can I get the redirect to work when there is a GET in the current URL?
You can check if the string user_id is present in the current URL, if present then redirect.
if (window.location.href.indexOf('user_id=') > -1) {
window.location.href = 'newURL';
}
I figured my problem out. The button was inside a form and when clicked, it would submit the form and the "" was coming from my PHP page. Taking the button out of the form, fixed my problem.

Redirect to any page and submit form details

I'm looking to submit form details using method="POST" to an external URL, then redirect the user to a 'Thank you' page after successfully completing the form.
My sample HTML/Javascript is as follows, however the page is not redirecting to Google.com as intended. Any help on fixing this would be much appreciated!
HTML:
<form action="externalURLhere" method="post" name="theForm"
id="theForm" style="margin-bottom:0px;padding:2px;background-color:#e0e0e0;" onSubmit="return
MM_validateForm(); return redirect();">
JavaScript:
function MM_validateForm() {
if ( !jQuery('#theForm #FirstName').val() ) {
alert('Please input your first name.');
jQuery('#theForm #FirstName').focus();
return false;
}
if ( !jQuery('#theForm #LastName').val() ) {
alert('Please input your last name.');
jQuery('#theForm #LastName').focus();
return false;
}
if ( !jQuery('#theForm #daytimephone').val() ) {
alert('Please input your phone number.');
jQuery('#theForm #daytimephone').focus();
return false;
}
if ( !jQuery('#theForm #Email').val() ) {
alert('Please input your email.');
jQuery('#theForm #Email').focus();
return false;
}
if ( !jQuery('#theForm #BID').val() ) {
alert('Please select your preferred campus.');
jQuery('#theForm #BID').focus();
return false;
}
if ( !jQuery('#theForm #programs').val() ) {
alert('Please select your preferred program.');
jQuery('#theForm #programs').focus();
return false;
}
if ( !jQuery('#theForm #How_Heard').val() ) {
alert('Please select how you heard about us.');
jQuery('#theForm #How_Heard').focus();
return false;
}
return true;
}
// ]]></script>
<script type="text/javascript">
function redirect() {
window.location = "www.google.com";
return false;
}
</script>
When the user clicks the submit button, onsubmit event occures, and, depending on the return value of the function binded to the event, the form submits (return true) or does not submit (return false);
The function may be binded to the event using HTML:
<form onSubmit="if(/*some validation here*/){return true;} else {return
false;}"></form>
or in javascript script itself:
form1.onsubmit=function(){if(/*some validation here*/){return true;}
else {return false;}}
Generally, it does not matter;
You know, the function's body is executed until the "return" occures. Then it immediatly stops and the return value is passed to the function invoker. So, what you have wrote in the onSubmit="" HTML tag attribute is the equivalent of the following JS code:
form1.onsubmit=function(){
testPassed=validate();
return testPassed;
someValueRedirectFunctionReturns=redirect();
return someValueRedirectFunctionReturns;
}
So, you can see, that no matter if the form data test is passed or not, because your validate() function's return value (true if form is okay and false if user has entered bad data) is immediatly then returned in the event function. So, your redirect() function cannot occur, because the onsubmit event handler function is stopped and the value is returned;
To make this work, you should modify the code:
form1.onsubmit=function(){
if(!validate())
return false; //test failed, form is not passed, no need to redirect to "thank you page".
else
redirect();
}
So, the redirect function will be called if the form validation test is passed. Right here we ran in an another problem.
The only way, if the onsubmit event handler function is defined, to submit the form is to return true; -- return from the function, means stop it and proceed executing from the where it was called. When you change the window.location propterty of the page in the function, redirection occurs immediatly, so the function even do not return; -- JavaScript execution immediatly interrupts, and the new page starts loading -- of course, no data can be passed via form submition;
So, you have to
Submit form (if the data is valid) -- return true;
Somehow redirect (this means, to continue execute your JS code at another page) from the page where the form is submitted.
And... that is not possible.
You can't continue executing the JS code after the form is sent because:
The event handler function has returned. That means it is stopped.
The form is sent, and an another page is now loading. The JS code of the previous page is lost, and cannot be executed anymore.
This means, that you can't affect the behaviour of the page that you are loading (in synchronous mode) from the page, that has started the loading.
And you can't make the new page redirect to the page you want ("thank you" one).
Usual form sending is just loading a new page with additional parameters. E. g. you can't modify the page that a link on your page is following to;
Anyway, there are still several ways to acheive what you want:
If YOU own the page, where the form is submitted, you may just receive the data of the form and immediatly send the redirection header. E. g., via PHP on the server side.If the page IS NOT YOURS (you can't modify neither the server, nor the page, nor anything on the server side), then you have to work with the form in slightly different way(s):Use frames or floating frames, either loading the data into the frame(s) by the javascript code itself, or by loading another page (from the same server on which the form page is located), that you have permission to modify, and modify it. E. g.:In one frame, make a form where the user actually enters data;In another frame, make another form which contains the same fields that the first does, but hidden ones;Do not submit the first form, but pass the data from to the second form, and submit() the second one;Redirect the first frame (or the whole page) to the "thank you" page;The first frame may be even hidden (CSS: display:none) -- that won't affect the functionality.Use AJAX. That is a special technology of making HTTP request (submitting form!) from the javascript code without reloading the actual page. There may be some problems, if you try to send data to the externalURLHere page, if it is not yours. If so, you may create a "router" page on your server, which will receive the data sent by the form and route it to the target, externalURLHere page. Then you may even...Don't use AJAX. Just make the router page (when I say "page", I mostly mean a PHPscript, or another cgi technology), which will also display the "Thank you" HTML document.And so on...
I've tryied to make as complete answer, as possible, I hope it has helped.
P. S. Sorry for my English.
P. P. S. My first answer on Stack Overflow -- I may be doing something wrong, sorry.
It's tough to pin down the exact reason why it isn't working without your full code and more specific requirements.
For instance, if you are submitting to a php file, you can do the redirect in that external php file using:
header('Location: http://www.example.com/');
If you are simply submitting to another html file, you could use Ajax: How to redirect using AJAX?
Try to add protocol
window.location = "http://google.com";

How do I stop the page reload after selecting an autocomplete suggestion

I made an autocomplete for a form input field that allows a user to add tags to a list of them. If the user selects any of the suggestions, I want the page to use add the new tag to a section of tags that already exist without the page reloading.
I want this to happen with 3 scenarios:
The user types in the tag, ignores the autocomplete suggestions and presses enter.
After typing in any part of a query, the user selects one of the autocomplete suggestions with the arrow keys and presses enter.
After typing in any part of a query, the user clicks on one of the autocomplete suggestions with the mouse.
I have been able to make scenario 1 work flawlessly. However, scenarios 1 and 2 make the page reload and still doesn't even add the tag to the list.
Scenarios 1 and 2 are both called by the same function:
$j("#addTag").autocomplete({
serviceUrl:'/ac',
onSelect: function(val, data){
addTag(data);
}
});
And here is the code for addTag():
function addTag(tag){
var url = '/addTag/' + tag;
//Call the server to add the tag/
$j.ajax({
async: true,
type: 'GET',
url: url,
success:function(data){
//Add the tag to the displayed list of already added tags
reloadTagBox(data);
},
dataType: "json"
});
//Hide the messages that have been displayed to the user
hideMessageBox();
}
Scenario 1 code:
function addTagByLookup(e, tag){
if(e && e.keyCode == 13)
{
/*This stops the page from reloading (when the page thinks
the form is submitted I assume).
*/
e.preventDefault();
//If a message is currently being displayed to the user, hide it
if ($j("#messageBox").is(":visible") && $j("#okayButton").is(":visible")){
hideMessageBox();
}
else{
//Give a message to the user that their tag is being loaded
showMessageBox("Adding the tag <strong>"+tag+"</strong> to your station...",'load');
//Check if the tag is valid
setTimeout(function(){
var url = '/checkTag/' + tag;
var isTagValid = checkTag(tag);
//If the tag is not vaid, tell the user.
if (isTagValid == false){
var message = "<strong>"+tag+"</strong>"+
" was not recognized as a valid tag or artist. Try something else.";
//Prompt the user for a different tag
showMessageBox(message, 'okay');
}
//If the tag is valid
else{
addTag(tag);
}
}, 1000);
}
}
}
I know I used the e.preventDefault functionality for a normal form submit in scenario 1, but I can't seem to make it work with the other scenarios and I'm not even sure that is the real problem.
I am using pylons as the MVC and using this tutorial for the autocomplete.
So in case anyone wants to know, my problem was had an easy solution that I should have never had in the first place.
My input tag was embedded in a form which submitted every time the input tag was activated.
I had stopped this problem in scenario 1 by preventing the default event from occurring when the user pressed enter. But since I didn't have access to this event in the jQuery event .autocomplete(), I couldn't prevent it.

Loading dynamically generated jQuery page after page reload

I have a search script written in jQuery. To submit a query a user presses enter and then a URL for the results page is created which is something like #search/QUERY/. However, when you either reload the page, click a result which goes to a different page or return back from a previous page the search results are no longer there. Why could this be?
My jQuery code is:
$(document).ready(function(){
$("#search").keyup(function(e){
if(e.keyCode==13){
var search=$(this).val();
var query=encodeURIComponent(search);
var yt_url='search.php?q='+query;
window.location.hash='search/'+query+'/';
document.title=$(this).val()+" - My Search Script";
$.ajax({
type:"GET",
url:yt_url,
dataType:"html",
success:function(response){
$("#result").html(response);
}
});
}
});
});
When a user reloads the javascript, all variables and functions are reinitialized. JavaScript does not pass variables from page to page. You either need a server side solution, or use JavaScript storage. The later may not work in all browsers.
This is because you are loading the search results dynamically with an AJAX call. If the page gets reloaded, that information gets lost.
A possible solution would be to store the search query and/or results in the user session. Then you will be able to automatically add the content on page reloads.

Categories