jQuery JSON PHP Request - php

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).

Related

Passing of javascript variable data to php variable in the same php file

I have a javascript that needs to pass data to a php variable. I already searched on how to implement this but I cant make it work properly. Here is what I've done:
Javascript:
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "POST",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
Then on my php tag:
<?php
if(isset($_GET['subDir']))
{
$subDir = $_GET['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
I always get the fail text so there must be something wrong. I just started on php and jquery, I dont know what is wrong. Please I need your help. By the way, they are on the same file which is signage.php .Thanks in advance!
When you answer to a POST call that way, you need three things - read the data from _POST, put it there properly, and answer in JSON.
$.ajax({
type: "POST",
url: 'signage.php',
data: {
subDir: val,
}
success: function(answer)
{
alert("server said: " + answer.data);
}
});
or also:
$.post(
'signage.php',
{
subDir: val
},
function(answer){
alert("server said: " + answer.data);
}
}
Then in the response:
<?php
if (array_key_exists('subDir', $_POST)) {
$subDir = $_POST['subDir'];
$answer = array(
'data' => "You said, '{$subDir}'",
);
header("Content-Type: application/json;charset=utf-8");
print json_encode($answer);
exit();
}
Note that in the response, you have to set the Content-Type and you must send valid JSON, which normally means you have to exit immediately after sending the JSON packet in order to be sure not to send anything else. Also, the response must come as soon as possible and must not contain anything else before (not even some invisible BOM character before the
Note also that using isset is risky, because you cannot send some values that are equivalent to unset (for example the boolean false, or an empty string). If you want to check that _POST actually contains a subDir key, then use explicitly array_key_exists (for the same reason in Javascript you will sometimes use hasOwnProperty).
Finally, since you use a single file, you must consider that when opening the file the first time, _POST will be empty, so you will start with "fail" displayed! You had already begun remediating this by using _POST:
_POST means that this is an AJAX call
_GET means that this is the normal opening of signage.php
So you would do something like:
<?php // NO HTML BEFORE THIS POINT. NO OUTPUT AT ALL, ACTUALLY,
// OR $.post() WILL FAIL.
if (!empty($_POST)) {
// AJAX call. Do whatever you want, but the script must not
// get out of this if() alive.
exit(); // Ensure it doesn't.
}
// Normal _GET opening of the page (i.e. we display HTML here).
A surer way to check is verifying the XHR status of the request with an ancillary function such as:
/**
* isXHR. Answers the question, "Was I called through AJAX?".
* #return boolean
*/
function isXHR() {
$key = 'HTTP_X_REQUESTED_WITH';
return array_key_exists($key, $_SERVER)
&& ('xmlhttprequest'
== strtolower($_SERVER[$key])
)
;
}
Now you would have:
if (isXHR()) {
// Now you can use both $.post() or $.get()
exit();
}
and actually you could offload your AJAX code into another file:
if (isXHR()) {
include('signage-ajax.php');
exit();
}
You are send data using POST method and getting is using GET
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
You have used method POST in ajax so you must change to POST in php as well.
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
Edit your javascript code change POST to GET in ajax type
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "GET",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
when you use $_GET you have to set you data value in your url, I mean
$.ajax({
type: "POST",
url: 'signage.php?subDir=' + val,
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
or change your server side code from $_GET to $_POST

Sending data with AJAX to a PHP file and using that data to run a PHP script

I'm currently trying to make live form validation with PHP and AJAX. So basically - I need to send the value of a field through AJAX to a PHP script(I can do that) and then I need to run a function inside that PHP file with the data I sent. How can I do that?
JQuery:
$.ajax({
type: 'POST',
url: 'validate.php',
data: 'user=' + t.value, //(t.value = this.value),
cache: false,
success: function(data) {
someId.html(data);
}
});
Validate.php:
// Now I need to use the "user" value I sent in this function, how can I do this?
function check_user($user) {
//process the data
}
If I don't use functions and just raw php in validate.php the data gets sent and the code inside it executed and everything works as I like, but if I add every feature I want things get very messy so I prefer using separate functions.
I removed a lot of code that was not relevant to make it short.
1) This doesn't look nice
data: 'user=' + t.value, //(t.value = this.value),
This is nice
data: {user: t.value},
2) Use $_POST
function check_user($user) {
//process the data
}
check_user($_POST['user'])
You just have to call the function inside your file.
if(isset($_REQUEST['user'])){
check_user($_REQUEST['user']);
}
In your validate.php you will receive classic POST request. You can easily call the function depending on which variable you are testing, like this:
<?php
if (isset($_POST['user'])) {
$result = check_user($_POST['user']);
}
elseif (isset($_POST['email'])) {
$result = check_email($_POST['email']);
}
elseif (...) {
// ...
}
// returning validation result as JSON
echo json_encode(array("result" => $result));
exit();
function check_user($user) {
//process the data
return true; // or flase
}
function check_email($email) {
//process the data
return true; // or false
}
// ...
?>
The data is send in the $_POST global variable. You can access it when calling the check_user function:
check_user($_POST['user']);
If you do this however remember to check the field value, whether no mallicious content has been sent inside it.
Here's how I do it
Jquery Request
$.ajax({
type: 'POST',
url: "ajax/transferstation-lookup.php",
data: {
'supplier': $("select#usedsupplier").val(),
'csl': $("#csl").val()
},
success: function(data){
if (data["queryresult"]==true) {
//add returned html to page
$("#destinationtd").html(data["returnedhtml"]);
} else {
jAlert('No waste destinations found for this supplier please select a different supplier', 'NO WASTE DESTINATIONS FOR SUPPLIER', function(result){ return false; });
}
},
dataType: 'json'
});
PHP Page
Just takes the 2 input
$supplier = mysqli_real_escape_string($db->mysqli,$_POST["supplier"]);
$clientservicelevel = mysqli_real_escape_string($db->mysqli,$_POST["csl"]);
Runs them through a query. Now in my case I just return raw html stored inside a json array with a check flag saying query has been successful or failed like this
$messages = array("queryresult"=>true,"returnedhtml"=>$html);
echo json_encode($messages); //encode and send message back to javascript
If you look back at my initial javascript you'll see I have conditionals on queryresult and then just spit out the raw html back into a div you can do whatever you need with it though.

Using Ajax to generate an alert box after checking whether some data are stored in database [duplicate]

I want to pop up an alert box after checking whether some data is stored in the database. If stored, it will alert saved, else not saved.
This is my ajax function:
AjaxRequest.POST(
{
'url':'GroupsHandler.php'
,'onSuccess':function(creategroupajax){ alert('Saved!'); }
,'onError':function(creategroupajax){ alert('not saved');}
}
);
but now it show AjaxRequest is undefined.
How can I fix this?
This of course is possible using Ajax.
Consider the below sample code for the same.
Ajax call :
$.ajax({
url: 'ajax/example.php',
success: function(data) {
if(data == "success")
alert('Data saved.');
}
});
example.php's code
<?php
$bool_is_data_saved = false;
#Database processing logic here i.e
#$bool_is_data_saved is set here in the database processing logic
if($bool_is_data_saved) {
echo "success";
}
exit;
?>
function Ajax(data_location){
var xml;
try {
xml = new XMLHttpRequest();
} catch (err){
try {
xml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (error){
try {
xml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (error1){
//
}
}
}
xml.onreadystatechange = function(){
if(xml.readyState == 4 && xml.status == 200){
alert("data available");
}
}
xml.open("GET", data_location, true);
xml.send(null);
}
window.onload = function(){
Ajax("data_file_location");
}
You can create an addtitional table with date(time) of last update database and check if this date is later. You can use standard setInterval function for it.
This is possible using ajax. Use jQuery.ajax/pos/get to call the php script that saves the data or just checks if the data was saved previously (depends on how you need it exactly) and then use the succes/failure callbacks to handle its response and display an alert if you get the correct response.
Below code based on jQuery.
Try it
$.ajax({
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
use the ajax to call the script and check values in the database through the script. If
data present echo success else not.lets look an example of it.
Assuming databasename = db
Assuming tablename = tb
Assuming tableColumn = data
Assuming server = localhost
Ajax:
$.ajax({
url: 'GroupsHandler.php',
success:function(data){
if(data=="saved")
{
alert("success");
}
}
});
Now in the myphpscript.php :
<?php
$Query = "select data from table";
$con = mysql_connect("localhost","user","pwd"); //connect to server
mysql_select_db("db", $con); //select the appropriate database
$data=mysql_query($Query); //process query and retrieve data
mysql_close($con); //close connection
if(!$empty(mysql_fetch_array($data))
{
echo "saved";
}
else
{
echo " not saved ";
}
?>
EDIT:
You must also include jquery file to make this type of ajax request.Include this at the top of your ajax call page.
<script src='ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
First, decide whether to use POST or GET (I recommend POST) to pass AJAX data. Make a php file (ajax.php) such that it echos true or false after checking whether some data is stored in the database. You may test with a variable $your_variable = "some_data_to_check"; having a data inside and once you are finished, you may replace it with $your_variable = $_POST["ajaxdata"];.
Then in your page, set up AJAX using jQuery plugin like:
var your_data_variable = "data_to_send";
$.ajax({
type: "POST",
url: "ajax.php",
data: 'ajaxdata=' + your_data_variable,
success: function(result){
if(result == "true"){
alert("saved");
}else{
alert("not saved");
}
}
You may have a look at jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery.

jQuery AJAX with PHP returning via JSON (Login form)

I don't know what I do wrong..
I have 2 files:
login.php
index.php
<script type="text/javascript">
$(document).ready(function(){
$('#btnLogin').bind('click', loginToWebsite);
});
function loginToWebsite(){
$.ajax({
url: "login.php",
type: "POST",
data: "username=" + $("#username").val()+"&password=" + $("#password").val(),
datatype:"json",
success: function(status)
{
if(status.success == false)
{
$("#loginform").effect("shake", {times:2}, 100);
$("#login_message")
.attr('class', 'ui-state-error')
.html('<strong>ERROR</strong>: Your details were incorrect.<br />');
}
else {
$("#login_message")
.attr('class', 'ui-state-highlight')
.html('<strong>PERFECT</strong>: You may proceed. Good times.<br />');
}
}
});
}
</script>
login.php gile looks this way:
<?php
if (isset($_POST['username'])&& isset($_POST['password']))
{
if (login ($_POST['username'], $_POST['password'])){
$data = array("success" => true);
echo json_encode($data);
}
else {
$data = array("success" => false);
echo json_encode($data);
}
}?>
But i get undefined back from login.php (via json)
If I try to alert(status.success) it prints undefined
And I can see i the header that the username and password are getting send to the login.php page.
The PHP function
login() is implemented elsewhere (and returns true or false)
It seems the value pass to javascript through variable "status" is a string. So you have to convert the string to json object. To convert string to json object use following script. Use the latest jquery library because older one using different functions to convert string to json.
var obj = jQuery.parseJSON(status);
alert(obj.success);
I guess that you have something bad in your php script output, and it cannot be parsed as json.
Try to use some debugging web proxy (http://www.charlesproxy.com/ for example, there is a free demo)
Add console trace to see the data
success: function(status)
{
console.log(status);
// ... function body
}
Your code in php file is incorrect
if login = false
{
$data['success'] = false;
echo json_encode($data);
}
else {
$data['success'] = true;
echo json_encode($data);
}

Jquery AJAX PHP login

I have a login form using jquery ajax and a php code. The issue is that is always returns an error instead of logging me into the system. I have spent days trying to find the error but I can't. The webpage displays no errors if I visit it directly. This used to work about a week ago until I accidentally deleted the jquery and now I can't get it to work.
Here is the PHP code:
include('.conf.php');
$user = $_POST['user'];
$pass = $_POST['pass'];
$result = mysql_query("SELECT * FROM accountController WHERE username = '$user'");
while ($row = mysql_fetch_array($result)) {
if (sha1($user.$pass) == $row['pword']) {
setcookie('temp', $row['username']);
session_start();
$_SESSION['login'] = 1;
$_SESSION['uname'] = $row['username'];
echo "success";
}
}
and here is the Jquery AJAX code:
var username = $('#main_username').val();
var password = $('#main_pword').val();
$('.mainlogin').submit(function() {
$.ajax({
url: 'log.php',
type: 'POST',
data: {
user: username,
pass: password
},
success: function(response) {
if(response == 'success') {
window.location.reload();
} else {
$('.logerror').fadeIn(250);
}
}
});
return false;
});
How would I check to see what is being returned like blank or success from the server. Is there any extension for safari? Thanks!
Put this in, instead. It will alert the server's response in a popup.
success: function(response) {
alert(response);
}
On your PHP side, try outputting more stuff - add an }else{ to your if statement that returns some useful data, for example
}else{
print("Post is: \n");
print_r($_POST);
print("\nMySQL gave me: \n");
print_r($row);
}
Just make sure you don't leave it in once it's working!
Look for:
hash is different
db field is different
db fields are blank for some reason
POST data is wrong / wrong field names
Edit: Here's another issue: Your first four lines should actually be:
$('.mainlogin').submit(function() {
var username = $('#main_username').val();
var password = $('#main_pword').val();
$.ajax({
Your code as it is gets the values before the form is submitted - at load - when they are blank, and as a result is sending blank strings to the server as username and password.
Take a look at the code i have in this answer here: user check availability with jQuery
You need to json encode your response, also Firefox has Firebug you can use to view your ajax post and response, chrome and IE both have developer tools
Safari also has dev tools: http://developer.apple.com/technologies/safari/developer-tools.html
Check the console to see what is happening with your AJAX

Categories