AJAX request confusion in jQuery - javascript

I am unable to understand that why the jquery AJAX is not fetching data from the ajax page.
Can someone please help.
<script type="text/javascript">
$(function() {
$('#lms_id').change(function(){
if ($(this).val() != "") {
// alert("1");
} else {
// alert("0");
}
});
$('#lms_user_role_id').change(function(){
if (($(this).val() == "7" || $(this).val() == "8")) {
$('#t_lms_dealers').show();
} else {
$('#t_lms_dealers').hide();
}
});
});
function loadAjax(message)
{
//alert(message);
//$.get("<?php echo $App['wwwroot'].'er.php' ?>?activity="+message);
$.get("http://www.abc.loc/er.php");
}
</script>
In loadAjax function, alert is alerting fine, but only the AJAX part is not working.

How do you know it is "not working"?
$.get("http://www.abc.loc/lmsapi/LMS_L2/templates/admin/user/tpl.user_dealer.php");
Even if it did, this statement would accomplish nothing. You need to put a handler in there:
$.get(
"http://www.abc.loc/lmsapi/LMS_L2/templates/admin/user/tpl.user_dealer.php",
function (data) {
alert("Retrieved :"+data);
}
);
You should also use some kind of in browser developer tool (eg, firebug) that will allow you to trace the request in real time. Finally, the plain jquery get lacks an error handler; you might want to instead use:
$.ajax ({
url: "http://www.abc.loc/lmsapi/LMS_L2/templates/admin/user/tpl.user_dealer.php",
success: function (data) {
alert(data);
},
error: function (xhr, err, code) {
alert("Error: "+err);
}
});
And read the query documentation:
http://api.jquery.com/category/ajax/

if i am not wrong 2nd possibility is may be you are trying "cross domain ajax call", if yes then you have to set header "Access-Control-Allow-Origin" and "crossDomain: true" for $.ajax call.

Related

outputting response to browser

am posting half code coz the rest is working.
just need to see if wat i want can work
Question: is it possible to send alert() errors to browsers. because alert() just output errors in popup window up the browser
so i want to do it like in success function where u do
$('#resp').text(response.feedback); and send response to html like <div id="resp"></div>
so my main question is it possible to send alert() errors to browser than popup up on browser.
to send it in browser and call it with id like above success function
beforeSend: function(){
if ($("form input[name='email']").val() == "") {
alert("Text-field is empty.");
return false;
}
},
success: function(response) {
$("#Submit").attr("disabled", true);
$('#resp').text(response.feedback);
},
if I understood you correctly:
beforeSend: function(){
if ($("form input[name='email']").val() == "") {
$('#resp').text('TextField is Empty');
return false;
},
},
success: function(response) {
$("#Submit").attr("disabled", true);
$('#resp').text(response.feedback);
},
You will need to send some flag/message back to the browser in your server response. Then check for that flag/message, and present an alert() in your client side code.
e.g.
function showMessage(msg){
alert(msg);
}
//in your success bit
success: function(response){
if(response.someFlagYouSet == "NO_SUPPLIES_LEFT"){
showMessage("There are no supplies left... sorry");
}
}
Rather than
alert("Text-field is empty.");
do
$('#resp').text("Text-field is empty.");

javascript not show results on success

I have this JavaScript code:
<script type="text/javascript">
$(document).ready(function() {
$(".deleteImage").on('click', function() {
var idmess = $(this).data("id");
var token = $(this).data("token");
$.ajax({
url: '{{ url('admin/deletemulti') }}/'+encodeURI(idmess),
type: 'DELETE',
dataType: "JSON",
data: {
"id": idmess,
"_method": 'DELETE',
"_token": token,
},
success:function() {
alert("it Work");
}
});
});
});
</script>
is working just fine (data is removing from my DB and I get 200 in network), except I cannot get my alert any idea why is that?
UPDATE
my network
my network response
Delete Function
function destroy(Request $request) {
$image = Image::find($request->id);
Storage::delete($image->name);
$image->delete();
}
try passing an argument in your success function.
success:function(data) {
alert("it Work");
}
You have used ajax with dataType : json
So you need to respond with a valid JSON as HttpResponse else it gets into a error event.
The response of your api call:
{{ url('admin/deletemulti') }}/'+encodeURI(idmess)
should be a valid JSON. Please check api response value and fix it, or share it so that we can help you update that.
In case the response is not a valid JSON, success function will never get triggered and hence alert is not getting executed.
More info :
Ajax request returns 200 OK, but an error event is fired instead of success
When I'm making backend for myown use, and when I'm writing json, I usually put my json on success like session = true, or something like that, so later you can check like :
success: function(json) {
if(json.session == true) {
alert('something')
}
}
Maybe it's not the best solution, but it's working perfectly for me.

getJSON in Javascript

I am new to html and javascript.As far as i know the following code should give an alert when i press "Get JSON Data" button.But the page is not giving me any response.Any help is greatly appreciated.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://127.0.0.1:5000/2", function(result){
if (result.length == 0){
alert("nothing") ;
}
if (result.length){
alert("success") ;
}
// $("div").append(myObject);
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
I suspected that should be the Cross-domain issue. That is why I asked for the console log. you have couple of choices:
config the cross-domain headers from your servlet/backend response.
(ex: if you're using a Servlet:)
response.setHeader('Access-Control-Allow-Origin','*');
use jsonp call back
$.getJSON("http://example.com/something.json?callback=?", function(result){
//response data are now in the result variable
alert(result);
});
The "?" on the end of the URL tells jQuery that it is a JSONP
request instead of JSON. jQuery registers and calls the callback
function automatically.
use $.ajax with CORS enabled or with jsonp
ex:
$.ajax({
url: surl,
data: {
id: id // data to be sent to server
},
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpcallback"
});
// Named callback function from the ajax call when event fired.
function jsonpcallback(rtndata) {
// Get the id from the returned JSON string and use it to reference the target jQuery object.
var myid = "#" + rtndata.id;
$(myid).feedback(rtndata.message, {
duration: 4000,
above: true
});
}
or else, download and configure "CORS.jar" in your server side which will allow the cross-domain requests.
HOW ?
Hope you can get some idea. follow which suits for you ..
Replace the JSON call with
$.getJSON("http://127.0.0.1:5000/2", function(result){
if (result.length == 0){
alert("nothing") ;
}
if (result.length){
alert("success") ;
}
// $("div").append(myObject);
}).fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err )
});
That way you can see what goes wrong. The javascript looks OK, I suspect it's a server issue.
You could also try getting back JSON from some random source, like http://1882.no/API/business/get/results.php?q=skole&page=0

Ajax post working but not callback message in Android browser

im implementing sign up with ajax on my site its working perfectly on desktop but causing problem in Android Browser The problem is after i click on signup button in android browser it post data to database but do not replace the html message.And alert native code error.
function postdata(){
var chkfrm = checkdata();
if(chkfrm == 0){
var url = '<?php echo base_url();?>index.php/Signup/signin';
$.ajax({
type: "POST",
url: url,
data: $("#formI").serialize(), // serializes the form's elements.
beforeSend:function(){
$("#signupdiv").html('<h1>Loadinng...........</h1>');
},
success:function(data)
{
$("#signupdiv").html(data);
},
error:function () {
alert(console.log);
}
});
e.preventDefault();
}
else {
$("#msgjava").html('<p>We need a little bit information from you.Please fill it.</p>');
return false;
}
You can't do e.preventDefault(); where you are because e is not passed into this function (thus it is undefined). This will cause an error and stop JS execution.
In what you posted, you are also missing a closing brace at the end of the postdata() function.
Your alert says "native code" because that's what this line of code:
alert(console.log)
will do. console.log is a native function so alerting a native function won't do anything useful. You need to make that alert a lot more useful. To see in more detail what error is coming back from the ajax function, change your error handler to something like this:
error: function(jqXHR, textStatus, errorThrown) {
alert("status = " + textStatus + ", errorThrown = " + errorThrown);
}
And, then see what it says.

$.ajax not working first time

I have a button in html page.
<input type="image" src="images/login_button.png" id="imageButton" onclick="LoginButtonClick();" />
I am calling this method on button click:
LoginButtonClick = function() {
alert ("Button click event raised"); // this alert msg raising every time when onclick event occurs.
$.ajax({
alert ("Inside Ajax."); // This alert not executing first 1 or 2 times.
type: 'GET',
url: 'http://URL/Service.svc/LoginValidation',
dataType: 'json',
error: pmamml.ajaxError,
success: function(response, status, xhr) {
if (response != "") {
alert ("Response receive ");
}
else {
alert("Invalid Data.");
}
}
});
}
As I mentioned above $.ajax not working first 2 , 3 button click attempts.
In mozilla it throws an error "[Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: JQuery.js :: :: line 20" data: no]"
Is there any way to fix this issues..
I'm not sure why it is executing later. But here's the deal--you're placing the alert in the object literal that defines the parameters for the .ajax method. It doesn't belong there. Try putting the alert in your success and/or error handlers.
UPDATE
How long are you waiting? When you initiate an ajax request, it isn't going to hang the UI. It could be that you're seeing the result of the first click on your 3rd or 4th attempt and think that you're triggering it on that 3rd or 4th attempt.
The $.ajax() function receives as a parameter a set of key/value pairs that configure the Ajax request. I don't think that the syntax will be correct by placing the alert() in there.
Note - entering an absolute path isnt going to work if the domain is not the current one - it is against the Same Origin Policy that browsers adhere too - this might explain why nothing happens when its executed - i suggest you look in your browser debugger to verify.
You should be binding the click event like this :
$(document).ready(function() {
$('#imageButton').click(function() {
// code here
});
});
so your complete code will look like this :
HTML
<input type="image" src="images/login_button.png" id="imageButton" />
JavaScript
$(document).ready(function () {
$('#imageButton').click(function () {
alert("Button click event raised"); // this alert msg raising every time when onclick event occurs.
$.ajax({
type: 'GET',
url: 'http://URL/Service.svc/LoginValidation',
dataType: 'json',
error: pmamml.ajaxError,
success: function (response, status, xhr) {
if (response != "") {
alert("Response receive ");
} else {
alert("Invalid Data.");
}
}
});
});
});
I have removed the alert ("Inside Ajax."); line as this will not be executed - you pass an object {} of parameters not code to execute. If you want to execute before the ajax request is sent do this :
$.ajax({
beforeSend: function() {
alert('inside ajax');
}
// other options here
});
Docs for the $.ajax() function are here
I agree that you have the second alert in the wrong place, and dont know what pmamml.ajaxError function is but may be your call returns with error and therefore your success alerts are not firing. You can check with error and complete functions as follows:
LoginButtonClick = function() {
alert ("Button click event raised"); // this alert msg raising every time when onclick event occurs.
$.ajax({
type: 'GET',
url: 'http://URL/Service.svc/LoginValidation',
dataType: 'json',
error: function(jqXHR, textStatus, errorThrown){
alert ("ajax call returns error: " + errorThrown);
},
success: function(response, status, xhr) {
if (response != "") {
alert ("Response receive ");
}
else {
alert("Invalid Data.");
}
},
complete:function(jqXHR, textStatus){
alert('completed with either success or fail');
}
});
}
You can test with Google Chrome's Developer tools -> Network tab, if a request is made and returned (https://developers.google.com/chrome-developer-tools/docs/network)

Categories