How to call jquery function with php script...? - php

I tried to make a login module. I require the ability to show the message "UNAME OR PASS INCORRECT", but when uname and pass are not matching I am not able to display that error message div.
So does anyone have an idea about how to display that div when user is not authenticated?
Thanks in advance.

Like GOV said, you probably want to do this via ajax calls because it doesn't require the user to leave the page as he tries to login.
If you use jquery, the script would be very simple, such as :
$.post(url,{user:UNAME,pass:PASS},function(data){
try{
// EDIT: server MUST return response in text/plain as "true" or "false".
// EDIT: if(data) changed to if(data == "true")
if(data == "true")
window.location = redirectPage;
else
showError();
}catch(e){
showError();
}
});
function showError(){
$('#'+errorDivID).show();
}
where url is the url of the page that verifies the user & pass combination, which returns "true" if the user & pass values are true and "false" otherwise.
UNAME and PASS are variables that hold the user info,
redirectPage is the url of the page you want to redirect your authentificated users,
and errorDivId is the id of the div element that you want to show. The error DIV probably contains a warning message such as "invalid user+pass combination !".
Hope this helps!
EDIT: Edited to remove "eval" as it's not necessary if the server is returning a boolean.

I would presume you could do a jQuery POST to a PHP script that handels your login.
<form id='login'>
<input type='text' name='username' id='username'>
<input type='password' name='password' id='password'>
</form>
Then posting this form with jQuery instead of PHP
$.post("login.php", { username: username, password: password } );
This would post the username and password field to login.php. Then have login.php output something you can process in the same jQuery script. Have PHP return true if login is correct and false if not, then have jQuery display an error if the PHP script returns false and have jQuery do whatever as correct login if the PHP returns true.

Ashvin ,
You need to use ajax for this
http://api.jquery.com/jQuery.ajax/
make ajax call to the database and let php send a resposne back to the UI either success or failure.
If it is failure , lets show a div with different colors...

You indeed don't have to specifically use PHP for this. A good way to do this is the separation of model (your database with the user information and the queries used to access and retrieve data from it), your controller which is putting everything in motion and sending data to your template and your view (the template).
The above structure makes also clear that PHP is not specifically used for this, PHP should only have the role to access your database and give data back to the template.
Have a look at jQuery or Prototype with the Ajax examples, once you get the hang of that a whole new world opens up. :)

Related

Return javascript data to html/php from prompt

My code makes a call to a service called OneID. The code is javascript and it prompts you to authorize the sharing of your email address (stored in the OneID repository) with a site.
I need the email address to be returned to the parent page if the user clicks, "OK".
Right now, all I can get it to do is generate a javascript Alert.
Note If you decide to help with this, you'll need to create a OneID account, sorry.
<script src="https://api.oneid.com/form/form.js" type="text/javascript"></script>';
echo '<script type="text/javascript">
OneIdExtern.registerApiReadyFunction(
function(){
OneId.getUserAttributes(
{
attr: "email[email]",
authLevel : null,
selectCards : true,
forceSelectCards : true
},
function(data){
if (data.attribute_data.email.email) {
<<-- somehow send data back to page? -->>
}
}
);
}
);
</script>';
I suspect your problem is to inform your backend of the email that have just been entered.
I see 2 way to do this:
If user have a form to validate as a next step, just prepare a Hidden field and store the email in there. It will be posted when the form will be validated
In real time, you can write a script on your server and call it with the email using Jquery (at the place you put you comment: <<-- somehow send data back to page? -->>). If you need to matchwith server information, put you'll probably need to maintain a session.
On more remark: if not constraints by cross domain issue, you can make your call directy in javascript instead of curling from your backend.

Keeping $_session['username'] inside a ajax function

I've been messing with a script, and i'm now currently at the protection part.
Basically i cant manage to receive a $_session['username'] request.
I can not use cookies, as these can be faked. And it's a pretty big security hole.
Is this a common issue?
(The non-ajax and ajax page have the same session-id, and yes. i do use session_start();)
If you know any good comment-scripts it would be appriciated if you would like to link! c: )
edit:
The user logs in, and the session is started.
Now i'm combining a page/post with a modified comment script. (found here: http://tutorialzine.com/2010/06/simple-ajax-commenting-system/ )
What i've done is that i made it work with multiple pages, and removed the user & password thing that was provided with the script.
The request is something similar to this:
$user = $_session['username'];
if(!($data['user'] = $user)){
$errors['error'] = $_session['username']; //just to see if it can find the username
}
The above request returns a null value, but if i run "echo $_session['username'];" on the page that calls java, i get "powback".
EDIT:
i couldn't get this to work, but i made a bypass. I managed to insert $_session['username'] directly into the database with an other kind of validation. The current one was stupid... It should work properly now. Thank you!
How are you passing the session ID if not via a cookie? If you're passing it via URL (which is an even bigger security risk), make sure you pass it in the URL of your AJAX request.
Try this
var v="any variable to be passed";
$.post( "passingfile.php",{name:v},
function(data) {
Alert("Pass OK");
});
return false;
});
If you for the security try not to pass session id via url
you can use this inside any function or document ready. and change page name where you want to post value.
var postRecord = 'variable='+value;
$.post("PHP_Page_Where_you_are_using_session.php", postRecord, function(response,status, xhr){
if (status == "success") {
alert('done');
}
else if (status == "error") {
alert('Something went wrong, we are working to fix it');
}
});
on another page you can get post value within $_POST['variable'];
change name of variable to another one that you want to use.

Jquery Validate: How do I call the PHP file

I am very new to this javascipt, jquery world and I am having great difficulty getting to grips with it.
I have got the following in my HTML
$(document).ready(function(){
$("#frmEnquiry").validate();
});
</script>
It works although I do not understand, what is going on behind that statement, especially as it validates on each field entry (which is wonderful).
I have action="" in my form definition and a submit button and I have created a process.php file which further validates and sends an email, but I have no idea how I call that php file or where I put the call or what the syntax is for doing it. I am assuming it is based on a return from validate().
Also what is the correct procedure for returning from the PHP file with either success or failure messages.
If anyone can help at a simple syntax level, I would be most grateful as I have looked at so many possible solutions, my head is just totally confused.
I apologise for probably asking a very common question, but when you are just starting, it is difficult finding an example which you fully understand.
Well, there are two general approaches:
Oldschool form processing: you set <form action='process.php'> so your request is submitted to that page. Browser reloads and displays the content that you have rendered in process.php
Ajax-submit: this way you leave action blank, block submitting with something like <form onSubmit = 'return false'> and then send content using one of jQuery's AJAX-methods: get, post or ajax. It looks something like that:
$(document).ready(function(){
if($('form').validate()){
$('form').submit(function{
//Personally I prefer ajax as get and post are just shorthands for this method
$.ajax({
url:'process.php',
dataType:'json',
data:{name:nameVal, value:valueVal}
success: function(){
/*server returned some data, process it as you wish*/
}
});
});
}
});
Don't forget the principles:
PHP is executed server-side
javascript is executed client-side
Thus, PHP will only be executed if you are calling the server, meaningly, if you call an URL (http://mydomain.com/MyPHPpage.php) or if you are calling your server through an AJAX request (which is seemingly the same, except there is no reload client-side).
On the contrary, javascript is called only client-side. So the code used to validate() your form is called only on the client-side (except if you have a specific function behind this that would call the server). Hence, the javascript will use the parameters you gave him to validate the form without calling the server. This is a very good way not to overload your server with un-wanted request (empty fields, wrong e-mail addresses...).
Anyway, you can still have some other checks on your server side (checking in your database if the user exists...) and return another message to the user.
To answer your question, i'll ask some other ones: what are you trying to validate? do you want to check client-side or server-side? which data and for which purpose?
You need an AJAX call to your PHP script. If your form data is valid you would do such a call. You can asign a success callback to the ajax request where you can process the return data from PHP and either update data, display a error message or something else. From PHP you can return an object or an array where you detail if errors occured and of what type. More about AJAX -> http://api.jquery.com/jQuery.ajax/
In your case it is reasonable to perform form validation via javascript by checking the value of each field.
There is no need to send data to the server and receive information about their correctness. This method complicates the validation and is not improve protection against bad data.

How to query database using javascript?

Another question by a newbie. I have a php variable that queries the database for a value. It is stored in the variable $publish and its value will change (in the database) when a user clicks on a hyperlink.
if ($publish == '') {
Link to publish.html
} else {
Link to edit.html
}
What is happening in the background is i am querying a database table for some data that i stored in the $publish variable. If the $publish is empty, it will add a link for publish.html in a popup. The popup will process a form and will add the data to the database and which means that the $publish is no more empty. What i would like to achieve is that as soon as the form is processed in the popup and a data has been added to the database, the link should change to edit.html. This can happen when the page will re-query the database but it should happen without page refresh.
How can it be donw using javascript, jquery or ajax?? Please assist.
Javascript by itself cannot be used to deal with database. That is done using php (Or the server side language of your choice). Ajax is used to send a request to your php script using javascript which will in turn communicate with the db. And it doesn't require a page refresh.
So what you are trying to do can be easily achieved using ajax. Since you mentioned jquery, you can check out the $.ajax or $.post methods in jquery which make the process even more simple.
You need to process the form using ajax. The ajax request is sent to a php script which will make the necessary changes in the database and send the new link (link to edit.html) in the response. Upon getting the response, just replace the current anchor element with the new one ..
for eg..
$.post(url, formdataobject , function (resp) {
$("a.youra").text('edit').attr('href', resp);
});
url - where the php script is located
formdataobject - a javascript object that will have the form data as key value pairs
the third parameter is an anonymous function also known as callback function since it will be invoked only when the response is received from the server. This is because ajax requests are asynchronous.
Inside the callback function, jquery is used to change the text inside the anchor element to edit and the href attribute is changed to value that came in the response.
$.post means we are using the post method. so the parameters can be accessed as elements of $_POST array in php.
After updating the db, you can simply echo out the new link and it will be received in the response.
Also, there are other formats in which you can get the response for eg. xml, json.
I'll try to leave the technical jargon aside and give a more generic response since I think you might be confused with client-side and server-side scripting.
Think of javascript as a language that can only instruct your WEB BROWSER how to act. Javascript executes after the server has already finished processing your web page.
PHP on the other hand runs on your web server and has the ability to communicate with your database. If you want to get information from your database using javascript, you'll need to have javascript ask PHP to query the database through an AJAX call to a PHP script.
For example, you could have javascript call a script like:
http://www.myserver.com/ajax_function.php?do=queryTheDatabase
In summary: Javascript can't connect to the database but it can ask PHP to do so. I hope that helps.
Let me try, you want to change the link in a page from a pop-up that handles a form processing. Try to give your link a container:
<div id="publish_link">Publish</div>
As for the form submission use Ajax to submit data to the server to do an update and get a response back to change the link to edit or something:
$.post("submit.php", { some_field: "some_value"}, function(response) {
if(response.isPublished)
$('#publish_link', window.opener.document).html('Edit');
});
Basically your publish link is contained in a div with an ID publish_link so you change its content later after data processing without reloading the page. In the pop-up where you would do the form processing it is done using jQuery Ajax POST method to submit the data. Your script then accepts that data, update the database and if successful returns a response. jQuery POST function receives that response and there's a check there if isPublished is true, get the pop-up's opener window (your main window) and update the link to Edit. Just an idea, may not be the best out there.
It cannot be made with javascript, jquery or ajax. only server side script can query a database. with ajax request you can get the script output. ajax requests can be sent either with pure javascript or jquery.
Well, i think i understand your quaestion, but you have to get a starting point, try to understand this:
try to understand what are client variables and server variables.
javascript does not comunicate with database.
you can use javascript to retrieve data to a specific "Object variable".
Using ajax methods of jquery you can post that data do other page, that will execute the
proper actions
you can ;)
at first you must create php file to query database and return something like true or flase and then with file url check the function and get answer
function find_published(folder_id) {
var aj_url = "{{server_path}}/ajax/url"
var list;
$.getJSON(aj_url+"?callback=?&",
function(data) {
//here is your data... true false ... do every thing you want
}
);
};
this app for node.js does mysql queries https://github.com/felixge/node-mysql
You need to use AJAX for this, like .post() or .get() or JSON.

Evaluating Returned Data after AJAX call with JQuery/CodeIgniter

EDIT:
I found the problem with my evaluation not working. All the text being returned from my codeIgniter functions has a space before it, so while I saw "success" it was actually " success". I don't know why it is, but I can certainly work with that.
As for the next step - opening a new view - Donny's answer was perfect!
I am using CodeIgniter for an application with JQuery for my AJAX library. I'm just learning the AJAX stuff, so I'm probably missing something basic here...
The following code if for a login form.
The goal is this -use an ajax call on the form submit so I can validate the errors and provide error messages on screen without web page refreshes. I'm doing all my validation with the CodeIgniter form_validation class.
My codeigniter function returns a text value - either an appropriate error message or the word "success." I want to evaluate the text value, and if it says "success", call another ajax function to load the needed CodeIgniter function that will load home page for logged in users.
Right now everything works in the code below until I get to the statement "if data=='success'".
Why would that return false when I know it is true because the on screen message displays "success"?
$(document).ready(function() {
$('#registration_form').submit(function(e) {
e.preventDefault();
$.post("login", {
email : $('#email').val(),
password : $('#password').val()
}, function(data) {
$('#message').text(data);
if (data == "success") {
alert(data);
post("landingpage");
}
});
});
});
You should consider using jQuery form plugins to do form submit using AJAX.
To do redirection, use this code:
window.top.location.assign(URL);
URL is the page destination. If you use CI, you can put this in view:
window.top.location.assign("<?php echo site_url(THE_PAGE_URL); ");
also, you can examine the data value in the Firebug net tab, or in Web Inspector Resource tab (Safari and Google Chrome).

Categories