How does Ajax work with PHP? - php

I'm having troubles using ajax and php. What I'm trying to do is call an ajax function that grabs a value from an form's input, and checks if that email exists in a database. Here is my current javascript:
//Checks for Existing Email
function checkExisting_email() {
$.ajax({
type: 'POST',
url: 'checkExist.php',
data: input
});
emailExists = checkExisting_email();
//If it exists
if (emailExists) {
alert("This email already exists!");
}
Unfortunately, I can't get my alert to go off. In my PHP function, it checks whether the input is a username or an email (just for my purposes, and so you know), and then it looks for it in either column. If it finds it, it returns true, and if not, it returns false:
include ('func_lib.php');
connect();
check($_POST['input']);
function check($args)
{
$checkemail = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
if (!preg_match($checkemail, $args)) {
//logic for username argument
$sql = "SELECT * FROM `users` WHERE `username`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
return true;
} else {
return false;
}
} else {
//logic for email argument
$sql = "SELECT * FROM `users` WHERE `email`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
return true;
} else {
return false;
}
}
}
SO my issue is, how does ajax respond to these returns, and how do I make ajax function accordingly? Mainly, why doesn't this work?
Any help is very much appreciated. Thank you!

You need to add the success option to your Ajax request, which is the JS function which gets executed when the XHR succeeds. Have a look at the jQuery documentation for more info.
Without running the script, I think you'll find that $_POST['input'] is empty; you need to pass your data as something like data: {'input': input} to do that.
Your PHP also needs to return some content to the script; consider changing your call to check() to something like this:
echo (check($_POST) ? 'true' : 'false');
You can now check the content in JavaScript.

Basically ajax is a hand-shaking routine with your server.
Ajax:
$.post('yoursite.com/pagewithfunction.php',
{postkey1:postvalue1, postkey2:postvalue2...},
function (response) {
// response is the data echo'd by your server
}, 'json'
);
pagewithfunction:
yourFunction(){
$var1 = $_POST['postkey1'];....
$result = dosomething($var1..);
echo json_encode($result); // this is passed into your function(response) of ajax call
}
So in $.post you have the url of the php page with the function, { var:val } is the post data, and function(response) is where you handle the data that is echo'd from your server -- the variable, response, is the content that is echo'd.

Related

jQuery JSON PHP Request

I've been trying to figure out what I have done wrong but when I use my JavaScript Console it shows me this error : Cannot read property 'success' of null.
JavaScript
<script>
$(document).ready(function() {
$("#submitBtn").click(function() {
loginToWebsite();
})
});
</script>
<script type="text/javascript">
function loginToWebsite(){
var username = $("username").serialize();
var password = $("password").serialize();
$.ajax({
type: 'POST', url: 'secure/check_login.php', dataType: "json", data: { username: username, password: password, },
datatype:"json",
success: function(result) {
if (result.success != true){
alert("ERROR");
}
else
{
alert("SUCCESS");
}
}
});
}
</script>
PHP
$session_id = rand();
loginCheck($username,$password);
function loginCheck($username,$password)
{
$password = encryptPassword($password);
if (getUser($username,$password) == 1)
{
refreshUID($session_id);
$data = array("success" => true);
echo json_encode($data);
}
else
{
$data = array("success" => false);
echo json_encode($data);
}
}
function refreshUID($session_id)
{
#Update User Session To Database
session_start($session_id);
}
function encryptPassword($password)
{
$password = $encyPass = md5($password);
return $password;
}
function getUser($username,$password)
{
$sql="SELECT * FROM webManager WHERE username='".$username."' and password='".$password."'";
$result= mysql_query($sql) or die(mysql_error());
$count=mysql_num_rows($result) or die(mysql_error());
if ($count = 1)
{
return 1;
}
else
{
return 0;;
}
}
?>
I'm attempting to create a login form which will provide the user with information telling him if his username and password are correct or not.
There are several critical syntax problems in your code causing invalid data to be sent to server. This means your php may not be responding with JSON if the empty fields cause problems in your php functions.
No data returned would mean result.success doesn't exist...which is likely the error you see.
First the selectors: $("username") & $("password") are invalid so your data params will be undefined. Assuming these are element ID's you are missing # prefix. EDIT: turns out these are not the ID's but selectors are invalid regardless
You don't want to use serialize() if you are creating a data object to have jQuery parse into formData. Use one or the other.
to make it simple try using var username = $("#inputUsername").val(). You can fix ID for password field accordingly
dataType is in your options object twice, one with a typo. Remove datatype:"json", which is not camelCase
Learn how to inspect an AJAX request in your browser console. You would have realized that the data params had no values in very short time. At that point a little debugging in console would have lead you to some immediate points to troubleshoot.
Also inspecting request you would likely see no json was returned
EDIT: Also seems you will need to do some validation in your php as input data is obviously causing a failure to return any response data
Try to add this in back-end process:
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: application/json');
header('Content-type: text/json');
hope this help !
i testet on your page. You have other problems. Your postvaribales in your ajax call are missing, because your selectors are wrong!
You are trying to select the input's name attribute via ID selector. The ID of your input['name'] is "inputUsername"
So you have to select it this way
$('#inputUsername').val();
// or
$('input[name="username"]').val();
I tried it again. You PHP script is responsing nothing. Just a 200.
$.ajax({
type: 'POST',
url: 'secure/check_login.php',
dataType: "json",
data: 'username='+$("#inputUsername").val()+'&password='+$("#inputPassword").val(),
success: function(result) {
if (result.success != true){
alert("ERROR");
} else {
alert("HEHEHE");
}
}
});
Try to add following code on the top of your PHP script.
header("Content-type: appliation/json");
echo '{"success":true}';
exit;
You need to convert the string returned by the PHP script, (see this question) for this you need to use the $.parseJSON() (see more in the jQuery API).

calling php function in jquery

I have one file json.js and one php function in php file .in json.js i want to check value returned by php function if value returned by function is 0 jquery should perform :$(':input').prop('disabled', true); otherwise nothing –
function loadJson (table, id) {
$.get("json-object.php", {'table': table, 'id':id}, function (data) {
console.log(data);
$.each(data, function (k, v) {
if ($('input[name="'+k+'"]').is('input[type="text"]')) {
$('input[name="'+k+'"]').val(v);
}
if($('select[name="'+k+'"]').val(v)){
get_input_value(k,v);
}
if ($('input[name="'+k+'"]').is('input[type="checkbox"]')) {
get_input_value(k,v);
}
console.log(k+' ==> '+v);
// Here I want to check condition of php function if value returned by fucntion is 0 it should perform :$(':input').prop('disabled', true); otherwise nothing //
});
}, 'json');
}
My php function:
function ronly($id) {
//$id=$_POST['noces'];
$sql = "SELECT COUNT(noces) FROM alterdetail WHERE noces = '$id'";
$sql.=';';
//echo "QUERY <br/>";
//echo $sql;
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
if($row['COUNT(noces)'] > 0)
{ echo "you can not alter data";
return 0;
}
else
{
echo " data new ";
return 1;
}
}
You can't, as Javascript is client-side executed, and PHP is server-side executed ...
A "solution" would be to assign a Javascript variable into the PHP file that you'll read into the Javascript file, as variable are global.
Use jQuery if possible.
$('#result').load('ajax/test.php', function() {
alert('Function called');
});
Or try JQuery forms. Use a form to submit any data, and it'll give you the response as a text or JSon object.
http://jquery.malsup.com/form/#ajaxSubmit
Here is an example for you:
$('#anyForm').ajaxForm({
url: "process.php?proc=7",
dataType: 'html',
success: function(responseText) {
if(responseText == "0") {
$(':input').prop('disabled', true);
}
}
});

JSON and PHP issues

I'm new to JSON and AJAX, and as such have searched for solutions and experimented for a few days before resorting to asking here.
I am using AJAX to process a PHP page on submit. It is saving the information fine, but I also need the PHP page to pass back the inserted ID. Here is what I have so far.
In the success:
success: function(){
$('#popup_name img').remove();
$('#popup_name').html('Saved');
$('#fade , .popup_block').delay(2000).fadeOut(function() {
$('#fade, a.close').remove(); //fade them both out
$.getJSON(pathName, function(json){
alert('You are here');
alert("Json ID: " + json.id);
});
});
}
Then, the PHP script calls this method to insert the info and return the inserted id:
public static function doInsertQuery($sparamQuery="",$bparamAutoIncrement=true,$sparamDb="",$sparamTable=""){
//do the insert
$iReturn = 0;
$result = DbUtil::doQuery($sparamQuery);
if(!$result){
$iReturn = 0;
}
elseif(!$bparamAutoIncrement){
$iReturn = DbUtil::getInsertedId();
}
else{
$iReturn = DbUtil::getInsertedId();
}
//log the insert action
//if not a client logged in- cannot log to client db
if(Session::get_CurrentClientId() > 0){
if($sparamTable != LogLogin::table_LOGLOGINS()){
$oLog = new LogDbRequest();
$oLog->set_Type(LogDbRequest::enumTypeInsert);
$oLog->set_Request($sparamQuery);
$oLog->set_RowId($iReturn);
$oLog->set_TableName($sparamTable);
$oLog->set_Before("NULL");
$oLog->set_After(serialize(DbUtil::getRowCurrentValue($sparamDb,$sparamTable)));
$oLog->insertorupdate_LogDbRequest();
}
}
echo json_encode($iReturn);
return $iReturn;
}
I hope this makes sense. I'm at a complete loss here. Any help at all would be greatly appreciated!
~Mike~
It's simple really. The success function accepts an argument corresponding to the response from the server.
Client side:
$.ajax({
'url':'/path/to/script.php',
'dataType':'json',
'success':function(response){ //note the response argument
alert(response.id); //will alert the id
}
});
Server side:
<?php
//...previous stuff here...
$response = array('id' => $id); //where $id is the id to return to the client
header('Content-type: application/json'); //Set the right content-type header
echo json_encode($response); //Output array as JSON
?>

AJAX to check the login name exists or not

i have a login box...
when the user starts typing.. i want to check whether the LOGIN NAME entered exists in the database or not...
if the login name is exist i am going to set the login button active... if it doesnot exist i am going to set the login button deactive...
offcourse i am going to need AJAX to perform my mySQL via PHP tough i don't know how it will be done...
lets say this is my query
<?php
$result = mysql_query("SELECT * FROM accounts WHERE name='mytextboxvalue'");
?>
how to do it
keep it simple:
$(document).ready(function(){
var Form = $('#myForm');
var Input = $('input.username',Form)
Input.change(function(event){
Value = Input.val();
if(Value.length > 5)
{
$.getJSON('/path/to/username_check.php',{username:Value},function(response){
if(response.valid == true)
{
Form.find('input[type*=submit]').attr('disabled','false');
}else
{
Form.find('input[type*=submit]').attr('disabled','true');
}
});
}
});
});
and then PHP side..
<?php
//Load DB Connections etc.
if(!empty($_REQUEST['username']))
{
$username = mysql_real_escape_string($_REQUEST['username']);
if(isset($_SESSION['username_tmp'][$username]))
{
echo json_encode(array('valid' => (bool)$_SESSION['username_tmp'][$username]));
die();
}
//Check the database here... $num_rows being a validation var from mysql_result
$_SESSION['username_tmp'][$username] = ($num_rows == 0) ? true : false;
echo json_encode(array('valid' => (bool)$_SESSION['username_tmp'][$username]));
die();
}
?>
You can use JSON-RPC, here is implementation in php.
and in JQuery you can use this code.
var id = 1;
function check_login(){
var request = JSON.stringify({'jsonrpc': '2.0',
'method': 'login_check',
'params': [$('#login_box').val()],
'id': id++});
$.ajax({url: "json_rpc.php",
data: request,
success: function(data) {
if (data) {
$('#login_button').removeAttr('disabled');
} else {
$('#login_button').attr('disabled', true);
}
},
contentType: 'application/json',
dataType: 'json',
type:"POST"});
}
and in php
<?php
include 'jsonRPCServer.php';
//mysql_connect
//mysql_select_db
class Service {
public function login_check($login) {
$login = mysql_real_escape_string($login);
$id = mysql_query("SELECT * FROM accounts WHERE name='$login'");
return mysql_num_rows($id) != 0;
}
}
$service = new Service();
jsonRPCServer::handle($service);
?>
Look at jQuery AJAX and jQuery TypeWatch
But like #halfdan said, this is a potential security risk. I have never seen a site do this with a username, only with search results.
Your potentially giving away an end point (URL) on your web site which anyone could query to find out if a username is valid. Intranet or not, it is a risk.

Modify the server side functions using jquery

I am developing one website using cakephp and jquery technologies.
Server-side there are some functions which handles SQL queries.
As per requirement I want to modify server side functions on client side using jQuery AJAX call.
E.g. : Below is the function on server side to modify users information.
function modifyUser(username,userid) {
//update query statements
}
Then jquery AJAX call will be like this:
$.ajax({
url: 'users/modiyUser',
success: function() {
alert("Updation done") or any statements.
}
});
and I want to modify above i.e. server side function depending upon client input criteria.
$.ajax({
function users/modiyUser(username,userid) {
// I will write here any other statements which gives me some other output.
}
});
Above AJAX call syntax may not present, but i think you all understood what I am trying to do I simply wants to modify/override server side functions on client side.
Please let me know is there any way to resolve above mentioned requirement.
Thanks in advance
You cannot call a PHP functions from the client directly. You can only make an HTTP request to a URI.
The URI determines the PHP script run. Input can be taken via $_GET, $_POST, and $_COOKIE (among others, but those are the main ones).
You can either write separate scripts for each function or determine what to do based on the user input.
You could have a server-side function in a separate PHP file to do this, and make an AJAX call call into that function first to perform the modification. But client-side changes to server-side code are just not possible.
I can't actually imagine why you would want to do this, though.
why override a function???
can i suggest this?
in PHP
try {
// functions here....
function modifyUser($username,$userid) {
//update query statements
if(!is_string($username)) throw new Exception("argument to " . __METHOD__ . " must be a string");
if(!is_string($userid)) throw new Exception("argument to " . __METHOD__ . " must be a string");
// do some modification codes....
}
function delete($userid){
// do stuff blah blahh...
}
// $_POST or $_GET etc. here
if(isset($_GET["modify"])){ // I make use of get for simplicity sake...
$username = $_GET['username'];
$userid = $_GET['userid'];
modifyUser($username,$userid);
$ret = array();
$ret["error"] = false;
$ret["msg"] = "$username has been modified";
echo json_encode($ret);
} else if(isset($_GET["delete"])) {
$userid = $_GET['userid'];
delete($userid);
$ret = array();
$ret["error"] = false;
$ret["msg"] = "$username has been deleted";
echo json_encode($ret);
}else {
// the client asked for something we don't support
throw new Exception("not supported operation");
}
}
catch(Exception $e){
// something bad happened
$ret = array();
$ret["error"] = true;
$ret["msg"] = $e->getMessage();
echo json_encode($ret);
}
in jQuery ajax
$.ajax({
url: 'ajax.php',
data : { modify : true, // sample for modify... can also be delete : true,
username : $('#username').val(),
userid : $('#userid').val() },
type: 'GET',
dataType: 'json',
timeout: 1000,
error: function(){
alert('error in connection');
},
success: function(data){
if(data.error)
alert('Something went wrong: ' + data.msg);
else {
alert('Success: ' + data.msg);
}
}
});

Categories