I have a select menu that, when a user makes a selection, it fires off an AJAX request to a PHP script to query a database and return a value that matches the selection and inserts this into an associated input field.
This is all working well, however I now need to cater for the possibility that an empty result might be returned (up until now a matching result was always returned). If that is the case it needs to delete the value from the associated input field/clear this input field.
Here's what a successful AJAX request returns (JSON data):
[{"senderMobile":"0412 345 678"}]
and here's what an empty result returns:
[{"senderMobile":""}]
Here's the AJAX code that calls the PHP script and updates the input field:
$(document).ready(function() {
$("#smsFromName").change(function() {
var smsFromName = $("#smsFromName").val();
console.log(smsFromName);
$.post('getSMSSender.php', {
senderName: smsFromName
}, function(data) {
data = JSON.parse(data);
if (data.error) {
alert("error");
$("#smsFrom").html('');
return; // stop executing this function any further
} else {
console.log(data[0].smsFrom);
$("#smsFrom").val(data[0].senderMobile);
}
}).fail(function(xhr) {
$("#smsFrom").html('');
});
});
});
I gather I need to update this section to include an option that if there is no data to simply clear out the #smsFrom input field:
} else {
console.log( data[0].smsFrom );
$("#smsFrom").val(data[0].senderMobile);
but I'm stumped at this point.
You just need to check if senderMobile has a value. Try this:
if (data.error) {
alert("error");
$("#smsFrom").html('');
return; // stop executing this function any further
} else if (data[0] && data[0].senderMobile) {
console.log(data[0].smsFrom);
$("#smsFrom").val(data[0].senderMobile);
} else {
$("#smsFrom").val(""); // or .html(""); I didn't get what kind of element is this...
}
You can try checking the response data for an empty string.
Code should look like this:
$(document).ready(function() {
$("#smsFromName").change(function() {
var smsFromName = $("#smsFromName").val();
console.log(smsFromName);
$.post('getSMSSender.php', {
senderName: smsFromName
}, function(data) {
data = JSON.parse(data);
if (data.error) {
alert("error");
$("#smsFrom").html('');
return; // stop executing this function any further
} else {
if(data[0].senderMobile == ""){
$("#smsFrom").empty();
continue;
}else {
console.log(data[0].smsFrom);
$("#smsFrom").val(data[0].senderMobile);
}
}
}).fail(function(xhr) {
$("#smsFrom").html('');
});
});
});
Related
I have a JSON request using post method using ajax within this code
$(document).ready(function() {
$(document).on('submit', '#registration_check', function() {
var data = $(this).serialize();
$.ajax({
type: 'POST',
url: 'apidomain.com',
data: data,
success: function(data) {
$("#registration_check").fadeOut(500).hide(function() {
$(".result_1").fadeIn(500).show(function() {
$(".result_1").html(data);
});
});
}
});
return false;
});
});
the response will return 3 fields like name, email, phone on this element:
<div id="result_1"></div>
it's working nice so far, but want I plan to do is I want to display the alert or popup message if the ajax response found some of return value null. For example:
If JSON response return:
name: jhon, email: jhon#doe.com, phone: 123456789
user will redirect to the other page (done so far)
But if JSON response return
name: jane, email: jane#doe.com, phone:
The popup or alert will appeared, within text phone number empty.
If your data is a JSON object then you can do:
success: function(data) {
for (var i in data) {
if (!data[i]) {
alert(/* MESSAGE HERE */)
return;
}
}
// Your regular code here
}
You can make an associative array of your values in php file and echo it in the json format like
echo json_encode($array);
Then you will receive this in your ajax response like this
var objs = JSON.parse(data);
Then you can parse the values by keys like name, email and phone as you defined in associative array in your php file
console.log(objs.name);
console.log(objs.email);
console.log(objs.phone);
This is how you can parse the values individually. You can also apply conditions by your own way
First thing that comes to my mind: Do you need the JSON response in the document element or is it, that you dont know how to work with jQuery Ajax?
Anyway, this solution should help you in both cases:
$(document).ready(function()
{
$(document).on('submit', '#registration_check', function()
{
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'apidomain.com',
data : data,
dataType: 'json', // tell jQuery, that the response data will be a JSON - it will be parsed automatically
success : function(data)
{
// now you have a parsed JSON object in the 'data' var
var show_alert = false;
if (data.phone === null || !data.phone.length) {
show_alert = true;
}
if (data.email === null || !data.email.length) {
show_alert = true;
}
if (show_alert) {
alert('here is the alert :)');
}
$("#registration_check").fadeOut(500).hide(function()
{
$(".result_1").fadeIn(500).show(function()
{
$(".result_1").html(JSON.stringify(data));
});
});
}
});
return false;
});
});
I'm trying to build a product compare module with a bootstrap 4 dropdown.
Inside that dropdown there are products listed with some info. When you click delete at a product then a function called updateCompareis loaded. This function loads json data and updates the compare list. This all works fine except when there's only one product listed. When I click delete on the last item then the function throw errors.
So what I have is this:
function updateCompare(){
$.get(compareUrl + '?format=json', function(e) {
products = [];
$.each(e.compare.products, function(index, product) {
// ... code to build products ....
products.push(productHtml);
});
products.join('');
$('#compare .compare-inner .empty').html(products);
})
}
$(function(){
// delete product from compare
$(document).on("click", "#compare .remove", function(e) {
e.preventDefault();
var vid = $(this).closest('.item').data('vid');
var url = compareUrl + 'delete/' + vid;
$.ajax({
type: "POST",
url: url,
success: function(msg){
updateCompare()
}
});
});
});
The error I get is TypeError: a is undefined
What I tried in updateCompare is things like:
function updateCompare(){
$.get(compareUrl + '?format=json', function(e) {
products = [];
if(e.compare.products.length > 1 ){
$.each(e.compare.products, function(index, product) {
// .... code to build products
});
} else {
$('#compare').dropdown("dispose")
}
But above throws an error like: TypeError: e.compare.products is undefined
Also I tried:
if(e.compare.products.length > 1 || e.compare.products != NULL || e.compare.products != false ){
But that throws an error e.compare.products is undefined.
I've been working on this way too long so perhaps I miss something very simple. I just can't see it anymore :(
Any help greatly appreciated!!
As per request
Empty compare json:
{
"compare":false
}
JSON with 3 products:
{
"compare":{
"products":[
{
"id":39687158,
},
{
"id":39687161,
},
{
"id":39687164,
}
]
},
}
I have a form with AJAX submit.
This form is working, but I have the impression that the functions are not correct.
jQuery(document).ready(function(){
var myForm = $("#ajax_form"), email = $("#email"), emailInfo = $("#emailInfo"), ck1 = $("#ck1"), ck2 = $("#ck2"), ck3 = $("#ck3");
jQuery('#ajax_form').submit(function(){
var dados = jQuery( this ).serialize();
jQuery.ajax({
type: "POST",
url: "check.php", // Checking data
data: dados,
beforeSend: function(){
emailInfo.html("<font color='blue'>Checking..</font>");
if(dados == "email=") // >>> This field, how to check if the field is blank?
{
email.focus();
emailInfo.html("<font color='red'>Required.</font>");
return false;
}
},
success: function(data){
if(data == "invalid")
{
emailInfo.html("<font color='red'>Invalid.</font>");
}
else if(data != "0")
{
email.val(data); // This field, how to display the data sent in the email field? not the return of PHP,
ck1.css("display", "none");
ck2.css("display", "inline");
}
else
{
ck1.css("display", "none");
ck2.css("display", "none");
ck3.css("display", "inline");
}
}
});
return false;
});
});
I think that has a lot of wrong code, for example:
if(dados == "email=") // >>> This field, how to check if the field is blank?
and >>
email.val(data); // This field, how to display the data sent in the email field? not the return of PHP,
I tried to update but not return any results
Test Code
//if (email.val() == "")
//{
//email.focus();
alert(email.val()); // op1
alert(dados); // op2
alert($.trim($('email').val())); // op3
emailInfo.html("<font color='red'>Required.</font>");
return false;
//}
if insert an email, the only option that returns is op2 email=teste#teste.com
I think your code is trying to validate email by ajax before submitting form. If so this code seems ok to me out of a few points.
return false at the end of submit call may not work on firefox. Use e.preventDefault();. Look at this post. If you try this code on chrome it may fail beacuse you have no return true anywhere.
Your second code block is ok. email.val(data); is equal to $("#email").val(data);. I think you are trying to set the email input value to the result.
if(dados == "email=") can be changed to if (email.val() != ''). So you wont need to dados also.
You don't use myForm variable nowhere. It should be deleted.
If validating the email on server side is not a must think about validating on client side.
The returned data value is echoed from your PHP file. There are two approaches to take to validate your data:
Do it in the frontend with JS prior to sending your form.
Do it with your PHP code in the separate file.
email.val(data); // This field, how to display the data
sent in the email field? not the return of PHP
I am guessing that you want to ensure that the value doesn't get deleted if the user sends an invalid request (thus having to type the value in again).
What you can do is store the values of what the user has entered on form submit but prior to sending the AJAX request: var emailVal = email.val();
jQuery(document).ready(function(){
var myForm = $("#ajax_form"), email = $("#email"), emailInfo = $("#emailInfo"), ck1 = $("#ck1"), ck2 = $("#ck2"), ck3 = $("#ck3");
jQuery('#ajax_form').submit(function(){
var dados = jQuery( this ).serialize();
var emailVal = email.val(); // Assign the entered input to an emailVal variable
jQuery.ajax({
type: "POST",
url: "check.php", // Checking data
data: dados,
beforeSend: function(){
emailInfo.html("<font color='blue'>Checking..</font>");
if(dados == "email=") // >>> This field, how to check if the field is blank?
{
email.focus();
emailInfo.html("<font color='red'>Required.</font>");
return false;
}
},
success: function(data){
if(data == "invalid")
{
emailInfo.html("<font color='red'>Invalid.</font>");
}
else if(data != "0")
{
email.val(emailVal); // Store the entered value back into the email input
ck1.css("display", "none");
ck2.css("display", "inline");
}
else
{
ck1.css("display", "none");
ck2.css("display", "none");
ck3.css("display", "inline");
}
}
});
return false;
});
});
Another Note
I would also like to point out this: if(data == "invalid")
I have found that PHP can send back error messages within the data along with whatever you ask it to return. If you have any error in your PHP code, this will never hit because invalid will never be the only string of characters in the returned data value. To protect yourself, I would do either two things:
Return an HTTP error and do error handling within the error callback of the AJAX function: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Return a unique word and search for that word within the returned data string:
PHP
if(!validEmailCheck($email)){
echo('invalidRAWR');
}
JS
if(data.indexOf('invalidRAWR') != -1) // Built in PHP errors will never return 'invalidRAWR'
I'm developing a website, and right now the registration form of it! But I have something like a problem! I want to create a Username input field, and when the user is typing, check if the username already exists in the database and give some output.
The error is this one: suppose that in the database there is only the username "Manuel". If I type "Manuel" in the input field no message is shown. Now if I type any other character it gives me the message 'The user already exists'. If i delete the last typed character the message goes away. If I type again and have something like "Manuela", the message shows up, if I type again and have "Manuelae" the message goes away
Thanks for your help!!
Here the code
Here the input field: (register.php)
<input type="text" id="username" name="username" maxlength="40" required="required">
<span id="username-info">What's your username?</span>
Here the javascript and jquery code (registration.js)
$(document).ready(function () {
var userExists = new Boolean();
var username = $("#username");
var usernameInfo = $("#username-info");
username.keyup(validateUsername);
}
Here the function validateUsername():
function validateUsername(){
checkUsername();
var minlenght = 5;
var usernameVal = username.val();
if(usernameVal.length < 1){
usernameInfo.addClass("input-error");
usernameInfo.text(messages.FIELD_REQUIRED);
} else if(usernameVal.length < minlenght){
usernameInfo.addClass("input-error");
usernameInfo.text(messages.USERNAME_MIN_WORDS+minlenght+' '+messages.USERNAME_CHARACTERS);
} else if(userExists){
//here i tell the user that the user already exists
usernameInfo.addClass("input-error");
usernameInfo.text('The user already exists');
} else {
usernameInfo.removeClass("input-error");
usernameInfo.text("");
}
}
And here the function checkUsername():
function checkUsername() {
var url = 'processregistration.inc.php';
$.ajax({
type: "POST",
dataType:"json",
url: url,
data: {username: username.val()},
success: function(data){
userExists = data.CHECK; //true if the user exists, false if not
}
});
}
Ajax means Asynchronous JavaScript and XML.
You are doing a check on a value which is actually not received.
You should do something like this :
function validateUsername() {
// remove input-error, text
if (...localcheck...) {
// add input-error, text
}
else if (...otherlocalcheck...) {
// add input-error, text
}
else {
$.ajax({
...
success : function(data) {
if (data.CHECK) {
// add input-error, text
}
}
});
}
}
I think you are on the right track, but I don't think your implementation is correct.
Note: I'm not a javascript hero
$("#filter").keyup( function(e) {
var filter = $("#filter").val(),
timer = $('#filter').data('timeout'),
if(timer) {
clearTimeout(timer);
$('#username').removeData('timeout');
}
$('#username').data('timeout', setTimeout(function() {
var url = 'processregistration.inc.php';
$.POST(url, {username: $('#username').val()}, function(data) {
// you get the picture ;)
updateComponentThatShowsIfUserNameIsTakenFunction(data.CHECK);
});
}, 100));
function updateComponentThatShowsIfUserNameIsTakenFunction(taken) {
$('#username').addClass('input_error');
}
What I did: Removed global variables, they are annoying and error prone. Instead, I'm using a callback named updateComponentThatShowsIfUserNameIsTakenFunction. You can also change it to directly call that function with the "data" of course. I have also added a timeout for you so that you won't call the server EVERY key-up. Every key-up cancels the previous timeout, causing the check to only trigger 100ms after the user is done typing (you don't want to spam your server).
I hope this works and helps you further!
When i use blur function on textbox to check duplicate name using jquery ajax working fine.
Here is code:
function duplicate(data){
//alert(data); //successfully gives the value from the text input
$.post("test.php", {name: data}, function (data){
if(data){
alert('duplicate name');
}
});
}
$(function() {
$("#name").blur(function(){
var data = $("#name").val();
duplicate(data);
});
});
The problem is it show alert message, in some case we submit with duplicate name itself so there is no use of checking duplication.
Let me know the solution to check duplicate name using onsubmit function ( jquery ajax or javascript ).
Your question is confusing because you're using the same variable name, data, outside of your request as well as in the request callback.
I'm not sure if you're asking to check for duplication based on data that has already been submitted and is back on the page, data that exists on the server, or if the data's simply "yes".
Based on the code you provided, it would appear that data is considered to be duplicated if the server returns yes once the POST completes.
Either way, maybe this will help:
$(function() {
$('#name').blur(function() {
duplicate($('#name').val());
});
});
function duplicate(sData) {
var sDuplicateValue = ...; // assign this whatever constitutes a duplicate value
if(isDataDuplicate(sData, sDuplicateValue)) {
// you have duplicate data
}
$.post('test.php', { name: sData }, function(sResposeData) {
/* because of question ambiguity, i don't know if you want to compare
* sData and sResponseData, or sResponseData and "yes." if it's the latter,
* just do isDataDuplicate(sResponseData, "yes"); otherwise, do this:
*/
if(isDataDuplicate(sData, sResponseData) {
// it's the same..
}
});
}
function isDataDuplicate(sData, sDuplicateValue) {
if(sDuplicateValue === null) {
return sData === 'yes';
} else {
return sData === sDuplicateValue;
}
}
I'll do something like this:
$(function() {
$("#name").blur(function(){
var value = $("#name").val();
$.post(
"checkDuplicates.php",
{ name: value},
function (data){
if( data.response === 'yes'){
$("#name").css({
'border': '1px red solid'
}).parent().append('This name already exists');
} else {
return false;
}
},
'json'
);
});
});