I have a simple code here that uses json_encode and echo out the response in PHP. Here is my code:
app.js
$scope.login = function() {
var data = {
username: $scope.login.username,
password: $scope.login.password
};
$http.post('endpoints/login.php', data)
.success(function(response) {
if(response.success == "true") {
alert('nice');
} else {
alert('not nice');
}
})
.error(function(response) {
console.log(response);
});
};
login.php
$data = json_decode(file_get_contents("php://input"));
$stmt = $db->prepare('SELECT * FROM accounts WHERE username=? AND password=?');
$stmt->execute(array($data->username, $data->password));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row > 0)
{
$response = [
"success" => true
];
echo json_encode($response);
}
else
{
$response = [
"success" => false
];
echo json_encode($response);
}
It works perfectly but this part doesn't work:
if(response.success == "true") {
alert('nice');
} else {
alert('not nice');
}
When I add console.log(response) I get Object {success: true} or Object {success: false}.
Am I missing something here? Thank you.
You need to use a boolean in your if statement, not a string because true != "true". Change your if statement to the following:
if(response.success === true) {
Related
I have an AJAX call from jQuery to PHP where the PHP responds with a json_encode array, but the values of the array are not accessible in jQuery.
The status is OK, but the responseText is undefined.
$(document).ready(function () {
$("#comments_form").on("submit", function(e) {
e.preventDefault();
e.stopPropagation();
$.ajax({
type: 'POST',
url: 'process_in.php',
data: {
first: $("#firstname").val(),
second: $("#lastname").val(),
third: $("#mail").val(),
fourth: $("#phone").val(),
fifth: $("#message").val()
},
success: function(result) {
var x = jQuery.parseJSON(result);
alert(x.f);
},
});
});
})
<?php
include ('connection.php');
if (isset($_REQUEST['first']) && isset($_REQUEST['second']) && isset($_REQUEST['third']) && isset($_REQUEST['fourth']) && isset($_REQUEST['fifth']))
{
$firstname = $_REQUEST['first'];
$lastname = $_REQUEST['second'];
$email = $_REQUEST['third'];
$contact = $_REQUEST['fourth'];
$message = $_REQUEST['fifth'];
$data = array();
$data["f"] = xssafe($firstname);
$data["l"] = xssafe($lastname);
$data["e"] = xssafe($email);
$data["c"] = xssafe($contact);
$data["m"] = xssafe($message);
echo json_encode($data);
}
function xssafe($d)
{
$x = filter_var($d, FILTER_SANITIZE_STRING);
return $x;
}
A good practice is to always catch the errors too. In your ajax request there is no error callback to handle the exception.
Use dataType: "JSON" instead of jQuery.parseJSON(); so that if json in unparsable you get the callback in the error block.
$.ajax({
type: 'POST',
url: 'process_in.php',
dataType: 'JSON',
data: {
first: $("#firstname").val(),
second: $("#lastname").val(),
third: $("#mail").val(),
fourth: $("#phone").val(),
fifth: $("#message").val()
},
success: function(result) {
console.log(result.f);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
}
});
You can learn how to debug the code and check your error logs
Now lets get to your code, there are many possible cases that you are not getting the value.
It could be your php code or it could be your jquery.
In php to check whether its returning a valid json hit the url in browser like this
http://.../process_in.php?first=foo&second=foo&third=foo&fourth=foo&fifth=foo
As in your php code you haven't return any value so add an else part for the
if (isset($_REQUEST['first']) && isset($_REQUEST['second']) && isset($_REQUEST['third']) && isset($_REQUEST['fourth']) && isset($_REQUEST['fifth']))
{
$firstname = $_REQUEST['first'];
$lastname = $_REQUEST['second'];
$email = $_REQUEST['third'];
$contact = $_REQUEST['fourth'];
$message = $_REQUEST['fifth'];
$data = array();
$data["f"] = xssafe($firstname);
$data["l"] = xssafe($lastname);
$data["e"] = xssafe($email);
$data["c"] = xssafe($contact);
$data["m"] = xssafe($message);
echo json_encode($data);
} else {
echo json_encode(['error'=>'Invalid request']);
}
My Codeigniter: (Do you think there is an error?)
public function KayitOl()
{
$data = array(
'kullaniciadi' => $this->input->post('kullaniciadi'),
'email' => $this->input->post('email'),
'sifre' => $this->input->post('sifre')
);
$kuladi = $this->input->post('kullaniciadi');
$sorgu = $this->db->query("SELECT * FROM uyeler WHERE kullaniciadi='".$kuladi."'");
if ($sorgu->num_rows() > 0)
{
$response_array['status'] = 'error';
echo json_encode($response_array);
}
else
{
$this->db->insert('uyeler',$data);
$response_array['status'] = 'success';
echo json_encode($response_array);
}
}
My jQuery Code: (Do you think there is an error?)
$(".submit").on("click", function(){
var kuladi = $("#kullaniciadi").val();
var email = $("#email").val();
var sifre = $("#sifre").val();
var confirm = $("#sifreonay").val();
var hata = $("#hata").val();
var checkbox = $("#checkbox").is(":checked");
var link = "http://tantunisiparis:8080/main/anasayfa/KayitOl";
var pattern = /^\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i;
if (!kuladi || !email || !sifre) {
$("p#hata").removeClass("hidden");
$("p#hata").html("Boş bırakılan alanlar var!");
}
else if (!pattern.test(email)) {
$("p#hata").removeClass("hidden");
$("p#hata").html("Lütfen geçerli bir e-mail giriniz!");
}
else if (!checkbox) {
$("p#hata").removeClass("hidden");
$("p#hata").html("Kullanıcı Sözleşmesini Kabul Etmediniz.");
}
else if (sifre != confirm) {
$("p#hata").removeClass("hidden");
$("p#hata").html("Şifreler eşleşmiyor!");
}
else{
$.ajax({
type :"POST",
url :link,
data : $("#kayitform").serialize(),
success: function (data){
console.log(data.status);
alert("Success döndü");
},
error: function (data){
console.log(data.status);
alert("Error döndü");
}
});
}
});
Why I am having a problem like this?
Any answer attempts are appreciated. Any correct answers are doubly appreciated ;)
Thanks!
You need to set HTTP status code. So in case of error call this code in the controller $this->output->set_status_header(500);.
public function KayitOl()
{
$data = array(
'kullaniciadi' => $this->input->post('kullaniciadi'),
'email' => $this->input->post('email'),
'sifre' => $this->input->post('sifre')
);
$kuladi = $this->input->post('kullaniciadi');
$sorgu = $this->db->query("SELECT * FROM uyeler WHERE kullaniciadi='".$kuladi."'");
if ($sorgu->num_rows() > 0)
{
$response_array['status'] = 'error';
$this->output->set_status_header(500); // or any other code
echo json_encode($response_array);
}
else
{
$this->db->insert('uyeler',$data);
$response_array['status'] = 'success';
echo json_encode($response_array);
}
}
You can read more about output class in the docs http://www.codeigniter.com/userguide3/libraries/output.html
$.ajax({
type :"POST",
url :link,
data : $("#kayitform").serialize(),
success: function (data){
if(data.status == 'success'){
console.log(data.status);
alert("Success döndü");
}
if(data.status == 'error'){
console.log(data.status);
alert("Error döndü");
}
}
});
I thing, This code will work for you...
I have created a .post() request
function validateLogin()
{
var username = $("#username").val();
var password= $("#password").val();
var details = {"name": username, "password": password};
console.log(details);
console.log(JSON.stringify(details));
$.post("getthedb.php", JSON.stringify(details), function(response)
{
if(response.code==0)
{
alert("Response: " + response.message);
$("#myDiv").innerHTML = response.message;
}
else
{
$("#myDiv").innerHTML = response.message;
}
}, "application/json");
}
getthedb.php
<?php
header('Content-type: application/json');
$jsonobj = file_get_contents("php://input");
$detail= json_decode($jsonobj);
if(($detail->{'name'}=="abc") && ($detail->{'password'}=="abc"))
{
$response1['code']=0;
$response1['message']="Success";
}
else
{
$response1['code']=1;
$response1['message']="No Success";
}
$response = json_encode($response1);
echo $response;
?>
This is not giving back any result,'console.log(details)' and
'console.log(JSON.stringify(details))' produces the JSON object. how to debug this???
where am i lagging here.??
If you code doesn't provide some error i assume that your if down there isn't called and $response1 is empty. So no response to read.
if(($detail->{'name'}=="abc") && ($detail->{'password'}=="abc")
{
$response1['code']=0;
$response1['message']="Success";
}
else ???
$response = json_encode($response1); // Response1 is empty
echo $response;
missing ) in if loop.
if(($detail->{'name'}=="abc") && ($detail->{'password'}=="abc")
should be
if(($detail->{'name'}=="abc") && ($detail->{'password'}=="abc"))
$response1 array not declared.
You haven't written else case
Anyone can see anything wrong with this code? It is connected to a php function that echos Json data. I am running Jquery 1.9.1. I belive the problem is at the end of the Jquery script, but I can´t find any solution...
var formObject = {
run : function(obj) {
if (obj.val() === '') {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
} else {
var id = obj.attr('id');
var v = obj.val();
jQuery.getJSON('func/blankett_func.php', { id : id, value : v }, function(data) {
if (!data.error) {
obj.next('.update').html(data.list).removeAttr('disabled');
} else {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
}
});
}
}
};
$(function() {
$('.update').live('change', function() {
formObject.run($(this));
});
});
The Php function:
$id = $_GET['id'];
$value = $_GET['value'];
try {
$objDb = new PDO('mysql:host=localhost;dbname=blankett', 'root', 'root');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `region`
WHERE `master_id` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($value));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!empty($list)) {
$out = array('<option value="">Select one</option>');
foreach($list as $row) {
$out[] = '<option value="'.$row['id'].'">'.$row['region'].'</option>';
}
echo json_encode(array('error' => false, 'list' => implode('', $out)));
} else {
echo json_encode(array('error' => true));
}
} catch(PDOException $e) {
echo json_encode(array('error' => true));
}
} else {
echo json_encode(array('error' => true));
}
The problem with the original code was in the .live of the javascript, it should be changed to .on
The reason for it not triggering was that jQuery changed the API.
http://api.jquery.com/on/
The new jQuery script:
var formObject = {
run : function(obj) {
if (obj.val() === '') {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
} else {
var id = obj.attr('id');
var v = obj.val();
jQuery.getJSON('func/blankett_func.php', { id : id, value : v }, function(data) {
if (!data.error) {
obj.next('.update').html(data.list).removeAttr('disabled');
} else {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
}
});
}
}
};
$(function() {
$('.update').on('change', function() {
formObject.run($(this));
});
});
I m using codeigniter and would like to grab some user info with ajax. This is what I have but it s not working
In the view I have a defined variable:
<script type="text/javascript">
var end_user = "<? echo $user_id; ?>";
</script>
<div id="tabs6"></div>
js file:
function get_experience()
{
$.post(base_url + "index.php/home/get_experience", { user : end_user }, function(data) {
if (data.status == 'ok')
{
$("div#tabs6").html(data);
}
else
{ //nothing }
}, "json");
}
get_experience();
controller:
public function get_experience()
{
$this->load->model('experience_model');
$end_user = $this->input->post('user');
$one_exp = $this->experience_model->one_exp($end_user);
if ($one_exp->num_rows() > 0)
{
$one_exp_html = '<ul>';
foreach($one_exp->result() as $exp)
{
$one_exp_html .= '<li>';
$one_exp_html .= $exp->experience;
$one_exp_html .= '</li>';
}
$one_exp_html .= '</ul>';
$result = array('status' => 'ok', 'content' => $one_exp_html);
return json_encode($result);
exit();
}
else
{
$result = array('status' => 'ok', 'content' => 'nothing here');
return json_encode($result);
exit();
}
}
model:
function one_exp($end_user)
{
$query_str = "SELECT experience FROM exp WHERE user_id = ?";
$query = $this->db->query($query_str, $end_user);
}
You need to add return $query to your one_exp method.
EDIT
You're setting user_id in your view, but then using end_user in your javascript function get_experience().
Also, since it's json you'll need to change the html fill to
$("div#tabs6").html(data.content);
For more debugging add an alert to your callback (right before if (data.status == 'ok') add alert(data);)
You've got to echo the result out I think, not return it.
I am not sure but problem occurs in end_user value in js.Try this oneView File:
<script type="text/javascript">
var end_user = "<? echo $user_id; ?>";
get_experience(end_user);
</script>
<div id="tabs6"></div>
The js file:
function get_experience(foo)
{
$.post(base_url + "index.php/home/get_experience", { user : foo }, function(data) {
if (data.status == 'ok')
{
$("div#tabs6").html(data);
}
else
{ //nothing }
}, "json");
}