I am able to autofill state,city and area based on 6 digit zipcode.The issue comes when i want to check for validity of zipcode starting from 5th digit.I know it will show invalid zip code error as i am comparing the value against database value..Here goes the code i have used.
Is there a way i can hide error of invalid zip code after 5th digit while still continuing to validate after 5th digit of zipcode?
<script>
require([
'jquery'
],function($){
$(document).ready(function(){
$('#seller_zipcode').keyup(function() {
pincode = $('#seller_zipcode').val();
pincode1 = $('#seller_zipcode').slice(0,-1);
//pincode1 = pincode.slice(0,-1);
//console.log(pincode1);
if(pincode.length == 6 || pincode1.length == 5){
$.ajax({
type: 'POST'
,url: "<?php echo $block->getUrl('marketplace/zipcode/zipcode');?>"
,data: {pincode : pincode}
,success: function(result){
var finalresult = $.parseJSON(result);
console.log(finalresult);
if(finalresult.state != null){
$('#state').val(finalresult.state);
$('#seller_district').val(finalresult.district);
$('#seller_taluka').val(finalresult.area);
$('#zip_error').removeClass('mage-error');
$('#zip_error').removeAttr('generated');
$('#zip_error').html("");
}
else{
$('#state').val("");
$('#seller_district').val("");
$('#seller_taluka').val("");
$('#zip_error').removeClass('mage-error');
$('#zip_error').addClass('mage-error').html("Zip Code invalid").show();
$('#zip_error').attr('generated','true');
}
}
});
}
});
Try doing this:
<script>
require([
'jquery'
],function($){
$(document).ready(function(){
$('#seller_zipcode').keyup(function() {
//Reset the zip error
$('#zip_error').removeClass('mage-error');
$('#zip_error').removeAttr('generated');
$('#zip_error').html("");
pincode = $('#seller_zipcode').val();
pincode1 = $('#seller_zipcode').slice(0,-1);
//pincode1 = pincode.slice(0,-1);
//console.log(pincode1);
if(pincode.length == 6 || pincode1.length == 5){
$.ajax({
type: 'POST'
,url: "<?php echo $block->getUrl('marketplace/zipcode/zipcode');?>"
,data: {pincode : pincode}
,success: function(result){
var finalresult = $.parseJSON(result);
console.log(finalresult);
if(finalresult.state != null){
$('#state').val(finalresult.state);
$('#seller_district').val(finalresult.district);
$('#seller_taluka').val(finalresult.area);
$('#zip_error').removeClass('mage-error');
$('#zip_error').removeAttr('generated');
$('#zip_error').html("");
}
else{
$('#state').val("");
$('#seller_district').val("");
$('#seller_taluka').val("");
$('#zip_error').removeClass('mage-error');
$('#zip_error').addClass('mage-error').html("Zip Code invalid").show();
$('#zip_error').attr('generated','true');
}
}
});
}
});
Related
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 want to send two values to my PHP script that is being called from an AJAX request. Somehow my data is not being passed to the PHP script.
Maybe I am doing something wrong somewhere. Can I have some insight?
$(function() {
$(".delbutton").click(function() {
var viewed_comments = $("#viewed_comments").val();
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
var comments = 'comm=' + viewed_comments;
var tr = $(this).closest('tr');
if (confirm("Are you sure to mark this as viewed?")) {
$.ajax({
type : "POST",
url : "update_entry.php",
dataType: "json",
data: {info:info, comments:comments },
success : function(response) {
if(response=="updation success"){
console.log('inside');
}
}
});
}
return false;
});
});
And my PHP where the AJAX request is going,
$id = $_POST['id'];
$viewed_comments = $_POST['comm'];
$level_code = $_SESSION['level_code'];
$action = 'view';
$viewed_date = date("Y-m-d");
$viewed_by = $_SESSION['session_admin_id'] ;
if($action == 'view')
{
$viewed_date = date('Y-m-d h:i:s');
$nots = $db->idToField("tbl_table","notes",$id);
if ($nots == "")
{
$date_string = "last viewed on|".$viewed_date."|" ;
}
else {
$date_string = $nots."last viewed on|".$viewed_date."|" ;
}
$fnc->update_is_viewed_for("tbl_table",$id, "$viewed_date", $viewed_by);
$notes_data = array("notes"=>$date_string,"viewed_comments"=>$viewed_comments);
$db->query_update("tbl_table", $notes_data, "id=$id");
}
if($db->query_update("tbl_table", $notes_data, "id=$id")){
http_response_code();
echo json_encode('updation success');
}else{
http_response_code(204);
}
Isn't it a name thing? You send two POST variables:
data: {
info: info,
comments: comments
},
but you retrieve them with different names:
$id = $_POST['id'];
$viewed_comments = $_POST['comm'];
What do you get if you var_dump($_POST);?
Use seriliaze form values it will solve your data missing problem, change #frm to your form id
$(document).ready(function(){
$('#frm').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"update_entry.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if (data == 'updation success') {
console.log('success');
}
}
});
});
});
I have a text box where I search database for a specific information.
The PHP code when I just type and click on search is the following:
try
{
$date_emp = $_POST['date_emp'];
$val = $_POST['data1'];
$gender = $_POST['gen'];
if($date_emp == "choose" && $gender == "specify")
{
$search = "SELECT * FROM employee
WHERE emp_name = :val OR position = :val
OR salary = :val OR date_employed = :val
OR gender = :val";
$searchStmt = $conn->prepare($search);
$searchStmt->bindValue(":val", $val);
$searchStmt->execute();
$res = $searchStmt->fetchAll();
echo json_encode($res);
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
And here the AJAX script for it:
$("#search").click(function()
{
var txt = $("#txtSearch").val();
var drop = $("#date_employed").val();
var gender = $("#sex").val();
//console.log(txt);
if(txt == '' && drop == "choose" && gender == "specify")
{
$("#txtSearch").css('border-color', 'red');
}
else
{
if(drop == "choose" && gender == "specify")
{
$.ajax
({
url: 'search.php',
type: 'POST',
data: {data1: txt, date_emp: drop, gen: gender},
dataType: 'JSON',
success:function(res)
{
$("#myTable tr").remove();
$("#myTable").append("<tr><th>Name</th><th>Position</th><th>Salary</th><th>Date</th><th>Gender</th></tr>");
$.each( res, function(key, row){
$("#myTable").append("<tr><td>"+row['emp_name']+"</td><td>"+row['position']+"</td><td>"+row['salary']+"</td><td>"+row['date_employed']+"</td><td>"+row['gender']+"</td></tr>");
});
},
error:function(res)
{
alert("Something Wrong");
}
});
}
$("#date_employed, #sex").change(function()
{
var txt = $("#txtSearch").val();
var drop = $("#date_employed").val();
var gender = $("#sex").val();
$.ajax({
url: 'search.php',
type: 'post',
data: {data1: txt, date_emp: drop, gen: gender},
datatype: 'json',
success:function(res)
{
$("#myTable tr").remove();
$("#myTable").append("<tr><th>Name</th><th>Position</th><th>Salary</th><th>Date</th><th>Gender</th></tr>");
$.each( res, function(key, row){
$("#myTable").append("<tr><td>"+row['emp_name']+"</td><td>"+row['position']+"</td><td>"+row['salary']+"</td><td>"+row['date_employed']+"</td><td>"+row['gender']+"</td></tr>");
});
},
error:function(res)
{
alert("Couldn't find any data!");
}
});
});
}
});
WHERE gender and drop are 2 drop lists that forming a search filters
When I change one of the drop lists, per example, when I choose the date equal to: this week I should see in table 2 rows.
But I can only see them in the network (in devTool), and at console tab I see the following error:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in
[{"id":"48","0":"48","emp_name":"Alexa","1":"Alexa","position":"Secretary","2":"Secretary","salary":"8000","3":"8000","date_employed":"2016-02-23","4":"2016-02-23","gender":"female","5":"female"}]
The PHP code when I change drop lists is:
if($date_emp == "week" && $gender == "specify")
{
$search = "SELECT * FROM employee WHERE (emp_name = :val OR position = :val
OR salary = :val OR date_employed = :val
OR gender = :val) AND date_employed > DATE_SUB(NOW(), INTERVAL 1 WEEK)";
$searchStmt = $conn->prepare($search);
$searchStmt->bindValue(":val", $val);
$searchStmt->execute();
$res = $searchStmt->fetchAll();
echo json_encode($res);
}
When you make an ajax call and expect the response to be a json you need to send a json header from the PHP
header('Content-Type: application/json');
echo json_encode($data);
Sending the json header from the PHP will turn the "res" param in your ajax to a json object and not a json string.
If you don't send the the header you need to parse the json string into a json object
var json = JSON.parse(res);
I'm trying to write a script in javascript/jquery that will send values to a php file that will then update the database. The problem is that the values aren't being read in by the PHP file, and I have no idea why. I hard-coded in values and that worked fine. Any ideas?
Here's the javascript:
var hours = document.getElementById("hours");
var i = 1;
while(i < numberofMembers) {
var memberID = document.getElementById("member"+i);
if(memberID && memberID.checked) {
var memberID = document.getElementById("member"+i).value;
$.ajax({
type : 'post',
datatype: 'json',
url : 'subtract.php',
data : {hours : hours.value, memberID : memberID.value},
success: function(response) {
if(response == 'success') {
alert('Hours subtracted!');
} else {
alert('Error!');
}
}
});
}
i++;
}
}
subtract.php:
if(!empty($_POST['hours']) AND !empty($_POST['memberID'])) {
$hoursToSubtract = (int)$_POST['hours'];
$studentIDString = (int)$_POST['memberID'];
}
$query = mysql_query("SELECT * FROM `user_trials` WHERE `studentid` = '$studentIDString' LIMIT 1");
Edit: Updated code following #Daedal's code. I'm still not able to get the data in the PHP, tried running FirePHP but all I got was "profile still running" and then nothing.
This might help you:
function subtractHours(numberofMembers) {
var hours = document.getElementById('hours');
var i = 1;
while(i < numberofMembers) {
// Put the element in var
var memberID = document.getElementById(i);
// Check if exists and if it's checked
if(memberID && memberID.checked) {
// Use hours.value and memberID.value in your $.POST data
// {hours : hours.value, memberID : memberID.value}
console.log(hours.value + ' - ' + memberID.value);
// $ajax is kinda longer version of $.post api.jquery.com/jQuery.ajax/
$.ajax({
type : 'post',
dataType : 'json', // http://en.wikipedia.org/wiki/JSON
url : 'subtract.php',
data : { hours : hours.value, memberID : memberID.value},
success: function(response) {
if( response.type == 'success' ) {
alert('Bravo! ' + response.result);
} else {
alert('Error!');
};
}
});
}
i++;
}
}
and PHP part:
$result = array();
// Assuming we are dealing with numbers
if ( ! empty( $_POST['hours'] ) AND ! empty( $_POST['memberID'] ) ) {
$result['type'] = "success";
$result['result'] = (int) $_POST['hours'] . ' and ' . (int) $_POST['memberID'];
} else {
$result['type'] = "error";
}
// http://php.net/manual/en/function.json-encode.php
$result = json_encode( $result );
echo $result;
die();
Also you probably don't want to CSS #ID start with a number or to consist only from numbers. CSS Tricks explained it well http://css-tricks.com/ids-cannot-start-with-a-number/
You can simple fix that by putting some string in front:
var memberID = document.getElementById('some_string_' + i);
This is not ideal solution but it might help you to solve this error.
Cheers!
UPDATE:
First thing that came to my mind is that #ID with a number but as it seems JS don't care about that (at least not in a way CSS does) but it is a good practice not to use all numbers. So whole error was because document.getElementById() only accepts string.
Reference: https://developer.mozilla.org/en-US/docs/DOM/document.getElementById id is a case-sensitive string representing the unique ID of the element being sought.
Few of the members already mentioned converting var i to string and that was the key to your solution. So var memberID = document.getElementById(i); converts reference to a string. Similar thing could
be accomplished I think in your original code if you defined wright bellow the loop while(i < numberofMembers) { var i to string i = i.toString(); but I think our present solution is better.
Try removing the '' fx:
$.post (
"subtract.php",
{hours : hours, memberID : memberID}
try this
$.ajax({type: "POST",
url:"subtract.php",
data: '&hours='+hours+'&memberID='+memberID,
success: function(data){
}
});
Also you could try something like this to check
$(":checkbox").change(function(){
var thisId = $(this).attr('id');
console.log('Id - '+thisId);
});
$studentID = $_GET['memberID'];
$hoursToSubtract = $_GET['hours'];
Try this:
$.post("subtract.php", { hours: hours, memberID : memberID })
.done(function(data) {
document.body.style.cursor = "auto";
});
Try n use this...
$.post("subtract.php", { hours: hours, memberID : memberID })
.done(function(data) {
$(body).css({ 'cursor' : 'auto' });
});
Currently I'm using this jquery script combining with php (doesn't matter):
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
var select = "<?php if_exist($select, ''); ?>";
var event = "<?php if_exist($event, 'click'); ?>";
var display = "<?php if_exist($display, '#display'); ?>";
var loading = "<?php if_exist($loading, '#loading'); ?>";
var datatype = "<?php if_exist($datatype, 'json'); ?>";
var cache;
if (event == "submit"){ $("input:submit").hide(); }
$(select).bind( event , function(key){
if ( event == "keypress" ) {
if ( key.which == <?php if_exist($keycode, '13'); ?> ) {
$(loading).show();
$.post(
$(select).attr("action"),
$(select).serialize(),
function(data){
if (datatype == "html" || datatype == "text"){ var returned = data; }
if (datatype == "json"){ var returned = data<?php if_exist($return, '.return'); ?>; }
if (returned != cache)
{
cache = returned;
if (datatype == "html" || datatype == "text"){ $(display).hide().html(data).fadeIn(); }
if (datatype == "json"){ $(display).hide().autoRender(data).fadeIn(); }
$(loading).hide();
}
},
datatype
);
return false;
};
}
else
{
$.post(
$(select).attr("action"),
$(select).serialize(),
function(data){
if (datatype == "html" || datatype == "text"){ var returned = data; }
if (datatype == "json"){ var returned = data<?php if_exist($return, '.returnValue'); ?>; }
if (returned != cache)
{
cache = returned;
if (datatype == "html" || datatype == "text"){ $(display).hide().html(data).fadeIn(); }
if (datatype == "json"){ $(display).hide().autoRender(data).fadeIn(); }
$(loading).hide();
}
},
datatype
);
if ($event == 'submit') { return false;}
}
});
});
</script>
I want to reduce the amount of code used in this script, I think we can surely reduce the amount of code in this script by giving our attention to the line #11 which contains: if ( event == "keypress" ) {, because in the next else statement the same code is repeated twice, but how can we do this? Any idea?
The following piece looks duplicated:
$.post(
$(select).attr("action"),
$(select).serialize(),
function(data){
if (datatype == "html" || datatype == "text"){ var returned = data; }
if (datatype == "json"){ var returned = data; }
if (returned != cache)
{
cache = returned;
if (datatype == "html" || datatype == "text"){ $(display).hide().html(data).fadeIn(); }
if (datatype == "json"){ $(display).hide().autoRender(data).fadeIn(); }
$(loading).hide();
}
},
datatype
);
You should consider moving it's functionality to a function (sic)!
In addition to Vlad's answer: Remove the unnecessary if query and variable assignment:
$.post(
$(select).attr("action"),
$(select).serialize(),
function(data) {
// in every case, data is assigned to another variable which is
// unnecessary as well
// if (datatype == "html" || datatype == "text"){ var returned = data; }
// if (datatype == "json"){ var returned = data; }
if (data != cache) {
cache = data;
}
if (datatype == "html" || datatype == "text") {
$(display).hide().html(data).fadeIn();
}
else if (datatype == "json"){
$(display).hide().autoRender(data).fadeIn();
}
$(loading).hide();
}
}, datatype );