If string is something then value is null - javascript

In javascript how can I write a function that if string is 'Select client' then address and contact number fields should be null or blank. I have already this function that if client name is selected then address and contact number fields are entered automatically using the populator gem of rails.
$('#client_id').change(function(){
$.ajax({
url: "/fetch_client",
type: "POST",
data: "id="+$(this).attr('value'),
dataType: "json",
success: function(data, textStatus, xhr){
$('#client_address').attr('value',data.client_address);
$('#client_contact_number').attr('value',data.client_contact_number);
},
error: function(xhr, textStatus, errorThrown){
}
});
});
Can some one please help me as I am new to javascript?

$('#client_id').change(function(){
if ($(this).val() == "Select client") {
$('#client_address').attr('value', "");
$('#client_contact_number').attr('value', "");
} else {
$.ajax({
url: "/fetch_client",
type: "POST",
data: "id="+$(this).attr('value'),
dataType: "json",
success: function(data, textStatus, xhr){
$('#client_address').attr('value',data.client_address);
$('#client_contact_number').attr('value',data.client_contact_number);
},
error: function(xhr, textStatus, errorThrown){
}
});
}
});

Related

Handle undefined data in ajax request

I have the below ajax call and sometimes the request stops the page from loading as the data being passed is undefined.
I there a way to put a condition to handle the request if it has values that are undefined?
Can it be wrapped with a if condition?
newuser is not defined
$.ajax(
{
url: 'sample.aspx,
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data){
...
} ,
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
});
Simplest way would be to use a pipe:
$.ajax({url: 'sample.aspx',
data: newuser || {},//continue here...
If your variable was not initialized, empty object will be sent instead.
That's if and only if you can handle empty "newuser" for some reason.
I'm assuming that not closed URL is just a mistake in copy-paste, and not actually part of your code.
how about
if(newuser)
{
$.ajax(
{
url: 'sample.aspx,
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data){
...
} ,
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
});
}
If you are unable to handle an empty newuser you can try something like this:
if (newuser) {
$.ajax({
url: 'sample.aspx',
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data) {
...
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}

How to post whole data to backend?

I am new to web development(Front end) and I have created a form and when I hit submit I want to post the values into the controller "/data" in the backend as a JSON.
So this my code to post the data
$(document).on("click", ".btn btn-warning", function(e) {
var params = {
username: $(".input-group[name=names]").val(),
email: $(".input-group[name=email]").val(),
nicknames: $(".input-group[name=names]").val()
};
$.ajax({
url: back + "/data",
type: "POST",
data: JSON.stringify(params),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data, textStatus, jqXHR) {
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Please enter the correct credentials: " + errorThrown);
}
});
});
My working
pen

calling ajax request inside ajax request

I want to call the jquery ajax inside another ajax success response.'request-status' response return correctly and '.table-responsive' div reloaded what I excepted.But in success response when I tried to call 'welcome-mail' I caught Uncaught SyntaxError: Unexpected token ) .I tried as as
$.ajax({
url: 'request-status',
type: 'GET',
data: {'id':user_id,'status':status,'comment':comment},
dataType: 'JSON',
success: function(data, textStatus, jqXHR){
//alert(data);
$(".table-responsive").load(location.href + " .table-responsive");
$.ajax({
type: "GET",
url: "welcome-mail",
data: {'id':user_id},
dataType: 'JSON',
success: function(data, textStatus, jqXHR){
alert(data);
}
});
},
error: function(jqXHR, textStatus, errorThrown){
// alert('errror');
},
});
Route
Route::get('welcome-mail','travelerHome#welcomeMail');
controller
public function welcomeMail(Request $request)
{
$request_data = $request->all();
$id = $request_data['id'];
return response()->json();
}
You are missing a bracket after success, but have an extra }); that doesn't belong there - it should be:
success: function(data, textStatus, jqXHR){
alert(data);
}
});

jQuery - failing to submit username password and causing 401 unauthorized

When i open using the Google chrome browser this url http://www.site.nl/a/b/c/d/e?niss=f, it first ask for username password:
Manually when i put the username password i get some data.
Now, using jQuery how can i submit that username password? following is not working, always after submit its failing with "401 unauthorized"
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://www.site.nl/a/b/c/d/e?niss=f",
dataType: 'json',
async: false,
headers: {
"Authorization": "Basic Username1:password1234"
},
data: '{ "test" }',
success: function (data, textStatus, jqXHR){
console.log(data, textStatus, jqXHR);
}
});
});
Please try following code
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://www.site.nl/a/b/c/d/e?niss=f",
dataType: 'json',
async: false,
data: '{ "test" }',
beforeSend: function(xhr)
{
xhr.setRequestHeader('Authorization', make_base_auth("Username1", "password1234"));
},
success: function (data, textStatus, jqXHR){
console.log(data, textStatus, jqXHR);
}
});
});
function make_base_auth(user,password)
{
var tok = user + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
} // ends

Jquery ajax post request not working

I have a simple form submission with ajax, but it keeps giving me an error. All the error says is "error". No code, no description. No nothing, when I alert it when it fails.
Javascript with jQuery:
$(document).ready(function(){
$(".post-input").submit(function(){
var postcontent = $(".post-form").val();
if (postcontent == ""){
return false;
}
$(".post-form").attr("disabled", "disabled");
$.ajax({
url: '/post',
type: 'POST',
data: {"post-form": postcontent},
dataType: json,
success: function(response, textStatus, jqXHR) {
alert("Yay!");
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
});
});
HTML:
<form class="post-input" action="" method="post" accept-charset="utf-8">
<textarea class="post-form" name="post-form" rows="1" cols="10" onFocus="this.value='';return false;">What are you thinking about...</textarea>
<p><input class="post-submit" type="submit" name = "post.submitted" value="Post"></p>
</form>
and if there are no problems there, then the server-side (pyramid):
def post(request):
session = Session()
user = authenticated_userid(request)
postContent = request.POST['post-form']
if not postContent == '':
session.add(Activity(user.user_id, 0, postContent, None, None))
return {}
return HTTPNotFound()
UPDATE:
After some more debugging with firebug, I discovered that the post request body contains only post.submitted=Post, instead of the intended result of {"post-form": postcontent}.
According to jQuery documentation, you must declare the data type:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
Also, looking at your server-side code, you don't actually want to post JSON formatted data. This {"post-form":postcontent} is JSON formatted data. What you actually want to do is send TEXT or HTML. Seeming as it's form data, I would guess at TEXT.
Try this:
$.ajax({
url: '/post',
type: 'POST',
data: 'post-form='+postcontent,
dataType: 'text',
success: function(response, textStatus, jqXHR) {
alert("Yay!");
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
Since you are posting JSON-data you have to declare the dataType "JSON":
$.ajax({
url: '/post',
type: 'POST',
dataType: "json",
data: {"post-form": postcontent},
success: function(response, textStatus, jqXHR) {
alert("Yay!");
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
I think the problem is that the data that you are passing is not properly written.
Try to change this:
data: {"post-form": postcontent},
To this:
data: 'post-form='+ $('.post-form').val(),

Categories