How do I search results from jquery GET - javascript

I'm having a bit of a problem investigating the result from my get in my script. I got the following code to check if a user is still logged in:
$.get("nowhereGet", function(result){
if($(result).find('[id="loginInput"]'))
{
//HTML is in the response then we have been logged out and the user needs to go to
window.location.href = "login";
}
});
Now if the user is logged in Struts will return one html-page in result from my get. If the user has been logged out different page will be returned one with and element id="loginInput"in it.
I thought the above would do the trick but no love. What am I doing wrong?
Is there a better way to do this than to ping the server with a random get? I need a method that performes this check using ajax and any get or post done while logged out will get intercepted and the result will be the login-page instead of the intended page

$('#result').get(......); ???
UPDATE
so the element #result would have what ever the #loginInput has
$('#result').load('login.php #loginInput');
Otherwise look for a json option because the way you are doing it, its kinda messy
Unless you are looking for this
$.get("nowhereGet", function(result){
if(result && $(result).find('#loginInput').length)
{
//HTML is in the response then we have been logged out and the user needs to go to
window.location.href = "login";
}
});

I found an other soloution and with help from Steven Benitez I got it working. Follow the link for more information but in short I let my interceptor do the work instead. If a certain path/action is called the interceptor will return a text stream that I can read from my script.

Related

Conceal URL in javascript code ( URL generated by PHP )

I am looking for a solution to the following:
I have a piece of JS code, that performs a redirection to a URL that is constructed with PHP, and that redirection is only done when the user presses a button on a confirmation dialog.
The code is, as follows:
function one() {
window.location.replace("<?php
if($new_redir == "1") {
echo "$new_second_redirect_URL/?token=$hash";
}
else {
echo "$second_redirect_URL/?token=$hash";
}
?>");
}
It works perfectly fine. What I wanna do is conceal the URL that is displayed in the source code when a user opens the page.
What would be the best way to do that?
You're thinking too much into this to be honest.
If they want to avoid the confirmation screen and get the URL from the source, there's not really much you could do.
The best really is possibly performing an AJAX request on confirmation and getting a CSRF token based URL from the response and using that, but that could end up being overkill as well.
You could also make it into an actual <form></form> form with a few hidden fields (again, such as a CSRF token), and perform the post validation onclick. If it a success - redirect them.
UPDATE:
Use robots.txt to stop bots
Build the QS with JS to stop most bots, something like:
var csrftoken='XJIWHEOU324uipHFOFUHR';
var url="http://url.com/page.php?token=";
url=url+csrftoken;
What you could also do, is something like us actually, although for your use case it could be too much.
Log every single page load into the DB, and check if if they're a first time visitor to the page after confirmation.
AJAX call (jQuery example):
$.post( "url_to_backend_page_to_get_url", {hasSubmittedForm:"true"}, function( data ) {
window.location.href = data;
});

jQuery .post() not seeming to work, no error

I've seen several questions here with the similar subject but I can't find anything which is relevant to my situation. I am trying to build jQuery code that is able to build a list of items to save it in an inventory database and I am using .post() those to a additems.php that will add them to that database (after sensitization), as well as the current path name so the .php can send the user back to the same page.
The behavior I am getting is nothing whatsoever with no console error (except the 'this works' alert when I leave that in.) The behavior I am looking for is, the page should redirect to additems.php as an html form action would, execute the code there and redirect back to this page.
Here is my piece of code:
$(document).ready(function(){
$("#button").click(function(){
alert("this works");
var itemsarray = ['itemname'];
var itemattributesarray = ['itemattribute'];
var quantitiesarray = ['1'];
$.post('additems.php', {
items:{items: itemsarray},
itemattributes:{itemattributes: itemattributesarray},
quantities:{quantities: quantitiesarray},
returnpath: window.pathname
});
});
});
Thank you for your time and any suggestions. I've never used this site so please let me know how I can improve my question as well, if you have the time.
An alternative way is,
$.ajax({
'url':'additems.php',
'method' : 'POST',
'data':{
'items':itemsarray,
'itemattributes':itemattributesarray,
'quantities' : quantitiesarray
},
success: function(data){
//here you will get ajax response
console.log(data);
}
});

Ajax Login that refresh only the logged div

Using Zoo Visitor ajax login or Ajax Auth, i manage well the ajax login witn EE.
When the user is logged, how to refresh only the div that contains: welcome user you are logged.
<div class="Welcome"><span>{username}</span> Logout</div><br />
Here is the Zoo Visitor Ajax login script:
$(document).ready(function(){
$('#loginForm').ajaxForm({
dataType: 'json',
success: function(data) {
if (data.success) {
alert('You are now logged in. You can add additional actions in the js script.');
} else {
alert('Failed with the following errors: '+data.errors.login);
}
}
});
});
I guess i have to insert a javascript code inside:
alert('You are now logged in. You can add additional actions in the js script.');
I'm still learning javascript, using
setInterval(function(){
document.getElementById('info').innerHTML =
It's a good method??Does someone has some tips??
It is possible to use a Expression Engine function??
thanks,
Stéphane
Assuming your <div class="Welcome">...</div> already exists on the page you would replace
alert('You are now logged in. You can add additional actions in the js script.');
With
$('div.Welcome').html('<span>Welcome...</span> Logout');
However, note that I removed {username}. When the user visits the page while logged out they do not have a username. When they log in via AJAX the page is not refreshed, therefore the username still remains on the server side. Zoo Visitor does not return any member data with it, either.
It might be better for you to just use a regular log in process than use AJAX if you're trying to do app-like stuff.
If you still want to stick to JavaScript for this then one thing you could do is create a template that returns the data via JSON, e.g.
{exp:http_header content_type="application/json"}
{ "username": "{username}" }
(Note the use of the http_header plugin.)
Right after a successful login you would use AJAX to check that template, then confirm the results. If username has a length then you know the person is logged in and you can update your Welcome div.
Or... you may want to try logging in via Open API by Ben Croker. Apparently its authentication returns the member data you're looking for, see http://docs.eeopenapi.apiary.io/#authentication

JS/JQuery/PHP - How to echo errors on form validate failure, and jump to div on success?

I have a fixed-position form that can be scrolled out onto the document and filled out anywhere on the page. If they fail to fill out the form properly, the errors are currently echod out onto the form, which is the intended design for that aspect. What I don't currently know how to do is, if the form is completed and $errors[] is empty, to use jQuery scrollTop() to jump down to the bottom.
Could anyone help me out with this? Current javascript involved is:
$("#A_FORM_submit_button").click(function() {
$("#FORM_A").submit( function () {
$.post(
'ajax/FORM_A_processing.php',
$(this).serialize(),
function(data){
$("#A_errors_").html(data);
}
);
return false;
});
});
The PHP involved is simply
if (!empty($errors)){
// echo errors
} else { // echo success message} <-- would like to jump to div as well
edit-- for clarity: not looking to make the page jump happen in the php file, so much as return a value for the jq $.post function to check and then perform an if/else
I might be jumping the gun here but I believe your design is wrong which is why you are running into this problem.
The ideal way of handling form validation is to validate forms via Javascript and when users enter in their information you immediately show some indicator to ask them to correct it. As long as the validation is incorrect, you should not be accepting a form request or making any AJAX calls.
In the off-chance that they do successfully send the data, you should be doing a validation check via PHP as well which, if failed, would redirect to the original page with the form. From there you could do whatever error handling you want but ideally you would retain the information they entered and indicate why it was wrong (Javascript should catch this but I guess if it gets here the user might have JS off or your validation logic might be wrong)
If I understand correctly, it seems like you are doing your error handling with Javascript (that's fine) but showing the error via PHP. As Hydra IO said don't confuse client-side and server side. Make them handle what they need to handle.
Hope this helps.
#aug described the scenario very clearly.
In code it translates in something like this
$('form').submit(function(){
form_data = $(this).serialize();
if(!validate(form_data))
{
// deal with validation, show error messages
return false;
}
else
{
// Submit form, either via Ajax $.post() or by just returning TRUE
}
});
The validate() function is up to you to work out.

How to verify signout and redirect to sign in page

In order to signout from my webapp, I need to call a json to signout (clear all cookies)
logout:->
$.get('/signout.json')
However, I am unsure how I can refresh the page + redirect the web page to the address i want e.g. /#!/signin? after the signout is successful.
if you want to solve it in javascript just use window.location = "yourlinkhere"
I use the same sort of thing to determine if I have to show a push notification.
I also use asp.net and vb.net so not sure if it will help you but you will get a basic idea of what to do :)
//admin is the controller the second is the function.
$.post("/admin/UpdateBrainBattle/
That function will return a json. in this case its about submitting a form. so you check if the form is valid or not.
in the end it shows this:
Return Json(New With {.status = "error"})
or when its good its with .status = "ok"
Then I get the json back on my page.
This is the whole function(including the post function)
$.post("/admin/UpdateBrainBattle/" + sessionId, { questionId: key, startTimeField: startTimeField, startDateField: startDateField },
function(data) {
if (data.status == 'ok'){
parentLi.find('li.onedit').hide();
parentLi.find('li.onview').show();
parentLi.find('div.dateTimeBlock div.view').html(data.value).show();
parentLi.find('div.dateTimeBlock div.edit').hide();
$('.errorBlockSummary').hide();
}
else
{
parentLi.find('span.errorBlock').show();
$('.errorBlockSummary').show();
}
});
This way you can tell your page, if everything was succesful go to this page, otherwise take this action.
Hope this helped you a bit on your way :)
Edit: noted you used a $.get instead, it can work exactly the same way as long as the function you call to has a return value you should be fine.

Categories