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!
Related
i am trying to get data via ajax. everything works fine except the "error handler". whenever i have error in my php i want that the error is sent to the html page (javascript file). it's not working.
im using the success in my ajax.
What i want is to get alerted with the msg and error ive set in the PHP file (line 5 and 6)
Here is my code:
PHP
$result = mysqli_query($conn, $sql);
if (!$result || mysqli_num_rows($result) == 0) {
$resp = array(
'status' => "Error",
'msg' => "Error Msg",
'error' => mysqli_error($conn)
);
echo json_encode($resp);
die();
} else {
while ($row = mysqli_fetch_array($result)) {
$id = $row['id'];
// $ownId = $row['own_id'];
$name = $row['name'];
$geraet = $row['manuf'].' '.$row['model'];
$fail = $row['fail'];
$abg_dat = $row['pick_date'];
$status = $row['status'];
$return_arr[] = array("id" => $id,
"name" => $name,
"geraet" => $geraet,
"fail" => $fail,
"abg_dat" => $abg_dat,
"status" => $status
);
}
$resp = array(
'status' => "Succ" ,
'msg' => "Daten erfolgreich abgerufen",
'resp' => $return_arr
);
echo json_encode($resp);
}
JS
$.ajax({
url: `${phpDir}/inc/techniker.inc.php`,
type: 'get',
dataType: 'JSON',
success: function(response){
if (response['status'] == "Error") {
alert(response['status'] + "<br/>" + response['error']);
} else {
var len = response['resp'].length;
var rspKey = response['resp'];
for(var i=0; i<len; i++){
var id = rspKey[i].id;
var name = rspKey[i].name;
var geraet = rspKey[i].geraet;
var stoerung = rspKey[i].fail;
var abgabe = rspKey[i].abg_dat;
var status = rspKey[i].status;
// example on muliple rows
// var username = response[i].username;
var tr_str = `
<tr id="${id}" onclick="tabCaller(${id})">
<td>#${id}</td>
<td>${name}</td>
<td>${geraet}</td>
<td>${stoerung}</td>
<td>${abgabe}</td>
<td>${status}</td>
</tr>
`;
$("#techniker_tbody").append(tr_str);
}
}
}
});
UPDATE
when mysqli error is happening the php is breaking and showing the error before he sends the response. that why im not gettin the 'error' either the 'msg'
What #aryan said was right. You can refer to the following which explains it well. How to trigger jquery.ajax() error callback based on server response, not HTTP 500?
When your "webservice" is returning a HTTP Statuscode 400, 401, 403, 405 or 5XX jQuery ajax event error will be triggered.
$.ajax({
url: `${phpDir}/inc/techniker.inc.php`,
type: 'get',
dataType: 'JSON',
success: function(response){
...
},
error: function(error) {
// alert, append to body
}
});
Just make sure to send a http header with the response. The mysql error is resulting in a HTTP 500 (Internal Server Error).
Like so:
header_status(500);
...
var arr = JSON.parse(response);
if(arr["status"] == "Error"){
alert(arr["error"]);
}
I am trying to execute data if the SMS OTP is equal to Session_oTp. So, that is working fine, I am able to verify the mobile OTP is verified or not. But when trying to execute some normal query it does not run.
case "verify_otp":
$otp = $_POST['otp'];
$orderId = $_POST['orderid'];
$params = array("status" => "completed");
$body = 'orders/'.$_POST['orderid'] ;
// $woocommerce->put('orders/'.$orderId, $params);
if ($otp == $_SESSION['session_otp'] && $orderId == $_SESSION['OrderID']) {
// if ($otp == $_SESSION['session_otp']) {
echo "$params";
// $params = array("status" => "completed");
// $woocommerce->put($body, $params);
// print_r($_SESSION['OrderID']);
unset($_SESSION['session_otp']);
unset($_SESSION['OrderID']);
echo json_encode(array("type"=>"success", "message"=>"Your mobile number is verified!"));
} else {
echo json_encode(array("type"=>"error", "message"=>"Mobile number verification failed"));
}
break;
If I turn off the $params or $woocommerce query it works perfectly. Even if I try to echo a normal words, it's returning the error code.
My AJAX code is below:
$('form.otp-ver-form').on('submit', function(e){
// $(document.body).on("submit", 'form.otp-ver-form', function() {
e.preventDefault();
$(".error").html("").hide();
$(".success").html("").hide();
var $form = $( this ),
url = $form.attr( 'action' );
// var otpnumber = $form.find('input[name="otpnumber"]').val();
var otpnumber = $form.siblings('.mobileOtp').val();
var Order_ID = $form.siblings('.orderID').val();
console.log(otpnumber);
console.log(Order_ID);
var input = {
"otp" : otpnumber,
"orderid" : Order_ID,
"action" : "verify_otp"
};
if (otpnumber.length == 6 && otpnumber != null) {
$.ajax({
url : 'controller.php',
type : 'POST',
dataType: 'json',//specify data type
data : input,
success : function(response) {
console.log(response.message);
$("." + response.type).html(response.message)
$("." + response.type).show();
},
error : function() {
alert("ss");
}
});
} else {
$(".error").html('You have entered wrong OTP.')
$(".error").show();
}
});
Please let me know where is my fault or if I missing something.
I'm creating an ajax script to update a few fields in the database. I got it to a point where it worked but it sent the user to the php script instead of staying on the page so I did some googling, and people suggested using either return false; or e.preventDefault() however, if I do this, it breaks the php script on the other page and returns a fatal error. I might be missing something being newish to AJAX but it all looks right to me
JS:
$(document).ready(function() {
var form = $('form#edit_child_form'),
data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$('#submit_btn').on('click', function(e) {
e.preventDefault();
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'post',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = ". $parent_id ." ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = $child_row[0]");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
it's probably something really small that I've just missed but not sure what - any ideas?
my solution:
I var_dumped $_GET and it returned null - changed to $_REQUEST and it got my data so all good :) thanks for suggestions
Try the following instead.
I moved the form data inside click and enclosed the mysql queries values in single quotes.
JS:
$(document).ready(function() {
var form = $('form#edit_child_form');
$('#submit_btn').on('click', function(e) {
e.preventDefault();
var data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'get',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = '". $parent_id ."' ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = '$child_row[0]'");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
You are using an AJAX POST request so in your PHP you should be using $_POST and not $_GET.
You can just change this:
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
to this:
$descriptions = $_POST['descriptions'];
$child_id = $_POST['child_id'];
$parent_id = $_POST['parent_id'];
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'm trying to retrieve a json object through a ajax request from a php file. My ajax request looks like the following:
function validateForm() {
var name = $('#usernameLogIn').val();
var password = $('#passwordLogIn').val();
$.ajax({
type: 'GET',
url: '../webroot/login/validateForm/',
data: {name: name, password: password},
dataType: 'json',
success: function(result) {
var data = JSON.stringify(result);
var b = $.parseJSON(data);
alert(b);
},
error: function(a,b,c) { console.log(a,b,c); }
});
}
and my php file looks like this:
$form = $this->form;
$status = false;
$name = preg_replace("/[^A-Za-z0-9]/", " ", $_GET['name']);
$formPassword = preg_replace("/[^A-Za-z0-9]/", " ", $_GET['password']);
$now = date(DATE_RFC2822);
$user = $this->user->findName($name);
if(isset($user->name))
{
$password = $user->password;
$status = password_verify($formPassword, $password);
}
if ($status === true)
{
$this->session->set('loggedIn', $this->user->name);
}
else if ($status === false) {
$this->session->clearSession('loggedIn');
}
$sessionLog = $this->session->get('loggedIn');
$advert = array(
'session' => $sessionLog,
'name' => $name,
'password' => $formPassword,
);
echo json_encode($advert);
exit;
Finally when it passes the values back to my Ajax request it goes straight into the error function and prints the following into the console:
Object "parsererror" SyntaxError
message: Unexpected Token <"
Is it any way to tell where this goes wrong and why?
thankfull for answers, cheers.
I think you have verbose set to true in you config file.