I would like to be able to authenticate a user in Joomla via an AJAX call so I can create the error effect if the login is incorrect and redirect the user if it is correct.
I would prefer to do it through the JQuery's .ajax API.
Also, do I need to somehow initialize JQuery or it is there already you just have to use "JQuery" instead of the "$"?
Try this,
You can use Joomla's login options for Ajax login authentication.
collect your user name and password via post and set to the array.
$options = array();
$options['remember'] = JRequest::getBool('remember', false);
$data['username'] = JRequest::getVar('username', '', 'method', 'username');
$data['password'] = JRequest::getString('password', '', 'post', JREQUEST_ALLOWRAW);
$credentials = array();
$credentials['username'] = $data['username'];
$credentials['password'] = $data['password'];
$app = JFactory::getApplication();
$error = $app->login($credentials, $options);
if (!JError::isError($error)) {
// login success
}
else{
//Failed attempt
}
The above code section can be write inside any of your controller function if you have any custom component. If your are using Joomla3.x you can use com_ajax for this task .
var data = "";//set your user name and password
jQuery.ajax ({
type: "POST",
url: "index.php?option=com_ajax&task=loginauth",
data: data,
success: function(data) {
}
});
When you include the jQuery library in your application then just access it with jQuery
'$' is used for moo-tools in Joomla.For including jQuery library you can just edit the template file templates/yourtemplate/index.php
Hope its helps..
Related
I'm sorry but I'm having a hard time setting up something simple but that doesn't work for me. I'm trying to put a code that counts the number of clicks on a phone number ( the last 4 hidden digits that appear ) then record this data in my DB. I set up the JAVASCRIPT at the bottom of my PHP page where I will listen if there is a click ( Addeventlistener.... ) on the phone number.
I understood that we can not execute PHP code in a JS script, OK, so I execute an Ajax code to send to a PHP file the values to insert in a new entry to my DB. Except that during the execution the functions that open a connection to the DB are not recognized while in the same way I use others functions in the same PHP file that selects and returns me data from the DB.
Is the difference that they are two different types of request SELECT and INSERT or it is because I send the data through Ajax that the PHP files that load the function of DB connection are not loaded?
AJAX Script
<script>
var phoneclick = document.querySelector(".data-phone");
var baseUrl = "public_html/oc-content/themes/delta/"
phoneclick.addEventListener("click", function() {
var item_id = 8111;
var ajaxPhoneClick = 1;
$.ajax({
url: '<?php echo osc_current_web_theme_url('model/sql_projet.php'); ?>',
type: "GET",
data: {
id: '1111'
},
success: function(data) {
console.log(data);
}
});
});
</script>
PHP FIle
$itemId = $_GET['id'];
$conn = DBConnectionClass::newInstance();
$data = $conn->getDb();
$comm = new DBCommandClass($data);
$db_prefix = DB_TABLE_PREFIX;
$query = "INSERT INTO {$db_prefix}t_item_stats (item_id,phone_clicks) VALUES ($itemId,1) ";
$result = $comm->query($query);
The error i get is this Fatal error: Uncaught Error: Class 'DBConnectionClass' not found in /Applications/XAMPP/
I want to know the reason why this error is throwing and what should i do to bypass this
I posted this question ealier today, however I recieved a fix (thank you) that works great against my RequestBin endpoint for testing, however when submitting to my AJAX script, its a different story.
Problem: I cant submit my jQuery toggle values to my PHP AJAX script because there is no form name associated with the POST request (so db never updates). I proven this by making a HTML form with the field names and the database updated right away. However this is not the case with this JS toggle method.
jQuery code
$(document).ready(function() {
$('.switch').click(function() {
var $this = $(this).toggleClass("switchOn");
$.ajax({
type: "POST",
url: "https://--------.x.pipedream.net/",
data: {
value: $this.hasClass("switchOn") ? 'pagination' : 'infinite'
},
success: function(data) {
console.log(data);
}
});
});
});
HTML
<div class="wrapper-toggle" align="center">
<label>
<div class="switch"></div>
<div class="switch-label">Use <b>Paged</b> results instead (Current: <b>Infinite</b>)</div>
</label>
</div>
PHP AJAX script
if (array_key_exists('pagination', $_POST)) {
$stmt = $conn->prepare("UPDATE users SET browse_mode = 'pagination' WHERE user_id = 1");
//$stmt->bindParam(":user_id", $account->getId(), PDO::PARAM_INT);
$stmt->execute();
} else if (array_key_exists('infinite', $_POST)) {
$stmt = $conn->prepare("UPDATE users SET browse_mode = 'infinite' WHERE user_id = 1");
//$stmt->bindParam(":user_id", $account->getId(), PDO::PARAM_INT);
$stmt->execute();
}
I cant figure out how to assign a field name to this, as it is not a traditional post form. This is driving me nuts. So the previous solution was applying hasClass() and calling var $this outside of $ajax(), great (and RequestBin receives both requests), but when submitting to PHP its a dead end (no form names).
Given the code above fixed and revised twice, where do I even start without a form ??
We need:
name="pagination"
name="infinite"
But this toggle JS doesn't allow for this. prop() has been removed to get toggle submitting values over (just not my AJAX script).
Any solution appreciated. Thank you again.
You can set your values as Form Data. So the PHP Function will get it just like a traditional form submission:
$(document).ready(function() {
$('.switch').click(function() {
var $this = $(this).toggleClass("switchOn");
var formdata = new FormData();
$this.hasClass("switchOn") ? formdata.append('pagination', 'name') : formdata.append('infinite', 'name');
$.ajax({
type: "POST",
url: "https://--------.x.pipedream.net/",
data: formdata,
success: function(data) {
console.log(data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
More info on JS Form Data: https://developer.mozilla.org/en-US/docs/Web/API/FormData
I am trying to allow visitors to my site to post a tweet with an image directly from the site. I am using Codebird PHP library to accomplish this. So far everything is working correctly, however there is no preview of the post before it gets posted to the user's account. Currently, it just posts directly to their account as soon as they click the button.
What I would like is to have it pop-up a small window where it will ask them to log in if they aren't logged in yet, or it will show a preview of the tweet and allow them to click the "Tweet" button if they are logged in like in this image:
Here's my PHP:
function tweet($message,$image) {
require_once('codebird.php');
\Codebird\Codebird::setConsumerKey("MYCONSUMERKEY", "MYCONSUMERSECRET");
$cb = \Codebird\Codebird::getInstance();
session_start();
if (! isset($_SESSION['oauth_token'])) {
// get the request token
$reply = $cb->oauth_requestToken([
'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
]);
// store the token
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
$_SESSION['oauth_verify'] = true;
// redirect to auth website
$auth_url = $cb->oauth_authorize();
header('Location: ' . $auth_url);
die();
} elseif (isset($_GET['oauth_verifier']) && isset($_SESSION['oauth_verify'])) {
// verify the token
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
unset($_SESSION['oauth_verify']);
// get the access token
$reply = $cb->oauth_accessToken([
'oauth_verifier' => $_GET['oauth_verifier']
]);
// store the token (which is different from the request token!)
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
// send to same URL, without oauth GET parameters
header('Location: ' . basename(__FILE__));
die();
}
// assign access token on each page load
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$reply = $cb->media_upload(array(
'media' => $image
));
$mediaID = $reply->media_id_string;
$params = array(
'status' => $message,
'media_ids' => $mediaID
);
$reply = $cb->statuses_update($params);
}
tweet("Tweet tweet","assets/tweet.jpg");
And here's my Javascript/HTML:
function postTweet() {
$.ajax({
type: "POST",
url: 'tweet.php',
data:{action:'call_this'},
success:function(html) {
alert('Success!');
}
});
}
<button class="download-share" onclick="postTweet()">Download and Share</button>
In the button click, you need another function that open the popup along with a tweet button.
Add the click event listener as postTweet to the new tweet button.
I created a sample snippet. Check it below.
To show the real time preview, you need to add the keyup event listener to the textarea which should copy it's value and add it as the innerHTML of the preview pane.
function openTweet(){
document.getElementsByClassName("preview")[0].style.display="";
document.getElementById("tweetPr").innerHTML = document.getElementById("tweet").value;
document.getElementById("tweet").addEventListener("keyup",
function(){
document.getElementById("tweetPr").innerHTML = document.getElementById("tweet").value;
});
document.getElementsByClassName("download-share")[0].style.display="none";
}
function postTweet() {
$.ajax({
type: "POST",
url: 'tweet.php',
data:{action:'call_this'},
success:function(html) {
alert('Success!');
}
});
}
<div style="display:none;" class="preview"><textarea id="tweet"> </textarea><div id="tweetPr"></div><button onclick="postTweet();">Tweet</button></div>
<button class="download-share" onclick="openTweet()">Download and Share</button>
First things first, you(codebird) are using the twitter API to post to twitter, which makes use of the statuses/update endpoint in the API. This call is a server to server call, ie from the server where your files are hosted to the twitter server.
https://dev.twitter.com/rest/reference/post/statuses/update
There are 2 possibilities i see for you to accomplish what you have in mind
-first would be to use twitters web intent system with which you can send the tweet as a query string which would bring up the popup provided you have included the twitter js files
https://dev.twitter.com/web/tweet-button/web-intent
-second if thats not really your style then you could try something like what #ceejayoz mentioned making a new window created by you recreating the necessary inputs as shown in the picture and follow the same procedure you have now
Now to your question, Since you have an image the web intent option will not work, but if its a link with an image( twitter cards ) then i think the twitter bots should be able to read through the page and show you a preview in the popup provided you have the right meta tags on the linked page
Try use the function window.open
https://www.w3schools.com/jsref/met_win_open.asp
function postTweet() {
$.ajax({
type: "POST",
url: 'tweet.php',
data:{action:'call_this'},
success:function() {
success = true
}
});
if(success)
{
window.open('tweet.php', "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400")
}
}
I'm a new developer. I've read a lot of question all around about my topic, and I've seen a lot of interesting answers, but unfortunately, I cannot find a way to resolve mine.
I have a simple form in HTML and <div id="comment"></div> in it (empty if there is nothing to pass to the user). This DIV is supposed to give updates to the user, like Wrong Username or Password! when it's the case. The form is treated via PHP and MySQL.
...
$result = mysqli_query($idConnect, $sql);
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
header("Location: ../main.html");
} else {
//Please update the DIV tag here!!
}
...
I tried to "read" PHP from jQuery (with AJAX), but whether I didn't have the solution, or it cannot be done that way... I used this in jQuery (#login is the name of the form):
$("#login").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function(data) {
$("#comment").replaceWith(data); // You can use .replaceWith or .html depending on the markup you return
},
error: function(errorThrown) {
$("#comment").html(errorThrown);
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
But I'd like to update the DIV tag #comment with some message if the credentials are wrong. But I have no clue how to update that DIV, considering PHP is treating the form...
Can you help please ?
Thanks in advance ! :)
In order for AJAX to work, the PHP must echo something to be returned from the AJAX call:
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
echo 'good';
} else {
//Please update the DIV tag here!!
echo 'There is a problem with your username or password.';
}
But this will not show up in error: function because that function is used when AJAX itself is having a problem. This text will be returned in the success callback and so you must update the div there:
success:function(data) {
if('good' == data) {
// perform redirect
window.location = "main.html";
} else {
// update div
$("#comment").html(data);
}
},
In addition, since you're calling the PHP with AJAX, the header("Location: ../main.html"); will not work. You will need to add window.location to your success callback dependent upon the status.
To begin, your pretend is using Ajax to send form data to PHP. So your client (HTML) have to communicate completely via Ajax. After you do authenticate, you need send an "Ajax sign" to the client.
$result = mysqli_query($idConnect, $sql);
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
echo 'true';//it's better for using json format here
// Your http header to redirect won't work in this situatition
// because the process is control by javascript code. Not PHP.
} else {
echo "false";//it's better for using json format here
}
//the result is either true or false, you can use json to send more details for client used. Example: "{result:'false', message:'wrong username'}";
// use PHP json_encode(Array(key=>value)) to convert data into JSON format
Finally, you have to check the "Ajax sign" in your js code:
$("#login").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function(data) {
// You can use `data = JSON.parse(data)` if the data format is JSON
// Now, data.result is available for your checked.
if (data == 'true')
window.location.href = "main.html";
else
$("#comment").html('some message if the credentials are wrong');
},
error: function(errorThrown) {
$("#comment").html('Other error you get from XHTTP_REQUEST obj');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
I have a form that submits data to parse.com using the code below:
<script>
function validateForm() {
Parse.initialize("xxxx", "xxxxxx");
var TestObject = Parse.Object.extend("Event");
var testObject = new TestObject();
testObject.save({
Name: document.forms["myForm"]["fname"].value,
Date: document.forms["myForm"]["date"].value,
success: function(object) {
$(".success").show();
},
error: function(model, error) {
$(".error").show();
}
});
}
</script>
however I was wondering if there was a way that I could simultaneously send an email with the contents of the form. Is this possible?
You would need some type of server side script to send email.
If you use PHP, you could use the mail function.
In the JavaScript, you would just send an AJAX request to the server-side file containing the code that sends the email.
Yes you can, use AJAX to send it. Here's an example code:
JavaScript
var name = "Test";
var last_name = "Last Test";
$.ajax({
type:"POST",
url:"your_php_file.php",
data:{
name : name,
lastname : last_name
},
success:function(data){
// TODO when success
}
});
And your PHP file would look like:
$name = $_POST['name'];
$lastName = $_POST['lastname'];
Note i've used different last name's on purpose.
EDIT: Forgot to mention, once in PHP you can send email either by using mail, PHPMailer or whatever you wish