Only do things if input-text is a domain like example.com - javascript

I would like to perform a whois-query if a user enters a valid domain. This query should be done using AJAX.
This script calls function checkDomain() always if the user types something into the form field:
js = jQuery.noConflict();
js(document).ready(function() {
jQuery('#jform_domain').keyup(function() {
checkDomain();
});
});
function checkDomain() {
var $this = jQuery(this);
jQuery.ajax({
url: '<?php echo JUri::root(); ?>/index.php',
dataType: 'json',
type: 'POST',
data: {
option: 'com_domaincheck',
format: 'json',
task: 'domain.checkDomain',
domain: jQuery("#jform_domain").val(),
'<?php echo JSession::getFormToken(); ?>': 1
},
success: function(response) {
if (response.success) {
console.log(response);
jQuery("#test").html(response.message);
// if (response.message == true) {} else {}
} else {
alert(response.message);
}
},
error: function(data) {
//console.log(data);
}
});
};
Now I would like to reduce unnecessary operations and start the script only, if the user entered a domain like:
example.com
It would be really, really, really cool, if the script would change inputs like www.example.com or http(s)://www.example.com to example.com aswell.
I'm a beginner in JS and jQuery, so please do not blame me for my bad knowledge - I try to learn ;-)

You need to use Regex for domain checking. I have used a basic regex, you can modify this regex or use another to suit your needs.
$(document).ready(function() {
$regExDomain = /^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/;
$('#domain_name').on('keyup', function(){
if($regExDomain.test($(this).val() ) ){
console.info("valid domain");
}else{
console.info("invalid domain");
return false;
}
console.log("Valid domain");
checkDomain();//domain is valid so call your ajax function
});
});

Related

AJAX display the content over time

I have a script in php that displays the content and add another content one in a one second. I want to get this effect in Jquery ajax, unfortunately the text is displayed complete. How to load content on the live in ajax?
My Jquery code:
<div class="div"></div>
<script src="//code.jquery.com/jquery.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: 'content.php',
type: 'post',
data:{
name: 'name'
},
success: function(r){
$('.div').html(r);
}
})
});
</script>
content.php
<?php
echo "one";
ob_end_flush();
flush();
sleep(1);
echo $_POST['name'];
?>
To do exactly what you're asking, you'll need to change your PHP to do echo, flush(), ob_flush(), sleep() and then do something like:
$.ajax('content.php', {
type: 'post',
data:{
name: 'name';
},
datatype: 'text',
xhrFields: {
onprogress: function(e) {
var cur, response = e.currentTarget.response;
if(last_len === false) {
cur = response;
last_len = response.length;
} else {
cur = response.substring(last_len);
last_len = response.length;
}
$('.div').html(cur);
}
}
});
But, using sleep like this is bad practice. Instead, you should handle timing in javascript and make timed ajax requests to different PHP files or with different data to get the desired output. Then, you don't need to do anything fancy just
$.ajax('content.php?first=one', {
success: function(data) {
return data;
}
});
setTimeout(function() {
$.ajax('content.php?name=name', {
success: function(data) {
return data;
}
});
}, 1000)
which makes two requests to content.php. In your example, the data was static, so I used static parameters. If you needed something dynamic, you could POST the data instead and set posted variables dynamically.
Obviously, to make the second option work, you need to edit content.php accordingly.

Detecting if a user has logged out (got no session) using php via JS, and if so - stopping the execution of the remainder of the JS function

I am trying to find a way to detect if a user has no session (which can happen in 2 ways - if the sessions expired OR if the user logged out in another browser window/tab) while running specific JS/jQuery functions.
If the user has no session, the function should stop executing at that point (return false).
I tried using AJAX like so:
function CheckForSession() {
var str="chksession=true";
jQuery.ajax({
type: "POST",
url: "chk_session.php",
data: str,
cache: false,
success: function(res){
if(res == "0") {
alert('Your session has been expired!');
}
}
});
}
chk_session.php is
require('includes/application_top.php');
$session_test = $_SESSION['customer_id'];
if($session_test == '') {
//session expired
echo "0";
} else {
//session not expired
echo "1";
}
Then I am calling that function inside:
jQuery('body').on('click','.cart_icon_div1.active.selected', function(){
CheckForSession();
//if the session doesn't exist, stop running this function, else continue to do more cool stuff
});
The problem is that I am unable to get this to work. Frankly, my js/jQuery skills are quite limited.
Any help is greatly appreciated.
Here's a callbacky version:
function CheckForSession(onLoggedIn, onLoginExpired) {
var str="chksession=true";
jQuery.ajax({
type: "POST",
url: "chk_session.php",
data: str,
cache: false,
success: function(res){
if(res == "0") {
onLoginExpired();
} else {
onLoggedIn();
}
}
});
}
jQuery('body').on('click','.cart_icon_div1.active.selected', function(){
CheckForSession(function() {
// Do any important session-required stuff here
},
function() {
alert('Your session has been expired!');
});
});
A couple things you could do:
Check login status on page load and have the status ready to go when the user clicks
pass a callback into CheckForSession which it runs when the server gives a response.
Personally I would go with option 1.

Request data from server using AJAX and Jquery

I need to create a script that takes data from a form, send it to a server (there's some diabolical C# procedure on it, that's not my job...), the server resolves the string and reply me with 4 strings (yup, they are in spanish): 'pendiente', 'verificada', 'rechazada', and finally 'error'
Now, I have to get that response and properly show the correct message (hidden-inline html).
All this procedure shouldn't "refresh" the actual page, so I'm using AJAX for this.
Have in mind I'm a newbie :) I've learned Jquery just for this task,
and I have to say I'm quite happy with this.
The problem
I don't really know how to handle or "manipulate" that request using Jquery... I figured how to send the data to the server, but I think I'm handling incorrectly the response.
The code:
In this case I've adapted the script, every different response should get its own border color, I'm using conditionals (they are wrong for sure) to add CSS clases to an #ajax div.
So, it might have silly errors...
$(document).ready(function () {
$('#enviar').click(function (event) {
event.preventDefault(); //avoid page refresh
var consulta = $('#string').val();
$("#normal").text(consulta);
//Start AJAX!
$.ajax({
async: true,
cache: false,
type: 'post',
url: 'http://184.22.97.218:8081/chequeostatusdonation', //la del servr
data: {
html: consulta
},
dataType: 'html',
beforeSend: function () {
console.log('Sending...');
},
success: function (data) {
console.log('Just sent -'+data+'- with success dooh');
$('#ajax').html(data);
//start conditional
if (data == pendiente) {
$("#ajax").addClass(pendiente);
} else if (data == verificada) {
$("#ajax").addClass(verificada);
} else if (data == rechazada) {
$("#ajax").addClass(rechazada);
} else {
$("#ajax").html('<h1>error</h1>');
}
//end condicional
},
complete: function () {
console.log('Listo el pollo');
}
});
});
});
Here is the JSFiddle
Edit: Now, I just found these two links
learn.jquery.com/code-organization/concepts/
learn.jquery.com/code-organization/beware-anonymous-functions/
Screw my code! :D
Async is by default "true", so you don't need to mention that one in your code.
You included a link to the server (in the URL-field), but what is the file you are trying to open? You will need to include the path to where you will get the data from (file / script). To make Ajax work, you will need to respect the "same origin policy", so you can insert a relative path to the file / script.
Is the response of your call always a short string with one of those key words ('pendiente', 'verificada', 'rechazada' or 'error)? In that case I would recomment using "text" instead of "html" as dataType, as jQuery will try to parse it to a DOM-structure, which is not what you want here.
Your if-statements (and class-assignments as well) aren't working because you try to compare it to a non-excisting variable instead of the string with that value. You should use " or ' around your string to solve that.
This code should be working. If not, let me know. Include the error given in the console of the browser.
$(document).ready(function () {
$('#enviar').click(function (event) {
event.preventDefault(); //avoid page refresh
var consulta = $('#string').val();
$("#normal").text(consulta);
//Start AJAX!
$.ajax({
type: 'POST',
cache: false,
url: 'RELATIVE_PATH_HERE', //la del servr
data: {
html: consulta
},
dataType: 'text',
beforeSend: function () {
console.log('Sending...');
},
success: function (data) {
console.log('Just sent -'+data+'- with success dooh');
$('#ajax').html(data);
//start conditional
if (data === 'pendiente') {
$("#ajax").addClass('pendiente');
} else if (data === 'verificada') {
$("#ajax").addClass('verificada');
} else if (data === 'rechazada') {
$("#ajax").addClass('rechazada');
} else {
$("#ajax").html('<h1>error</h1>');
}
//end condicional
},
complete: function () {
console.log('Listo el pollo');
},
error: function() {
console.log('Problem with XHR-request');
});
});
});
Be careful with .addClass if you process multiple Ajax-calls as they will add on each other.

jquery ajax json doesnt return true

i have large form in my website and using serialize() to process the form.
my problem is:
the result always return false after the form has been completed! i checked using firebug. if false, the result being shown. it was actually data.ok == true had been called, but it didnt show the message in the page? and it didnt redirect the page to the destination address?
jquery ajax:
$("#details").live("submit", function(e){
var form = $(this).serialize();
var data_string = form;
$.ajax({
type: "post",
url: "../_include/ajax.php?details",
cache: false,
data: data_string,
dataType: "json",
success: function(data) {
if(data.ok) {
("#pop").html(data.message).addClass("oke").fadeIn("slow");
setInterval(function() {
location.href = data.redirect
},2000)
} else {
$("#pop").html(data.message).addClass("warning").fadeIn("slow");
}
}
});
e.preventDefault();
})
in PHP:
if (isset($_GET['details'])) {
if (empty($name)) {
$data['ok'] = false;
$data['message'] = 'Please enter name!';
} ................ {
.............
} else {
$db->query("UPDATE query....");
$data['ok'] = true;
$data['message'] = 'Your details has been submitted!';
$data['redirect'] = 'index.php?p=details';
}
echo json_encode($data);
}
You appear to have a syntax error in your success function (if that's not a copy/paste error):
("#pop").html(data.message).addClass("oke").fadeIn("slow");
should be:
$("#pop").html(data.message).addClass("oke").fadeIn("slow");
you check for GET in your PHP (if (isset($_GET['details']))), but send POST (by specifying the type as post) in your AJAX.
Either check the $_POST array instead of the $_GET, or change the type to get.

PHP/ Ajax/ jQuery - Equivalent for my code

I have the following code and would like to use jquery to make it simpler:
var auctionBidAjax;
function auctionBid(auction_id) {
auctionBidAjax=GetXmlHttpObject();
if (auctionBidAjax==null) {
alert ("Your browser does not support XMLHTTP!");
return;
}
var url="/cms/ajax/auctionBid.php?auction_id="+auction_id;
auctionBidAjax.onreadystatechange=function() { auctionBidReady(auction_id); };
auctionBidAjax.open("GET",url,true);
auctionBidAjax.send(null);
}
And...
function auctionBidReady(auction_id) {
if (auctionBidAjax.readyState==4) {
if (auctionBidAjax.responseText == "Bid Placed") {
document.getElementById('auctionBid' + auction_id).innerHTML=
"Place Bid";
userBids();
} else if (auctionBidAjax.responseText == "Not Logged In") {
popupCentre('popupLogin');
popupLoad('popupLogin');
} else if (auctionBidAjax.responseText == "No Bids"){
popupCentre('popupNoBids');
popupLoad('popupNoBids');
}
}
}
My PHP script adds a bid etc and echos the responseText.
You've tagged this question as jquery so you can use $.ajax():
function auctionBid(auction_id) {
$.ajax({
url: "/cms/ajax/auctionBid.php",
type: "GET",
data: {
auction_id: auction_id
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// act appropriately
},
success: function(data, textStatus) {
// do whatever
}
});
}
If you didn't need an error handler you could use the simpler form of $.get() instead:
function auctionBid(auction_id) {
var url = "/cms/ajax/auctionBid.php";
$.get(url, { auction_id: auction_id }, function(data, textStatus) {
// do whatever
});
}
I actually prefer not to use error handlers. It's a little uglier than it needs to be. Use that for actual errors. Things like "not logged in" could be handled by the success handler. Just pass back a JSON object that contains the required information to tell the user what happened.
For this you could use the $.getJSON() shorthand version.
function auctionBid(auction_id) {
var url = "/cms/ajax/auctionBid.php";
$.getJSON(url, { auction_id: auction_id }, function(data) {
if (data.notLoggedIn) {
alert("Not logged in");
}
...
});
}
To return some information as JSON from PHP use json_encode() and set the MIME type appropriately:
<?php
session_start();
header('Content-Type: application/json');
echo json_encode(array(
'highBid' => get_new_high_bid(),
'loggedIn' => $_SESSION['loggedIn'],
));
exit;
?>
I'm making assumptions about your login system so the above is a gross simplification.
Return that to a $.getJSON() callback and you should be able to do:
alert(data.highBid);
alert(data.loggedIn);
JQuery.get is what you need
http://docs.jquery.com/Ajax/jQuery.get

Categories

Resources