I have a problem here, I want to create conditions like if (isset) in PHP, but after ajax response
the response received here is like this if it is empty:
(2) [Array(0), Array(0)]
0: []
1: []
length: 2
and like this if there is data:
0: {description_content: "mnadmnsa", course_content1: "madmna", course_content2: "mmnsadm", course_content3: "msadn", …}
1: {course_content1: "madmna", course_content2: "mmnsadm", course_content3: "msadn", course_content4: "msandm"}
length: 2
I have tried with the empty method but an error:
empty is not defined
This is my code:
$.ajax({
type : "get",
url : url,
success:function(data){
if (empty (data[0]) !=null) {
console.log('has data');
}else{
console.log('data');
}
}
Just remove the empty() function, as that is invalid JS. With that said, here is you adjusted code:
$.ajax({
type: 'get',
url: url,
success: function (data) {
if (data[0] != null) {
console.log('has data');
} else {
console.log('does not have data');
}
}
});
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I am trying to make a desktop like text input help using datatable.in table with keyboard navigation.
For that I am dynamically changing the source and also change the header column. So far I have succeeded in that except getting dynamic column header.
For getting the column header based on the text input header, I am making an ajax call and getting the list of column header. the issue is during first call ajax returns undefined but in the second call it shows the value. I understand this is pertaining to the asynchronous call but not sure how to handle this.
Below is my code snips.
AJAX call in external .js
function ajaxCall(ipUrl, callType = "POST", dataIn) {
return $.ajax({
url: ipUrl,
type: callType,
data: dataIn,
dataType: "json",
success: function (response) {
retData = response.data;
alert('success'+ retData);
return retData;
}, error: function (err) {
alert("fail" + JSON.stringify(err));
}, //error
});
//alert('in js'+ retData);
//return retData;
}
HTML Script tag
$("#btn").click( function (e) {
var tData = { action: 'getHeader',
csrfmiddlewaretoken: 'Gys4TSx3ODJLcMDuXlSvS7DopVZr1HWEDLg9AlJsARXp7wmUGAxxKwo6uLVXIrf2',
}
tmp = ajaxCall('dyncolheader','GET',tData) ;
if (tmp == undefined) {
alert('second call');
tmp = ajaxCall('dyncolheader','GET',tData) ;
alert('tmp' + tmp);
} else {
alert('else' + tmp);
}
});
Django View code
def dyncolheader(request):
hrdText = 'First,Second,Third'
if request.is_ajax and request.method == 'GET':
print('ajax call')
if request.GET.get('action') == 'getHeader':
print('get header')
return JsonResponse({ 'data': hrdText }, status=200)
return render(request, 'dyncolheader.html')
use this code in external.js file
function ajaxCall(ipUrl, callType = "POST", dataIn) {
console.log('function Call', ipUrl, callType, dataIn);
retData = null;
$.ajax({
url: ipUrl,
type: callType,
data: dataIn,
dataType: "json",
async: false,
success: function (response) {
retData = response.data;
},
error: function (err) {
alert("fail" + JSON.stringify(err));
},
});
console.log('retData', retData);
return retData;
}
here is my web method
[HttpGet]
public ActionResult EditEmp(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Employee Emp = db.Employees.Find(id);
if (Emp == null)
{
return HttpNotFound();
}
ViewBag.dept_id = new SelectList(db.Departments, "dept_id", "dept_name", Emp.dept_id);
return PartialView("_EditEmp", Emp);
}
and here is the ajax call
$.ajax({
type: "GET",
url: '/Employee/EditEmp',
data: { id: idp },
dataType: "json",
success: function (result) {
alert(result);
$('#editid').html(result);
},
error: function (result) {
alert("FAILED : " + result.status + ' ' + result.statusText);
}
});
it gives me result.status =200 and result.statusText = OK but it fire Error Event
Please check that you are returning valid json or not, because you are setting
dataType: "json"
it evaluates the response as JSON and returns a JavaScript object. (...) The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown.
You may want to see this
I am trying to make an Ajax call inside another Ajax success function but it somehow doesn't work. I get the following error in my console. I don't understand what it means:
Object { readyState: 0, getResponseHeader: .ajax/v.getResponseHeader(), getAllResponseHeaders: .ajax/v.getAllResponseHeaders(), setRequestHeader: .ajax/v.setRequestHeader(), overrideMimeType: .ajax/v.overrideMimeType(), statusCode: .ajax/v.statusCode(), abort: .ajax/v.abort(), state: .Deferred/d.state(), always: .Deferred/d.always(), then: .Deferred/d.then(), 10 more… }
I found something like below from the object
statusText:"SyntaxError: An invalid or illegal string was specified"
JS
//Update the board with the moves so far made
var updateBoard = function() {
var style;
$.ajax({
type: "POST",
url: "engine/main.php",
data: {code: 2},
success: function(response) {
if(response != "") {
var obj = JSON.parse(response);
lastClick = obj[obj.length - 1].player;
$(obj).each(function (i, val) {
if (val.player == 1) {
style = "cross";
}
else if (val.player == 2) {
style = "circle";
}
$('td[data-cell="' + val.cell + '"]').html(val.sign).addClass(style);
});
if(obj.length > 2) {
makeDecision();
}
}
else {
lastClick = null;
$('td').html("").removeClass();
}
setTimeout(updateBoard, 1000);
}
});
};
updateBoard();
function makeDecision() {
console.log('starting decision function');
$.ajax({
type: "engine/main.php",
data: {code: 3},
success: function(winner) {
console.log('end');
console.log(winner);
},
error: function(data) {
console.log(data);
}
});
}
PHP
if(isset($_POST['code'])) {
$code = $_POST['code'];
//Handle player number on game start
if($code == 1) {
if (!isset($_COOKIE['gamePlay'])) {
header('Location: index');
}
$playerCode = $_COOKIE['gamePlay'];
$player = $playersHandler->getPlayer($playerCode);
echo $player;
}
// Update board with new moves
else if($code == 2) {
$currentPosition = $gameHandler->getMoves();
echo $currentPosition;
}
else if($code == 3) {
$result = $code; //$gameHandler->decide();
echo $result;
}
//Reset Board
else if($code == 4) {
$gameHandler->reset();
}
}
You are passing an invalid string to type property inside the makeDecision function ajax call. You should set this as following:
type: 'POST',
url: 'engine/main.php',
...
instead of
type: 'engine/main.php'
Make sure that the following line
var obj = JSON.parse(response);
returns an array, not an object. If obj is not an array, then obj.length is undefined
You can not get length of object directly obj.length in javascript.So if you are getting response properly.Get length of Parsed object like this..
var length = Object.keys(obj).length;
Then
lastClick = obj[length-1].player;
Make correct use of $.each like this..
$.each(obj,function (i, val){
//code
});
You can call ajax again inside the ajaxComplate event like this:
$( document ).ajaxComplete(function() {
$.ajax({
type: "post",
url: 'engine/main.php',
data: {code: 3},
success: function(winner) {
console.log('end');
console.log(winner);
},
error: function(data) {
console.log(data);
}
});
});
this is how the javascript looks like
<script type="text/javascript">
$(document).ready(function () {
$('#loginButton').click(function () {
//this.disabled = true;
debugger;
var data = {
"userid": $("#username").val(),
"password": $("#password").val()
};
$.ajax({
url: "/Account/LoginPost",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
},
error: function () {
alert('Login Fail!!!');
}
});
});
});
I am getting the alert('Login fail') also debugger not getting hit.
I am using jquery 1.9.1 and have included unobstrusive
my controller is this as you can i am passing string values not object values
to the controller so stringify is justified here
[HttpPost]
public JsonResult LoginPost(string userid, string password)
{
using (someentities wk = new someentities())
{
var LoginUser = wk.tblUsers.Where(a => a.Username.Equals(userid)&&a.Password.Equals(password)).FirstOrDefault();
if (LoginUser != null)
{
FormsAuthentication.SetAuthCookie(userid,false);
Session["Username"] = LoginUser.Username;
Session["Password"] = LoginUser.Password;
Session["Name"] = LoginUser.Name;
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
else
{
TempData["Login"] = "Please Enter Correct Login Details";
return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
}
}
// If we got this far, something failed, redisplay form
}
when page is loading these error are shown
$(..) live is not a valid function in
(anonymous function) # jquery.unobtrusive-ajax.js:115
(anonymous function) # jquery.unobtrusive-ajax.js:163
take a look to the success function
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
}
you are using multiple ", combine it with the single one ', this is a syntax error, try to check the code on an editor such as Atom, to avoid this kind of errors
Stringify converts an object to a string. Have you tried passing data an object instead of a string? Try replacing JSON.stringify(data), with data?
I have the following ajax call
function update_ledger_amount(id) {
$.ajax({
type: "POST",
url: "/ledgeritems/UpdateAmount",
data: "Id=" + id + "&Amount=" + $('#ledger_edit_amount_input_' + id).val(),
success: function (str) {
var result = str.split('|');
alert(str);
if (result[0] == 'success') {
set_display_message('Item updated', 'success');
load_ledger_month($('#BankAccountId').val(), $('#StartDate').val());
}
else {
alert('bad');
set_display_message(result[1], 'error');
}
},
error: function (request, status, error) {
alert(error);
}
});
}
The problem I'm having is that I get no alerts on success or error. Watching the traffic via firebug I can see the response is a simple
success
I believe the problem could have to do with the content-type of the response, it shows as text/javascript. I'm thinking maybe I need to do something different to handle that content type.
use dataType as json and send the response as json in your controller(php).. you can do that by ...echo json_encode(array('success'=>'success'))
JQUERY
$.ajax({
type: "POST",
url: "/ledgeritems/UpdateAmount",
data: "Id=" + id + "&Amount=" + $('#ledger_edit_amount_input_' + id).val(),
dataType:'json',
success: function (str) {
alert(str.success); //in mycase.. you can do your stuff here
/*var result = str.split('|');
alert(str);
if (result[0] == 'success') {
set_display_message('Item updated', 'success');
load_ledger_month($('#BankAccountId').val(), $('#StartDate').val());
}
else {
alert('bad');
set_display_message(result[1], 'error');
}*/
},
error: function (request, status, error) {
alert(error);
}
});
PHP
.....
echo json_encode(array('success'=>'success'));
this sends success as json and you can get that in success function of ajax
put a try catch block in your success handler. I guess it is failing at this line
ar result = str.split('|');
You're doing a POST ajax not GET. The data part of the ajax should be in the form of:
data: { name: "John", location: "Boston" }
Remove the line
type = "POST",
because you want to append params to the url with your request.
As of jQuery 1.8 success, error and complete are deprecated, use done, fail and allways instead.
http://api.jquery.com/jQuery.ajax/#jqXHR
The syntax for a POST would be like:
data = {id:"something", Amount:"someval"};