I am making a login form on HTML using JSON and PHP but all of the if statements on success are not working but the beforeSend and error is working. Can you help me check my mistakes?
I dont know know what is wrong with the function on success. The alerts are not popping up. For example response.success == true is supposed to pop up ' You are successfully logged in... '
<script>
$(document).ready(function(){
$('#loginForm').on('submit',function(e){
var myForm = new FormData($(this)[0]);
$.ajax({
type:'POST',
url: 'connections/login.php',
data : new FormData($(this)[0]),
cache: false,
contentType:false,
processData: false,
beforeSend: function(){
$("div#divLoading").show();
},
success: function(response){
$("div#divLoading").hide();
console.log(response);
if(response.success == true)
{
alert(' You are successfully logged in... ')
}
else if( response.success == false ){
alert('please enter a correct email & password');
}
else{
if(response.matric){
alert('email is wrong');
}
if(response.password){
alert('password is wrong');
}
}
},
error: function(data){
alert('error');
$("div#divLoading").hide();
}
});
return false;
});
});
</script>
Here is my PHP:
<?php
require_once('connect.php');
session_start();
header('Content-Type: application/json');
if (!empty($_POST['matric']))
{
$matric=$_POST['matric'];
$password=$_POST['password'];
$pass= $dbh->prepare("SELECT * FROM users WHERE matric=:matric AND password=:password");
$pass->bindParam(':matric', $matric);
$pass->bindParam(':password', $password);
$pass->execute();
if($pass->fetch(PDO::FETCH_NUM) > 0)
{
$_SESSION['matric']=$matric;
$response = array(
'success' => true,
'message' => 'Login successful');
}
else
{
$response = array(
'success' => false,
'message' => 'Login fail');
}
}
echo json_encode($response);
echo json_encode($_POST);
?>
You have
echo json_encode($response);
echo json_encode($_POST);
which is going to issue corrupted JSON. e.g. your output is going to be
{"success":true,"message":"Login successful"}Array
^^^^^^---corruption
Since your JSON is corrupted, it won't decode properly, and response WON'T be what you think it is.
Remove this line:
echo json_encode($_POST);
Related
I have some difficulties to call PHP script with:
$("#tata").click(function(){
$.ajax({
url : 'http://localhost/joomla/modules/mod_visitor/helper.php' ,
type : 'GET' ,
success: function(data) {
alert(data);
},
error : function(resultat, statut, erreur){
console.log("no")
}
});
});
But my alert is empty... I am sure that the URL is correct, because if I add in my PHP file HTML code it appear on my alert!
I am sure that my PHP code works
PHP file:
echo "lalalala";
$getData = new mod_visitor();
$writeData = new writeData();
$urlPart1 = $_SERVER['HTTP_HOST'];
$urlPart2 = $_SERVER['REQUEST_URI'];
$pageEnCours = $urlPart1 .= $urlPart2;
$getData->get_ip();
$getData->LookupIP($GLOBALS['domain']);
$getData->ValidateIP($GLOBALS['domain']);
if ($GLOBALS['domain'] && $pageEnCours != preg_match("#localhost/joomla/$#", $pageEnCours)) {
$GLOBALS['domain'] = trim($GLOBALS['domain']);
if ($getData->ValidateIP($GLOBALS['domain'])) {
echo "cc";
$result = $getData->LookupIP($GLOBALS['domain']);
$writeData->write_domain($result);
} else {
echo "erreur";
$writeData->write_error();
};
} else {
echo "je ne rentre pas dans la boucle";
};
echo $pageEnCours;
echo $GLOBALS['domain'];
Parse the dataType to 'json'
Add dataType: 'json' to the javascript
$.ajax({
url : 'http://localhost/joomla/modules/mod_visitor/helper.php' ,
type : 'GET' ,
dataType: 'json',
success: function(data) {
alert(data);
},
error : function(resultat, statut, erreur){
console.log("no")
}
And echo back as JSON in your php
<?php
echo json_encode('lalala');
?>
If you want to return multiple items, you can return them as an array
<?php
$return = array(
'pageEnCours' => $urlPart1 . $urlPart2,
'domain' => $GLOBALS['domain']
);
echo json_encode($return);
?>
And get the items client-side
success: function(data) {
console.log(data.pageEnCours, data.domain);
}
Hopefully an easy question here. I actually used an example I found on SO but can't figure out why its not working. No errors in console or anything.
I have an ajax Post function I am using to pass data to a php script.
Its passing the data correct, but the response each time is coming back as an error alert. I can confirm that server side is getting the data and processing it correctly, just can't figure out why its never returning a success response.
Here is the Ajax:
$(function () {
$('#pseudoForm').on('click', '#submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "psu_output.php",
data: $('#pseudoForm').serialize(),
datatype: 'json',
success: function (response) {
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
return false;
});
});
</script>
And in my php script I used this:
<?php
$success = true;
if($success == true) {
$output = json_encode(array('type'=>'success', 'message' => 'YAY'));
} else {
$output = json_encode(array('type'=>'error', 'message' => 'WHOOPS'));
}
die($output);
?>
The problem is that datatype: 'json' should be dataType: 'json'. Javascript is case-sensitive.
The error is because you received the returned data as json but the content type is a simple string (text/html) so you need to JSON.parse() the received data first like so:
$(function () {
$('#pseudoForm').on('click', '#submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "psu_output.php",
data: $('#pseudoForm').serialize(),
datatype: 'json',
success: function (response) {
response = JSON.parse(response);
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
return false;
});
});
The second option is to send json headers from php itself thus removing the need of parsing JSON in javascript. You can do that by using the following line of code BEFORE ECHOING OR PRINTING ANYTHING ELSE FROM THE PHP SCRIPT:
header('Content-Type: application/json');
and then
echo $output;
If you are working with JSON responses, you need to set the header so your browser and your JavaScript could interpret it correctly:
<?php
$success = true;
if ($success == true) {
$output = json_encode(array(
'type' => 'success',
'message' => 'YAY'
));
} else {
$output = json_encode(array(
'type' => 'error',
'message' => 'WHOOPS'
));
}
header('Content-Type: application/json');
echo $output;
I'm trying to send a message from php to ajax. I'm using echo json_encode to do it. When I do that, the website displays the arrays message. ({"foo":"content of foo"}). How can I get it to not display the message?
Also, the alerts from ajax don't get called.
Here's the code:
<?php
$myString = $_POST['data'];
if ($myString == "") {
echo json_encode(
array()
);
} else if ($myString == "foo" {
echo json_encode(
array(
'foo2' => 'this is the contents of foo'
)
);
} else if ($myString == "foo2") {
echo json_encode(
array(
'foo2' => 'this is the contents of foo2'
)
);
}
?>
<script>
var formData = new FormData($(this)[0]);
$.ajax({
url: $(this).attr("action"),
context: document.body,
data: formData,
type: "POST",
contentType: false,
processData: false,
success: function(response) {
if (response.length == 0) {
alert("empty");
} else if (response.foo) {
alert("foo");
} else if (respons.foo2) {
alert("foo2");
}
}
});
</script>
How can I get the array to not display on the website? And why are the ajax if statements not getting called?
You need to set the HTTP header at the top of the script so you can return son:
header('Content-type: application/json');
Your script is a little confusing. You can't return json AND html/javascript.
It's one or the other.
Here i'm storing span values into a database. It's working fine. I'm now facing a problem with ajax return error message. For example in my save.php code i changed my database table name sample to simple (i don't have a simple database table). In the mainpage I want to get the error message like "this simple database table name doesn't exists". But it always shows Data saved succesfully.
I've searched on some other sites. Some people say I should use json to get the proper error message. But, I don't how to do that. How do I get the correct error message using json and ajax? I think this is very simple. But, I'm new to ajax.
save.php
<?php
include('config.php');
$get = $_POST['content'];
try
{
$stmt = $conn->prepare("INSERT INTO sample (divvalue) VALUES (?)");
$conn->errorInfo();
$stmt->bindParam('1', $get, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
'Error : ' .$e->getMessage();
}
if($stmt)
{
echo 1;
}
?>
ajax.js
$(document).ready(function() {
$("#save").click(function (e) {
var span_contents = $('#ele').html();
$.ajax({
url: 'save.php',
type: 'POST',
data: {
content: span_contents
},
success: function(data){
if(data == '1')
{
$('#status')
.addClass('return')
.html('Data saved succesfully')
.fadeIn('fast')
.delay(3000)
.fadeOut('slow')
}
else
{
$('#status')
.addClass('error')
.html('Error occured')
.fadeIn('fast')
.delay(3000)
.fadeOut('slow')
}
}
});
});
});
mainpage.php
<span id="ele" class="ele" contenteditable >element</span>
<input type="button" id="save" value="save" />
<br />
<div id="status"></div>
In your code i think every time it returns one. In your catch block you need to return another value like 0.
try
{
if($stmt){
echo "1";
}
}
catch(PDOException $e)
{
echo 'Error : ' .$e->getMessage();
}
Also you can add an error handler in ajax function like ,
$.ajax({
success: function(data){
if(data == '1')
{
$('#status')
.addClass('return')
.html('Data saved succesfully')
.fadeIn('fast')
.delay(3000)
.fadeOut('slow')
}
else
{
$('#status')
.addClass('error')
.html('Error occured')
.fadeIn('fast')
.delay(3000)
.fadeOut('slow')
}
},
//another handlers and properties
error:function(error){
$('#status')
.addClass('error')
.html('Error occured')
.fadeIn('fast')
.delay(3000)
.fadeOut('slow')
}
});
Please update your code. It was ur PHP, which needs to echo on error too.
<?php
include('config.php');
$get = $_POST['content'];
try
{
$stmt = $conn->prepare("INSERT INTO sample (divvalue) VALUES (?)");
$conn->errorInfo();
$stmt->bindParam('1', $get, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
echo 'Error : ' .$e->getMessage();
}
if($stmt)
{
echo 1;
}
?>
And in your JavaScript too.
$(function() {
$("#save").click(function (e) {
var span_contents = $('#ele').html();
$.ajax({
url: 'save.php',
type: 'POST',
data: {
content: span_contents
},
error: function(data){//callback option is invoked, if the request fails.
$('#status')
.addClass('error')
.html('Error occured')
.fadeIn('fast')
.delay(3000)
.fadeOut('slow');
},
success: function(data){//callback option is invoked, if the request succeeds.
$('#status')
.addClass('return')
.html('Data saved succesfully')
.fadeIn('fast')
.delay(3000)
.fadeOut('slow');
}
});
});
});
You can do it as follows using json data
PHP :
<?php
include('config.php');
$get = $_POST['content'];
try
{
$stmt = $conn->prepare("INSERT INTO sample (divvalue) VALUES (?)");
$conn->errorInfo();
$stmt->bindParam('1', $get, PDO::PARAM_STR);
$stmt->execute();
if($stmt)
{
echo '{"status":1}';
}
}
catch(PDOException $e)
{
echo '{"status":0,"Error" : "' .$e->getMessage().'"}';
}
?>
JQUERY :
success: function(data){
$('#status')
.addClass('return')
.html(data.status?'Data saved succesfully':'Error'+data.Error)
.fadeIn('fast')
.delay(3000)
.fadeOut('slow')
},
dataType:'json'
I think
if($stmt)
{
echo 1;
}
Always evalute to true, try (for test) to do echo "2" without modify anything else.
Try also adding an echo in the catch block.
Also you can check with the devTools in the network tab what does the response return.
Please use the following syntax for your ajax call:
$.ajax({
url: 'save.php',
type: 'POST',
data: {
content: span_contents
},
success: function(data){
if(data == '1')
{
$('#status')
.addClass('return')
.html('Data saved succesfully')
.fadeIn('fast')
.delay(3000)
.fadeOut('slow')
},
error: function(data){
alert('Your error message here');
}
});
When ever you get an error, the error callback of the jquery ajax call will be fired
A Good standard way is to use JSON as below
catch
{
echo {"status":"failure","message":"The Error message goes here"};
}
if($stmt)
{
echo {"status":"success","message":"Data saved successfully"};
}
and in your ajax success function check like this
dataType:'json',
success: function(data){
if(data.status == 'success')
{
// do the required
}
else{
// do the required
}
}
You can add more variables as required like status and message in the return string
I have a problem with my ajax loader in CI.
This is what I have tried so far:
<script type="application/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var form_data = {
username : $('.username').val(),
password : $('.password').val(),
};
var loader = $('<img/>', {
'src':'assets/img/ajax-loader.gif',
'id':'message'
});
loader.insertAfter($(this));
//.removeClass().addClass('loader').html('<img src="assets/img/ajax-loader.gif">').fadeIn(1000);
$.ajax({ //
url: "<?php echo site_url('login/ajax_check'); ?>",
type: 'POST',
async : false,
data: form_data,
success: function(msg) {
$('#ajax_loader').remove();
$('#message').html(msg);
}
});
return false;
});
});
</script>
c_login.php controller
function ajax_check() {
//if($this->input->post('ajax') == '1') {
if($this->input->is_ajax_request()){
$this->form_validation->set_rules('username', 'username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean');
$this->form_validation->set_message('required', 'Please fill in the fields');
if($this->form_validation->run() == FALSE) {
echo validation_errors();
} else {
$this->load->model('m_access');
$user = $this->m_access->check_user($this->input->post('username'),$this->input->post('password'));
if($user) {
echo 'login successful';
//echo '<img src="assets/img/loader-bar.gif"> Hello!';
//$this->load->view('welcome');
} else {
echo 'unknown user'; //
//echo ' <img src="assets/img/icon_error.gif"> Username or password not valid';
}
}
}
}
UPDATE:
The problem is, it's just displaying the loader infinitely.
What I want to do is, if the user is valid, will show the loader.gif and then redirect to main page else will display the username or password incorrect. What is wrong with my code? Any ideas? Thanks.
It seems that you named your loader as "message" instead of creating a "message" new element and name your loader as "ajax_loader".
var loader = $('<img/>', {
'src':'assets/img/ajax-loader.gif',
'id':'ajax_loader'
});
var message = ...
...
'id':'message'
.
success: function(msg) {
$('#ajax_loader').remove();
$('#message').html(msg);
}