javascript getting failed after the ajax request is failing - javascript

I am trying to fetch data from local network IP. It works fine if I am in the local network. It fails when accessed from outside, which is understandable. But the jquery error block is not getting executed, it just breaks the code and the page is stuck forever. Here is the code:
var url = "http://10.0.0.1:8080/status";
$.ajax({
url: url,
dataType:"jsonp",
crossDomain: true,
data : {},
success: function(response){
var clientState = response.clientState;
$(".clientstate-input").val(clientState);
document.loginform.submit();
},
error: function(response){
console.error(response);
$(".clientstate-input").val("0");
document.loginform.submit();
}
});
Error:

Try converting it to use a Promise:
var url = "http://10.0.0.1:8080/status";
$.ajax({
url: url,
dataType:"jsonp",
crossDomain: true,
data : {}
})
.then(response => {
var clientState = response.clientState;
$(".clientstate-input").val(clientState);
document.loginform.submit();
})
.catch(response => {
console.error(response);
$(".clientstate-input").val("0");
document.loginform.submit();
});

The issue was because of using older version of jQuery. Updated the library and everything was working fine.

Related

Rails/AJAX Stringify Data Returning Undefined

I'm trying to POST a comment to a using AJAX in Rails (without using remote: true and am having difficulty understanding why my myJSON variable is returning as undefined, when data is returning as expected.
Here's my code:
function submitViaAjax() {
$("#new_comment_button").on("click", function (e) {
e.preventDefault();
url = $(this.form).attr('action')
data = {
'comment': {
'content': $("#comment_body").val()
}
};
var myJSON = JSON.stringify(data);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: url,
data: myJSON,
// headers: { 'Content-Type': 'application/json' },
success: function (response) {
var $ul = $("div.comments_section ul");
$ul.append(response)
}
}).done(function(response){
debugger
var $ul = $("div.comments_section ul");
$ul.append(response)
})
})
};
I can run var myJSON = JSON.stringify(data); in the browser console just fine, so I'm not sure why it's not doing anything in my code.
Any help would be appreciated.
I found out why I wasn't getting the response I expected. It's a jQuery function, but I was using JavaScript variable declaration to define myJSON.
In short, I need to remove var from var myJSON = JSON.stringify(data);
EDIT:
Implementing 'use strict'; within that function renders those variables undefined, which may mean that I was originally overwriting them - causing the 400 and/or 422 error.
EDIT 2:
I was getting the 422 error because my data object had a key of content when my param was looking for body.

Upload Image/File with Jquery ajax in Laravel 5.* error

This problem confused me. Why my code cannot run on the server (in local runs well). What is wrong with the uploaded code?
I did the first ajax setup for all ( my script )
$.ajaxSetup({
headers: { 'X-CSRF-Token' : tokenCsrf,
// 'Content-Type':'application/x-www-form-urlencoded; multipart/form-data; charset=UTF-8',
},
error: function(jqXHR, exception) {
var response = JSON.parse(jqXHR.responseText);
var message = '';
if(response.body){
message = (response.body.msg ? response.body.msg : response.body);
}else{
$.each(response, function (key, value) {
message += value[0] + '<br/>';
});
}
// scripts
},
beforeSend:function(){
// scripts
},
complete:function(){
// scripts
},
done:function(){
// scripts
}
});
and script ajax for uploading (cut)
var fd = new FormData($(this)[0]);
$.ajax({
url: url,
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
// scripts
}
});
so why in my bankend i use
dd($request->all()) // emtpy
if in my local work perfectly
UPDATE:
in my backend
public function myController(Request $request){
dd($request->all()); // <<--- empty ( nothing parameter from front)
}
in my case, why when submit form empty parameter, If in server, but work in local.
Solved
I got wrong config in PHP.ini

JSON is not loading from server

I have a JSON file which i want to load end it is working fine when I am trying to load that file locally from my hard drive.
function save(){
$.ajax({
type: "GET",
url: 'cameras.json',
dataType: "JSON",
async : false,
success: function(data) {
var output = data.result["0"].Address;
alert(output);
},
error: function(data) {
alert("Error")
}
});
}
When i want to get access to this JSON file from my server:
function save(){
$.ajax({
type: "GET",
url: 'http://192.168.0.21:8080/json.html?type=cameras',
dataType: "JSON",
async : false,
success: function(data) {
var output = data.result["0"].Address;
alert(output);
},
error: function(data) {
alert("Error")
}
});
}
It's not working and I am getting error script.
What can be issue with that ?
I had the same problem.
Unfortunately, I think that remote (i.e. away from localhost) ajax calls are forbidden - or something similar - for security reasons.
Depending on your purposes, you can resolve the problem with a 2-steps action:
You can call - via ajax - a local server class which loads the remote file via REST web service.I solved this way...

IE9 + IE10 AJAX Call not working

I'm getting reports that a website I developed is not functioning as it should in IE 9 and IE 10. The problem occurs when attempting to submit a form:
$("form[name='signIn']").submit(function(e) {
var formData = new FormData($(this)[0]);
e.preventDefault();
$( "#return_status_sign_in" ).empty();
$.ajax({
url: "<?= SITE_URL ?>account/login",
type: "POST",
data: formData,
async: false,
success: function (msg) {
$('#return_status_sign_in').append(msg);
},
cache: false,
contentType: false,
processData: false
});
});
The above submits the form via AJAX in all other browsers and works perfectly. However, in IE 9 and 10, the page refreshes and the POST data appears as get variables in the URL. How come is this happening? Could it be that e.preventDefault(); is not triggering? If so, what's the alternative to that?
As I stated in my comment, IE 9 uses the 'xdomainrequest' object to make cross domain requests and 'xmlhttprequest' for other requests. Below is a sample of code that I use to work around this issue. 'xdomainrequests' only send 'plain/text.' They cannot send JSON:
if ('XDomainRequest' in window && window.XDomainRequest !== null) {
var xdr = new XDomainRequest(),
data = JSON.stringify(jsonData);
xdr.open('POST', 'http://www.yourendpoint.com');
xdr.onload = function() {
// When data is recieved
};
// All of this below have to be present
xdr.onprogress = function() {};
xdr.ontimeout = function() {};
xdr.onerror = function() {};
// Send the request. If you do a post, this is how you send data
xdr.send(data);
} else {
$.ajax({
url: 'http://www.yourendpoint.com',
type: 'POST',
dataType: 'json',
data: {
// your data to send
},
cache: true
})
.done(function(data) {
// When done
})
.fail(function(data) {
// When fail
});
}

How to add local json file in jsfiddle?

How can I add a JSON file in jsfiddle? I have a JSON file but I am not able to attach it in jsfiddle. I can make a JSON object and use it, but is there any way to add an external JSON file to a fiddle?
Myjson.com provides api, which runs in Jsfiddle.net.
Custom my myjson:
// Loading JSON with CROS
var url = 'https://api.myjson.com/bins/3ko1q';
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('success');
console.log(data);
},
error: function (e) {
alert('error');
console.log(e);
}
});
Myjson GET Example:
// 1. Create valid uri via POST
// 2. GET using newly created uri
var obj = {
"key": "value",
"key2": "value2"
};
var data = JSON.stringify(obj);
$("#clickMe").click(function () {
$.ajax({
url: "https://api.myjson.com/bins",
type: "POST",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, jqXHR) {
// load created json
$.get(data.uri, function (data, textStatus, jqXHR) {
var json = JSON.stringify(data);
$("#data").val(json);
});
}
});
});
You can harness the power of Cross-Origin Resource Sharing (CORS) to achieve your task.
Basically how CORS works is that if the Access-Control-Allow-Orign header is set in the HTTP response, then the content loaded by AJAX can be used in our script regardless of the fact it is on the same domain or some other.
Now for your purpose, you can upload your local JSON file to Dropbox's Public folder and get a Public URL, that you can load by a simple AJAX call.
The AJAX call will succeed in this case because Dropbox sets the following value in the response Access-Control-Allow-Orign:* which means any domain can use the loaded content.
Jquery code will be something like this(you can even use pure JavaScript if you prefer ).
var url = 'https://dl.dropboxusercontent.com/u/94145612/example.json';
var myJsonData= {};
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('success');
console.log(data);
myJsonData= data;
},
error: function (e) {
alert('error');
console.log(e);
}
});
Example JSFiddle
Based on your comment, you want to use a pure JSON file as an external resource in a jsFiddle. You can't do this, because pure JSON is not JavaScript. Say you try to include http://example.com/foo.json as an external resource, and that file contains the following:
{"foo":"bar"}
This will result in Uncaught SyntaxError: Unexpected token :, because the JSON object is not valid JavaScript by itself.
But if you assign the JSON object to a variable, like so:
var foo = {"foo":"bar"};
then no problem.
Solution: use a modified version of your file to initialize a variable for use in the jsFiddle.

Categories

Resources