CodeIgniter + jQuery Ajax runs error but successfully callback is called - php

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

Related

Correct way to parse php object array for Ajax

I am trying to fill a dropdown using Ajax and PHP with JQuery. For some reason, I always get a Parse JSON Error.
JS file
function loadRolesToDropDown() {
var url = 'controller/get_all_roles.php';
$.ajax({
url: url,
type: 'GET',
dataType: 'JSON',
success: function (data) {
var len = data.length;
$("#roledropdown").empty();
for (var i = 0; i < len; i++) {
var roleId = data[i]['roleId'];
var roleName = data[i]['roleName'];
$("#roledropdown").append("<option value='" + roleId + "'>" + roleName + "</option>");
}
},
error: function (x, e) {
if (x.status == 0) {
alert('You are offline!!\n Please Check Your Network.');
} else if (x.status == 404) {
alert('Requested URL not found.');
} else if (x.status == 500) {
alert('Internal Server Error.');
} else if (e == 'parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if (e == 'timeout') {
alert('Request Time out.');
} else {
alert('Unknown Error.\n' + x.responseText);
}
}
});
}
get_all_roles.php
$roleDaoImpl = new RoleDaoImpl($pdo);
$roleDaoImpl->getAllRoles();
Implementation of getAllRoles()
function getAllRoles()
{
$roleList[] = "";
try {
$SQL = "CALL getAllRoles()";
$sp_getAllRoles = $this->connection->prepare($SQL);
$sp_getAllRoles->execute();
$resultSet = $sp_getAllRoles->fetchAll(PDO::FETCH_ASSOC);
foreach ($resultSet as $row) {
$roleId = $row['role_id'];
$roleName = $row['role_name'];
$roleList[] = array("roleId" => $roleId, "roleName" => $roleName);
}
echo json_encode($roleList);
} catch (PDOException $e) {
die($e->getMessage());
}
}
And when I tried to echo what's return by json_encode($roleList); I get the ff:
["",{"roleId":1,"roleName":"Administrator"},{"roleId":2,"roleName":"Teacher"},{"roleId":3,"roleName":"Student"}]
What is the correct way to parse the php object array return by php?
Thank you.
In your php function getAllRoles
function getAllRoles()
{
$roleList[] = ""; // -> should be $roleList = [];
In your get_all_roles.php if you are getting such type of result from query then this code will work
$resultSet = array(0=>array('role_id'=>1,'role_name'=>'Administrator'),1=>array('role_id'=>2,'role_name'=>'Teacher'),2=>array('role_id'=>3,'role_name'=>'Student'));
foreach ($resultSet as $row) {
$roleId = $row['role_id'];
$roleName = $row['role_name'];
$roleList[] = array("roleId" => $roleId, "roleName" => $roleName);
}
echo json_encode($roleList);

Cannot get data from json_encode in jQuery AJAX with php

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']);
}

Ajax code doesn't work inside of jquery form validation

I want to write (register section) code that can check if email have been used in past or the login is empty.
The code is working fine, but my ajax code dont run at all.
I checked everything, path to php file is good, variables are good etc. Don't how to solve it.
Code:
$('.login').submit(function(e) {
e.preventDefault();
var error = 0;
var self = $(this);
var $name = self.find('[type=name]');
var $email = self.find('[type=email]');
var $pass = self.find('[type=password]');
var emailRegex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (!emailRegex.test($email.val())) {
createErrTult("Błąd! Email ma zły format!", $email)
error++;
}
//MY AJAX CODE
var email = $email.val();
$.ajax({
url: '../inc/rejestracja.php?action=emailcheck',
data: {
'email': email
},
type: 'POST',
success: function(odp) {
if (odp == 1) {
createErrTult("Błąd! taki email już istnieje w bazie!", $email)
error++;
}
}
});
if ($name.val().length > 1 && $name.val() != $name.attr('placeholder')) {
$name.removeClass('invalid_field');
} else {
createErrTult('Error! Wrong name!', $name)
error++;
}
if ($pass.val().length > 1 && $pass.val() != $pass.attr('placeholder')) {
$pass.removeClass('invalid_field');
} else {
createErrTult('Error! Wrong password!', $pass)
error++;
}
if (error != 0) return;
self.find('[type=submit]').attr('disabled', 'disabled');
self.children().fadeOut(300, function() {
$(this).remove()
})
$('<p class="login__title">sign in <br><span class="login-edition">welcome to A.Movie</span></p><p class="success">You have successfully<br> signed in!</p>').appendTo(self)
.hide().delay(300).fadeIn();
// var formInput = self.serialize();
// $.post(self.attr('action'),formInput, function(data){}); // end post
});
php:
<?php
include ("config.php");
if($action == "emailcheck"){
//sprawdzamy czy był już dodany plus
$test = mysql_num_rows(mysql_query("select * from uzytkownicy where email='$email'"));
if ($test > 0) {
$dodano = 1;
echo json_encode($dodano);
}
?>
First, you should try adding error callback:
$.ajax({
url: '../inc/rejestracja.php?action=emailcheck',
data: {
'email': email
},
type: 'POST',
success: function(odp) {
if (odp == 1) {
createErrTult("Błąd! taki email już istnieje w bazie!", $email)
error++;
}
},
error: function(xhr, textStatus, error) // THOSE ROWS
{
alert(error);
}
});
This may alert you about some occured error.
Second, you can try to use json instead of plain text:
Client-side:
$.ajax({
url: '../inc/rejestracja.php?action=emailcheck',
data: {
'email': email
},
dataType: 'json', // THIS ROW
type: 'POST',
success: function(odp) {
if (odp['result'] == 1) {
createErrTult("Błąd! taki email już istnieje w bazie!", $email)
error++;
}
},
error: function(xhr, textStatus, error)
{
alert(error);
}
});
Server-side:
<?php
include ("config.php");
if (isset($_GET['action'])){
$action = $_GET['action'];
if($action == "emailcheck") {
if(isset($_GET['email'])) {
$email = $_GET['email'];
//sprawdzamy czy był już dodany plus
$test = mysql_num_rows(mysql_query("select * from uzytkownicy where email='$email'"));
if ($test > 0) {
$dodano = 1;
echo (json_encode(array("result" => $dodano))); // THIS ROW
}
}
}
}
?>
before everything check you config.php file path .. In your case config.php should be in the same path with rejestracja.php and try this.. lets start with ajax
$.ajax({
url: '../inc/rejestracja.php?action=emailcheck',
data: {
email: email
},
type: 'GET',
success: function(odp) {
if (odp == 1) {
alert('Email exists');
}else{
alert('Email dosen\'t exists');
}
}
});
then in php
<?php
include ("config.php");
if (isset($_GET['action'])){
$action = $_GET['action'];
if($action == "emailcheck"){
if(isset($_GET['email'])){
$email = $_GET['email'];
//sprawdzamy czy był już dodany plus
$test = mysql_num_rows(mysql_query("select * from uzytkownicy where email='$email'"));
if ($test > 0) {
$dodano = 1;
echo ($dodano);
}
}
}
?>
you should get alert with ('Email exists')

AJAX/PHP pop up for validation

Anyone can help me. Please. I don't how to have a pop up every validation exist.
I used alert(data.message); but validation says undefined.
here is my PHP code for the function:
<?php
include('connect.php');
$mydata = $_POST["results"];
$inputs = [];
parse_str($mydata, $inputs);
extract($inputs);
$plate_no_full = "$plate_char-$plate_no";
$result1 = mysql_query("SELECT * FROM cars where plate_no ='" . $plate_no_full . "'");
$result2 = mysql_query("SELECT * FROM cars where chass_no ='" . $chassis_no . "'");
$result3 = mysql_query("SELECT * FROM cars where eng_no ='" . $engine_no . "'");
$rows1 =mysql_num_rows($result1);
$rows2 =mysql_num_rows($result2);
$rows3 =mysql_num_rows($result3);
$errors = [];
if (mysql_num_rows($result1) > 0) {
$errors[] = array(
'error_code' => 1,
'message' => 'That plate number was already taken'
);
}
if (mysql_num_rows($result2) > 0) {
$errors[] = array(
'error_code' => 2,
'message' => 'That chassis number was already taken'
);
}
if (mysql_num_rows($result3) > 0) {
$errors[] = array(
'error_code' => 3,
'message' => 'That engine number was already taken'
);
}
if(empty($errors)) {
mysql_query("INSERT INTO cars VALUES ('', '$plate_char-$plate_no', '$engine_no', '$chassis_no', '$car_year', '$car_brand', '$car_model', '$horse_power', '$torque','$transmission $transmission_no', '$drivetrain', '$length/$width/$height', '$seating', '$condition','$air_bag' , '$front_wheel/$rear_wheel' , '$front_susp/$rear_susp' , '$brake_front/$brake_rear' , '$eng_type', '$fuel_type' , '$acquisition_cost' , '$marg_cost', '$selling_price' , '')");
if(isset($_POST["txt1"])){
for($i=0;$i<=count($_POST["txt1"])-1;$i++){
mysql_query("INSERT INTO expenses VALUES ('','$plate_char-$plate_no', '". $_POST["txt1"][$i] ."','". $_POST["txt2"][$i] ."', '". $_POST["txt3"][$i] ."')");
}
}
$response = array(
'message' => 'Successfully Added'
);
echo json_encode($response);
} else {
$response = array(
'errors' => $errors
);
echo json_encode($response);
}
here is my ajax code:
$(document).ready(function() {
$('#submitme').on('submit', function(e) {
e.preventDefault();
var mytxt1 = [];
var mytxt2 = [];
var mytxt3 = [];
$(".expense_name").each(function () {
mytxt1.push($(this).val());
});
$(".expense_desc").each(function () {
mytxt2.push($(this).val());
});
$(".expense_cost").each(function () {
mytxt3.push($(this).val());
});
var perfTimes = $(this).serialize();
$.post("addfunction.php", {results: perfTimes, txt1: mytxt1, txt2: mytxt2, txt3: mytxt3 }, function(data) {
if(data.errors) { }
else {
alert(data.message);
window.localtion.href = data.redirect;
}
});
});
});
You need to add the datatype to your post request so jquery can parse the response, then you can handle the errors like you did:
$.post("addfunction.php", {results: perfTimes, txt1: mytxt1, txt2: mytxt2, txt3: mytxt3 }, function (data) {
if (data.errors) {
var alertErrors = "The following errors were found: ";
$.each(data.errors, function(index, error){
alertErrors += "\n" + error.message;//Add each error in a new line
});
alert(alertErrors);
}
else {
alert(data.message);
window.localtion.href = data.redirect;
}
}, "json");//<--datatype here
Also the data.redirect value is missing in your response:
$response = array(
'message' => 'Successfully Added',
'redirect' => ''//add here
);
echo json_encode($response);
Fixing the redirect you wrote "localtion" wrong:
window.location.href = data.redirect;
I found that I needed to parse the returned JSON as well. This is because $.post is just a preconfigured $.ajax call, which does not (I think) specify which dataType is being fetched.
Hence, your Client-side code cannot immediately access the response as an object.
The simplest option is just to parse the response using jQuery:
data = $.parseJSON(data);
Otherwise you could change your code to use the $.ajax function:
$.ajax({
url:url,
type:"POST",
data:data,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
...
}
})
Good luck!

Using ajax to grab information from database

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");
}

Categories