Cannot read property 'id' of null if object Null using ajax - javascript

I am trying to retrieve data by using ajax and successfully the data appears, but there is my problem when data is not there I want to try to change its value, but it fails what is wrong with my script? and its error message is
Uncaught TypeError: Cannot read property 'id' of null //this error
$('[name="changeID"]').change(function () {
var url = base_url+'tools/get_id';
var idTools = $('[name="number_tools"]').val();
$.ajax({
url : url,
type: 'POST',
dataType: "JSON",
data: { id : idTools},
success: function(data) {
var result = data.id;
var getNewID = parseInt(result.substr(result.length -3)) + 1;
if (!data) {
$('[name="id"]').val("000"); //error here
}else{
$('[name="id"]').val(getNewID);
}
console.log(result);
},
error: function (request, jqXHR, textStatus, errorThrown) {
console.log(request.responseText);
}
});
});

Change your ajax response to below format,
if(!data)
{
$('[name="id"]').val("000");
}
else
{
var result = data.id;.
var getNewID = parseInt(result.substr(result.length -3)) + 1;
$('[name="id"]').val(getNewID);
}

You are use data object before checking null. If data is null then obviously you will get error of Uncaught TypeError: Cannot read property 'id' of null. You have to use data in if (!data) { } condition.

Related

Autocomplete :Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

The error
"Uncaught TypeError: Cannot use 'in' operator to search for 'length'
in"
is showing in Google chrome console
$(document).ready(function() {
$("#trackerid").change(function() {
var var_locoid = $("#trackerid option:selected").val();
// alert(var_locoid);
$("#deliverylocation").autocomplete({
source: function(request, response) {
var auto_data = $("#deliverylocation").val();
// alert(auto_data);
//alert(var_locoid);
$.ajax({
url: "http://localhost/CodeProject/Testctrl/lookup",
type: "POST",
datatype: "json",
//returnType:"json",
data: {
'var_locoid': var_locoid,
'auto_data': auto_data
},
success: function(data) {
var resp = $.map(data, function(obj) {
return obj.tag;
});
response(resp);
}
});
},
minLength: 1
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this
jQuery.parseJSON(data);
The in operator only works on objects. You are using it on a string. Make sure your value is an object before you using $.map. In this specific case, you have to parse the JSON:
$.map(JSON.parse(data), ...);

Uncaught TypeError: Cannot read property 'split' of undefined

I'm trying to edit a record through AJAX, but it fails intermittently with the following error
Uncaught TypeError: Cannot read property 'split' of undefined
Here is the code:
$.ajax({
type: "POST",
url: url + "/customer/" + customer_id + "/order/" + order_id + "/cust_inline_editing",
data: {
'_token': token,
'order_id': order_id,
'hourid': hourid
},
async: false,
success: function(data) {
$("#inline_submit").text('Update');
var result = JSON.parse(data);
alert(result.dato);
var edit_date = result.dato.null.split("-").reverse().join(".");
$("#dato").val(edit_date);
}
});
What is the cause of the error?
Check condition if result.dato not null then only split.
if(result.dato != null) {
var edit_date = result.dato.split("-").reverse().join(".");
$("#dato").val(edit_date);
}

Uncaught TypeError: Cannot read property toLowerCase of undefined

How can I include the token within all your Ajax requests using jQuery and spring security?
At the moment I get the following error
Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
Javascript:
function editUser(data) {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
var ctx = location.href.substring(0, location.href.lastIndexOf("/"));
var dataObject = JSON.stringify({ 'username': data });
$.ajax({
url: ctx+'/users/edit',
type: 'POST',
beforeSend: function(xhr){
xhr.setRequestHeader(header, token);
},
data: data
});
}
Controller:
#RequestMapping(value = "/users/edit", method = RequestMethod.POST)
public String editUser(#RequestParam("username") String username) {
System.out.println(username);
return "users/edit";
}
toLowerCase function is in jQuery
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
Either make sure that the page always has <meta name="_csrf" content="something"> and <meta name="_csrf_header" content="something"> tags, or have your AJAX code check that the values exist before trying to set the header:
beforeSend: function(xhr) {
if (header && token) {
xhr.setRequestHeader(header, token);
}
}

Passing dynamic field names to jquery's each method

I'm trying to pass a field name dynamically to my function in order for my form to use autocomplete. I then call this function in my page but I keep getting an error and I think it's because it's trying to get the column property literally as opposed to dynamically.
In PHP I could do something like {$fieldName}. Is there a javascript equivalent? Or am I getting this horribly wrong?
// Call to function index.php
inputSuggetion('input.search', 'http://myapi.com/endpoint', 'title')
// Function
function inputSuggestion(element, endPoint, fieldName) {
$(element).on("keydown", function(event) {
$.ajax({
type: 'GET',
dataType: "json",
data: {
q: $(element).val()
},
url: endPoint,
success: function(data) {
var apiCollection = [];
$.each(data, function(key, value) {
apiCollection.push(value.fieldName);
});
$(".autocomplete").autocomplete({
source: apiCollection
});
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
});
}
Thanks!
If I'm right then you want to get the value of field 'title' from your Json data and this field name 'title' will be passed to the function dynamically.
In this case your syntax to get the value from json is wrong.
you just need to change following line of code:
from :
apiCollection.push(value.fieldName);
to :
apiCollection.push(value[fieldName]);
let me know in case of any issue.

Cannot access data in JSON response

I am trying the access the json response from the server, using the following code. According to firebug, my server is outputting what looks like a valid json response as follows:
{"result":"error","message":"This group is not empty"}
my JavaScript is as below, but when I try to alert() the data from json response, I get nothing
$.ajax({
type: 'post',
url: data_ajax_url,
dataType: 'json',
data: 'data_mysql_record_id=' + data_mysql_record_id + '&data_mysql_table_name=' + data_mysql_table_name,
//success, annimate and remove row
success: function(data){
alert(data.result);
//get a json message from server if one exists
$ajax_response = data.message;
if ($ajax_response == '' || $ajax_response == 'undefined') {
$ajax_response = 'Request has been completed';
}
//slide up table row
parent.slideUp(300, function(){
parent.remove();
});
//show noty notification 1 sec later
setTimeout(function(){
noty({
text: $ajax_response,
layout: 'bottomRight',
type: 'information',
timeout: 1300
});
}, 1000);
},
//error - alert
error: function(data){
alert(data.result); //my test
//get a json message from server if one exists
$ajax_response = data.message; //where 'message' is key in php jason output
if ($ajax_response == '' || $ajax_response == 'undefined') {
$ajax_response = 'Error!- This request could not be completed';
}
//fire up a noty message
noty({
text: ''+$ajax_response,
layout: 'bottomRight',
type: 'warning',
timeout: 1300
});
}
UPDATE:
//data = jQuery.parseJSON(data);
console.log(data);
Console.log is giving me this
readyState
4
responseJSON
Object { result="error", message="This group is not empty"}
responseText
"{"result":"error","mess...is group is not empty"}"
status
400
statusText
"Bad Request"
and
data = jQuery.parseJSON(data);
console.log(data);
is giving this error
SyntaxError: JSON.parse: unexpected character
...nction(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i) {if("string"...
The status 400 and "bad request" is something I am oputiing in my php headers to show that there was an error backend
The error handler of an $.ajax request has the signature
Function( jqXHR jqXHR, String textStatus, String errorThrown )
[…] receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred.
Change your function to
error: function(jqXhr) {
var data = jqXhr.responseJSON; // you saw this in your console.log
if (data) {
…
} else {
// there might be other errors, where you don't get the server message
}
}
The problem is with parsing the JSON data in the javascript :
Before using the json data
data=jQuery.parseJSON(data);
alert(data.result);
Try this.
Use jQuery.parseJSON and might I suggest to use console.log instead of alert, like this:
$.ajax({
type: 'post',
url: data_ajax_url,
dataType: 'json',
data: 'data_mysql_record_id=' + data_mysql_record_id + '&data_mysql_table_name=' + data_mysql_table_name,
//success, annimate and remove row
success: function(data){
data = jQuery.parseJSON(data);
console.log(data.result);
//get a json message from server if one exists
$ajax_response = data.message;
if ($ajax_response == '' || $ajax_response == 'undefined') {
$ajax_response = 'Request has been completed';
}
//slide up table row
parent.slideUp(300, function(){
parent.remove();
});
//show noty notification 1 sec later
setTimeout(function(){
noty({
text: $ajax_response,
layout: 'bottomRight',
type: 'information',
timeout: 1300
});
}, 1000);
},
//error - alert
error: function(data){
data = jQuery.parseJSON(data);
console.log(data); //my test
//get a json message from server if one exists
$ajax_response = data.message; //where 'message' is key in php jason output
if ($ajax_response == '' || $ajax_response == 'undefined') {
$ajax_response = 'Error!- This request could not be completed';
}
//fire up a noty message
noty({
text: ''+$ajax_response,
layout: 'bottomRight',
type: 'warning',
timeout: 1300
});
}

Categories

Resources