The following code works perfectly in Chrome and Safari, but bonks in Firefox.
First the javascript:
$.ajax('/sn.php',{
type: 'POST',
dataType: 'json',
data: {...stuff},
complete: function(response){
console.log(response);
// do stuff with response...
}
});
and the php relay (on MY server) that uses cURL() to POST or GET from another domain:
// setup cURL...
$token = curl_exec($handle);
echo $token;
error_log('token='.$token);
$token shows up perfectly in the error_log, and everything works perfect in Chrome and Safari, but in Firefox the ajax status is "error" and the responseText is blank. Been banging my head against the wall for a couple days on this one.
Firefox doesn't have a native console.log like Webkit browsers do. Comment that out or replace it with alert() and I bet it works.
I might be barking up the wrong tree here, but I suspect it's the call to error_log in your php code. If you remove that, does it help?
Also, it might help to set an error handler on your .ajax request too, something like
$.ajax('/sn.php',{
type: 'POST',
dataType: 'json',
data: {...stuff},
complete: function(response){
console.log(response);
// do stuff with response...
},
error: function (jqXHR, textStatus, errorThrown){
console.dir(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
It won't fix the problem, but it'll at least give you some more debug output to look at
edit Couple more ideas from 249692. Is your webserver returning the correct mime type for the request? Can you try doing a beforeSend and setting overrideMimeType
Firefox was returning Status: 0 for the ajax request. Based on a heads up from this blog post I updated my form to onSubmit='return false;' and now it works perfect.
Related
I am currently learning the Laravel API, and have been developed a very simple API that retrieves data from the database by simply entering 127.0.0.1:8000/api/XXX to the browser, however, when I tried to use ajax call to get data from the exact same url, the ajax always showed that the HTTP request was failed, the ajax codes I used are following:
$.ajax({
url: "127.0.0.1:8000/api/XXX",
success: function(data) {
let response = JSON.parse(data);
displayResult(response, 1);
}
})
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
And this code always resulted in alert("error");, therefore I am wondering that maybe there are some Routes needed to be written in order to let the API properly processes HTTP request? I have already defined a route in routes\api.php:
Route::apiResource('XXX', 'XXXController');
PS: when entering the API URL to the browser, it worked fine, it went wrong when doing an ajax call with the API URL.
Edit
These are the errors I got from the browser console after I used function(jqXHR, textStatus, errorThrown) to catch the errors
DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL
at Object.send (https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js:2:79420)
at Function.ajax (https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js:2:77118)
at retrieveAllBooks (http://127.0.0.1:8000/js/api-query.js:25:5)
at HTMLInputElement.<anonymous> (http://127.0.0.1:8000/js/api-query.js:10:7)
at HTMLInputElement.dispatch (https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js:2:41772)
at HTMLInputElement.y.handle (https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js:2:39791)
I am not exactly sure why it is an invalid URL, since if I copy and paste this link to browser, nothing goes wrong...
(Posted on behalf of the question author).
Actually the solution is simple, just add http:// to the url.
I'm having problems with ajax responses on my live server which all appear to work on my local server.
I'm making the request as follows:
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
dataType: 'json',
success:function(data, textStatus, jqXHR)
{
console.log("ajax response:", data);
//DO SOME STUFF
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log("Error", errorThrown);
//if fails
}
});
In the live server I can see the response correctly in the network panel in Chrome and all looks ok. However console shows nothing at all and fails to act on the success. I can see no errors in console.
If I remove dataType: "json" I can see the messages in console but the data that should be displayed is poorly formatted as:
array() array() array('result': true)
I can't see where the additional arrays are coming from.
On my test server everything shows correctly in the browser and in console. With or without dataType
The response is coming from PHP created in laravel 4.2 on php 5.5. This is on https request rather than http. I don't know if that makes a difference?
My php is:
$formMessage = array(
'result' => true,
'title' => 'Thank you for your email',
'message' => '<p>Thank you for your Message. We will contact you shortly (during normal business hours) to respond to your enquiry.
</p>'
);
return Response::json($formMessage);
Are there any configurations in either php, jquery or laravel 4.2 that I'm missing that would affect this behaviour?
Text shown in chrome console for the response (being displayed by console.log())
ajax response: Array
(
)
Array
(
)
{"result":true,"title":"Thank you for your email","message":"<p>Thank you for your Message. We will contact you shortly (during normal business hours) to respond to your enquiry.<\/p><p>"}
This is with NO dataType
Thanks
In php i do echo json_encode($dump);
If echo it out using php i get {"load":"0.64 0.58 0.52 2\/361 12978\n","procs":"8\n"}
Than i make CORS Request using dataType:jsonp
$(function () {
$.ajax({
type: "POST",
ContentType: 'application/json; charset=utf-8',
url: 'http://labs.isaumya.com/loadtest/load',
dataType: "jsonp",
success: function (response) {
console.log(response.data);
},
error: function (xhr, status, error) {
console.log(error);
}
});
});
I get this error on the console:
DEMO
You are dealing with JSON, not JSONP. dataType: "jsonp", should be dataType: "json",
You can remove the data parameter entirely if your server outputs the correct content-type header for JSON (application/json).
JSONP is a hack to work around the Same Origin Policy from before CORS was designed and implemented by browsers. CORS is the modern approach to making cross origin requests. You use it instead of JSONP.
Both CORS and JSONP are technologies that must be supported by the server. http://labs.isaumya.com/loadtest/load doesn't appear to support either. You will have to modify the server if you want it to supply data in JSONP format or grant permission with CORS.
Unrelated to your actual problem:
You have no data parameter so you aren't sending JSON to to the server, remove the ContentType parameter. Since you aren't POSTing any data, you should probably be making a GET request, not a POST request.
Update IV / Current status: I've now confirmed trough another question that the character encoding of the file is fine and not the cause of the problem. I've also tested against another server and the error still persists. It does however work towards localhost.
So to summarize: JSONP call works towards localhost, but when running against external domains the response from the server is empty (no header / no http response code). When copying the requested URL and inserting it directly in a browser, the output is correct with correct formating (utf-8 / json).
Fiddle: http://jsfiddle.net/5SJvp/1/
Update III: I'm now able to get it working succesfully on localhost. However, using the exact same code (both client and server) towards my production domain it still fails. The response from the server is "empty" meaning to say it returns no http status code.
Update II: After some more debugging I noticed that the response does not include an http status code. This probably is the cause of my problem? I assume this means there is something wrong server side, but I cannot for the life of me see where.
Update I: Snip from jQuery where to request seems to halt.
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
Params (from Firebug)
_ 1356655864905
callback jQuery18308375673194150332_1356655863817
p 0522
pl 12
s false
secret ##############################
u request12341299
Request (from Firebug)
Accept text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language nb-no,nb;q=0.9,no-no;q=0.8,no;q=0.6,nn-no;q=0.5,nn;q=0.4,en-us;q=0.3,en;q=0.1
Connection keep-alive
Host localhost:8888
Referer http://localhost:8888/popup.html
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:17.0) Gecko/20100101 Firefox/17.0
X-Requested-With XMLHttpRequest
Original question:
I'm struggling with what seems to be a common problem, but I've yet to find a solution. I'm trying to execute a very simple jsonp call using jQuery. The problem is that either a) nothing is happening or b), the response from the server is empty.
I've tried several different approaches, using both the $.ajax method and the $.getJSON method. Both produce the same faulty result. Using the code below nothing happens: Using the Chrome debugger I can see that it simply stops its execution halffway trough the method. However using Wireshark I can see that the client performs the three way handshake and thusly prepars to send data, it just fails to do that.
If I remove the callback=? it does execute, however the response is malformed (or at least, I think so since I can only see a response marked with a red line in Firebug).
$.ajax({
url: "http://mydomain.com/asd.php", //"http://localhost:8888/index.php",
dataType: 'jsonp',
type: 'GET',
data: {p:p, u:u, s:symbols, pl:pl, secret:secret},
contentType: "application/json; charset=utf-8",
async: false,
success: function(data){
console.log("What " + data.test);
},
error: function(data){
console.log("failed for some reason");
}
});
Server code ($callback = $_GET["callback"]
<?php header('content-type: application/json; charset=utf-8');
.
.
.
$data = array
(
"message" => $message,
"status" => $statuscode,
"length" => strlen($message)
);
echo $callback . '('.json_encode($data) .')';
exit;
?>
Here is the server response with manually typed input.
funcName({"message":"!0b7(cb6Gv40","status":"OK","length":12})
It is hard to debug this without a jsfiddle/jsbin, so my best suggestion would be to try getting the request to work with fake, static data (just an empty JSON struct, {}, will do).
It seems that the problem might lie in how you are using json_encode, since you write that when you add the callback=? param the response looks mangled. The suggested test will let you diagnose better where the issue lies.
This will obviously NOT work if you did not set up your SSL certificates properly.
This works properly when I transform the https to http: http://jsfiddle.net/eysEe/
var u = "test";
var p = 1234;
var symbols = false;
var pl = 16;
var secret = "c68f39913f901f3ddf44c707357a7d70";
$.ajax({
url: "http://serve.pin2pass.com?index.php",
dataType: 'jsonp',
type: 'GET',
data: {
p: p,
u: u,
s: symbols,
pl: pl,
secret: secret
},
contentType: "application/json; charset=utf-8",
async: false,
success: function(data) {
$('#test').text(data.message);
},
error: function(data) {
$('#test').text("SDf");
}
});
You can tell if you have bad SSL installation when "https://serve.pin2pass.com?index.php" leads to a risky page. Maybe you never intended to put it in https mode ?
callback is the universal GET param for wrapper function name for the jsonp. When you use callback=? in jQuery request, jQuery will parse the ? into something else with a time stamp so it will be always be a unique value. The API server will wrap the json in this unique function name, and jQuery stores the name so it can use it to unwrap the response.
Some API's are not flexible and require their own specific name in which case you can use the jsonpCallback option in either $.ajax or set it globally in $.ajaxSetup
See $.ajax API docs: http://api.jquery.com/jQuery.ajax/
Starting from your code I've set it up locally and everything works as expected:
test.php :
<?php
$callback = $_GET["callback"];
$data = array
(
"message" => 'test',
"status" => 200,
"length" => strlen('test')
);
echo $callback . '('.json_encode($data) .')';
exit;
test.html :
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON("http://localhost/test.php?callback=?",
{
whatever: 1,},
function(data) {
alert("hmm");
});
});
</script>
</head>
<body>
</body>
</html>
Two things that could help you :
Not putting the callback=? in your call fails because the JSON returned from your server is not valid JSON (due to the parenthesis around your json data). $.getJSON will silently fail in this case. If you want to see the error, use $.ajax instead.
Your problem might come from the fact that you're apparently trying to use https here. In Chrome at least, making an AJAX request to an https URL with an invalid certificate (I assume your localhost or test domain doesn't have a valid certificate) just puts an error in the console. The browser never prompts with the "are you sure?" about the certificate.
Hope it helps
Hm, can you try using 'Fiddler' to debug the call? Perhaps that empty server response isn't that empty after all.
Or maybe your server has some strange security settings, and checks the REFERRER header to block out external calls?
If you can give a full url to your app I could test it for you =)
So, with the new fiddle it was much easier to work. This is a working sample of your call-
var u = "test";
var p = 1234;
var symbols = false;
var pl = 16;
var secret = "c68f39913f901f3ddf44c707357a7d70";
$.ajax({
url: "https://serve.pin2pass.com/index.php",
dataType: 'jsonp',
type: 'GET',
data: {
p: p,
u: u,
s: symbols,
pl: pl,
secret: secret
},
contentType: "application/json; charset=utf-8",
aync:true,
success: function(data) {
$('#test').text(data.message);
},
error: function(data) {
console.log("failed for some reason");
}
});
jsfiddle
I hope I am not missing something here. The only change I had to do is in the request url, from
https://serve.pin2pass.com?index.php
to
https://serve.pin2pass.com/index.php
Hope this solves it.
I have created Restful web service in jomsocial environment.
It's on the local machine.
When I test it using REST console it return's response.
local url formed is...
http://localhost:5454/kisan-06/index.php?option=com_api&format=raw&app=users&resource=login&key=dfd8a84f8cdce807ae1d30a838415ea37eaa075c
Problem:
When I call same using jQuery.ajax, always error callback function is getting called.
Ajax call is...
$.ajax({
type: "POST",
url: "http://localhost:5454/kisan-06/index.php?option=com_api&format=raw&app=users&resource=login&key=dfd8a84f8cdce807ae1d30a838415ea37eaa075c",
data: "{ username: 'sai.kiks2#gmail.com', password: '123456'}",
contentType: "application/json; charset=utf-8",
cache : false,
dataType: "json",
success: function(data) {
alert("in success");
},
error: function(jqXHR,error, errorThrown){
//alert("There was an error loggin in");
alert("responseXML ",jqXHR.responseXML);
alert("responseText: ",jqXHR.responseText);
alert("errorThrown: ",errorThrown);
}
});
I have a asp.net web service, which was returning response as...
<?xml version="1.0" encoding="utf-8"?>
<string>{"UserID":"180339206","LogInName":"Amol Chakane","IsValid":"True","UserRoleID":"1","IsPending":"0","IsOrganization":"False"}</string>
Response from jomsocial web service is...
["UserID : 475", "LogInName : kruti patil", "IsValid : True", "UserRoleID : 1", "IsPending : 0", "IsOrganization : False"]
I searched for this issue, but couldn't find solution.
Please help me in this.
Edit #1
Tried to get response in other format.
{
"UserID": "475",
"LogInName": "kruti patil",
"IsValid": "Yes",
"UserRoleID": "1",
"IsPending": "NO",
"IsOrganization": "No",
}
Still it's not working :(
Thanks
When you posted more information I think I found the/a reason for your trouble.
According this page the syntax of your json object is wrong. The linked page shows examples for the most common datatypes in Javascript. If you read the examples, take an eye of the position of quotation signs.
After lot of search finally I found solution to this issue. :)
Instead of localhost need to use 10.0.2.2 this network address
coz android emulator doesn't recognize localhost
refer this
Now at least success callback is called
ajax call is..
$.ajax({
type: "POST",
url: "http://10.0.2.2:5454/kisan-06/index.php?option=com_api&format=raw&app=users&resource=login&key=dfd8a84f8cdce807ae1d30a838415ea37eaa075c",
data: {username: 'sai.kiks2#gmail.com', password: '123456'},
success: function(data, textStatus, jqXHR) {
alert("in success");
},
error: function(jqXHR, textStatus, errorThrown){
alert("There was an error loggin in");
}
});
But now I am facing another problem...
How to access data returned in success callback?