Jquery ajax 'patch' doesn't seem to be sending data - javascript

I have the following javascript code...
function editShipment(){
var method = "PATCH";
var serializedData = $form.serialize();
$.ajax({
type: "PATCH",
url: Routing.generate('api_1_shipment_patch_shipment', {api_key: API_KEY, id:$('#caddress-shipmentID').val()}, true),
data: serializedData,
success: newShipmentSuccess,
error: newShipmentError
});
}
When I run this code the Chrome developer tools "network" tab shows a patch method with data being sent to the correct URL.
however my application never receives this data.
Is it possible that the network tab is somehow wrong and that my browser isn't actually sending the data.
I'm using the latest jQuery and the receiving application is a Symfony2 web app.
Thanks in advance,
M
EDIT: It also worth noting that i have a test case passing for this patch method within my symfony codebase. so thats why I'm looking at Javascript as the culprit.

Related

Wikipedia API. File not found Error

I'm trying to make a wikipedia search bar. The idea is to send a new AJAX request every time search input is changed. I'm using https://www.mediawiki.org/wiki/API:Search_and_discovery as a guideline.
var search = $('#search');
search.keyup(function() {
if (search.val() === '') {
result.html('');
}
$.ajax({
url: '//en.wikipedia.org/w/api.php',
data: {
action: 'query',
list: 'search',
format: 'json',
srsearch: search.val()
},
dataType: 'jsonp',
success: function(response) {
console.log("success!");
}
});
});
However, success function is not even triggered.
On any keypress the error I get is this ("d" pressed):
jquery-2.1.1.min.js:4 GET file://en.wikipedia.org/w/api.php?>callback=jQuery21107844703783826772_1484403407494&action=query&list=search&srse>arch=d&format=json&_=1484403407495 net::ERR_FILE_NOT_FOUND
Thank you in advance for any help or guidance!
Well, you're probably trying to do a AJAX request without a local server (opening your file directly in the browser).
First of all, your url options starts with //en... (without the protocol). It indicates that it'll construct your full url using the same protocol you're using. In this case: file://. That's because your browser is trying to reach file://en.wikipedia.org/....
So, you can set your url to https://en.wikipedia.org/w/api.php to make it work.
Just replace:
url: '//en.wikipedia.org/w/api.php',
with:
url: 'https://en.wikipedia.org/w/api.php',
Looks like you're running it from a simple html file located in your filesystem, in other words not running it from a web server (even local).
Try calling the api with
url: 'https://en.wikipedia.org/w/api.php'
or run the file from a web server (can be a local one).

Feeding webpage data via remote Web API

I'm trying to operate two servers.
MVC Web API service.
MVC Web application.
The idea is that the web application renders a page filled with javascript requests, which populate the actual data from the remote API service. The web application will never itself touch the database, or the API service (besides setting up authorisation tokens initially).
What is the best way to achieve this?
So far I've been using JQuery AJAX requests, attempting to use JSONP. However I always get "x was not called" exceptions.
$.ajax({
url: '#(ViewBag.API)api/customer',
type: 'get',
dataType: 'jsonp',
jsonp: false,
jsonpCallback: function (data) {
debugger;
// code to load to ko
},
error: function (xhr, status, error) {
alert(error.message);
}
});
Also the jsonpCallback function is called before the request is sent, so I assume its actually trying to call a function to generate a string? If I reform this request:
window.success = function (data) {
debugger;
// code to load to ko
};
... with jsonpCallback being "success", I still get the same error (but the success method is never called.
Any ideas? Thanks.
Edit: I've gotten started on the right course from this:
http://www.codeproject.com/Tips/631685/JSONP-in-ASP-NET-Web-API-Quick-Get-Started
Added the formatter, and replaced jsonCallback with success, like a normal ajax. However this only seems to work for get. I cannot delete or update. :(
Can you get it to work using the $.getJSON method?
$.getJSON( "ajax/test.json", function( data ) {
//handle response
});
Have you fired up developer tools in IE and watched the network traffic to see precisely what is being sent and returned?

Strange $.post() AJAX error when parsing JSON

I am facing this strange error in using $.post.
works
$("#add-video").click(function(){
var url = $("#new-video-url").val();
$('#loader').show();
$.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
alert(data);
$('#loader').hide();
});
});
The above piece of code, shows me the json array I am receiving using a php file, and also shows the title field here, and hides the loader image.
But when I alert(data.title), it shows me undefined. More over, when I add datatype 'json' to $.post,
doesn't work
$("#add-video").click(function(){
var url = $("#new-video-url").val();
$('#loader').show();
$.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
alert(data);
$('#loader').hide();
}, "json"); //Added datatype here.
});
This neither alerts anything nor does it hide the loader image. I also tried,
$("#add-video").click(function(){
var url = $("#new-video-url").val();
$('#loader').show();
$.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
jQuery.parseJSON(data);
alert(data.title);
$('#loader').hide();
});
});
The above one too neither alerts anything nor does it hide the loader. And then I tried this one too that did nothing.
$("#add-video").click(function(){
var url = $("#new-video-url").val();
$('#loader').show();
$.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
jQuery.parseJSON(data); //tried without this too.
alert(data['title']);
$('#loader').hide();
});
});
The strangest thing is that I have previously used json as I have shown in the 2nd script(out of 4), and that works normally. My JS console too doesn't show any errors or warning. What am I doing wrong here? How do I access the title field of data?
If this helps, here is how I send the json array,
$json = array("title" => $title, "embed" => $embed, "desc" => $desc, "duration" => $duration, "date" => $date);
print_r(json_encode($json));
I would really appreciate if someone can point out the error and tell me why my scripts are failing, similar functions worked in other js file.
here is my data, that is returned by server,
{"title":"Sunn Raha Hai Na Tu Aashiqui 2 Full Song With Lyrics |
Aditya Roy Kapur, Shraddha Kapoor","embed":"\r\t\t\t\t\t\r\t\t\t\t\t</param></param>\r\t\t\t\t\t</param>\r\t\t\t\t\t\r\t\t\t\t\t</embed></object>","desc":"Presenting
full song \"Sun Raha Hai Na Tu\" with lyrics from movie \"Aashiqui 2\"
produced by T-Series Films & Vishesh Films, starring Aditya Roy Kapur,
Shraddha Kapoor in voice of Ankit Tiwari. \n\nSong: SUNN RAHA
HAI\nSinger: ANKIT TIWARI\nMusic Director: ANKIT TIWARI\nAssistant Mix
Engineer - MICHAEL EDWIN PILLAI\nMixed and Mastered by ERIC PILLAI
(FUTURE SOUND OF BOMBAY)\nLyrics:SANDEEP NATH\nMovie: AASHIQUI
2\nProducer: BHUSHAN KUMAR KRISHAN KUAMR Producer: MUKESH BHATT
\nDirector: MOHIT SURI\nMusic Label: T-SERIES\n\nBuy from iTunes -
https://itunes.apple.com/in/album/aashiqui-2-original-motion/id630590910?ls=1\n\nEnjoy
& stay connected with us!! \n\nSUBSCRIBE T-Series channel for
unlimited entertainment\nhttp://www.youtube.com/tseries\n\nCircle
us on G+ \nhttp://www.google.com/+tseriesmusic\n\nLike us on
Facebook\nhttp://www.facebook.com/tseriesmusic\n\nFollow
us\nhttp://www.twitter.com/_Tseries","duration":"391","date":"2013-04-03"}
Edit
This worked suddenly.. :o
$("#add-video").click(function(){
var url = $("#new-video-url").val();
$('#loader').show();
$.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
alert(data.desc);
console.log(data.desc);
$("#loader").hide();
}, "json");
});
In comments, you mention that this AJAX corresponds to a YouTube API.
YouTube's blog announced in 2012 that they would support CORS, which uses server-side header flags that compatible browsers interpret as permitting requests that would otherwise be prohibited by browser security Same-Origin-Policy.
Assuming, as you say, the first example worked, the first issue was "Why did (a subsequent) alert(data.title) fail? (my edit) ". If you type alert(data.title) in the console, it will fail because the scope of data is the callback function where it is defined as a parameter, and in the global scope data is undefined. If you try to pass data back to the global scope somehow, it can still be undefined because $.post returns immediately, before the data has been fetched, and merely queues a request and sets the callback function you supply to handle the reply.
The second example, which explicitly sets the $.post dataType parameter to 'json', may fail with CORS based API because the mime types for json are not allowed to be sent up to the server as Content-Type: for a simple CORS request, and $.post will as far as I know only do simple requests without preflight. $.ajax can possibly do the more complex requests if correctly applied.
The work around to keep using $.post is not to use json as the expected data type, send requests up as form data, the server may send you back json anyway if that is what the API says will happen, which can be verified while testing the code.
From https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
Simple requests
A simple cross-site request is one that:
Only uses GET, HEAD or POST.
If POST is used to send data to the
server, the Content-Type of the data sent to the server with the HTTP
POST request is one of application/x-www-form-urlencoded,
multipart/form-data, or text/plain.
Notice that application/json did not make the list of what Content-Type is permissible in a simple CORS request.
See also A CORS POST request works from plain javascript, but why not with jQuery?
Use ajax as
$.ajax({
url:url,
type:'post',
dataType:'json',
success:callback
})
With this type you can set lots of parameter in low level.
With datatype attribute jQuery parses JSON and send data as callback function.
I think you have to replace all single \ with double '\' to feed it to JSON.parse.

Sinatra not recognising javascript for session

I'm trying to log into a Sinatra app with jQuery, but Sinatra is just not seeming to recognise it at all for some reason, here is my code to see if the user is logged in:
Sinatra app:
get '/logged_in' do
if session[:logged_in] == true
status 200
"OK"
else
status 200
"False"
end
end
When I browse to /logged_in in my browser, I see OK, but when I execute the following Javascript, I get False printed to the console - seems bizarre to me.
var r = $.ajax({
type: "GET",
url: "http://xxx-xxx.com/logged_in"
});
r.success(function(msg) {
console.log(msg);
});
Any insight would be appreicated!
It would be good if you could give more details. (Browser, chronological request log including HTTP status codes, or even a dump from wireshark.) However here is my guess:
var r = $.ajax({
cache: false,
type: "GET",
url: "/logged_in",
success: function(msg) {
console.log(msg);
}
});
Some browsers aggressively cache AJAX requests, in particular GET requests. So you may want to try cache: false. Adding the success function later also seems odd to me, I have never seen that in any code.
Edit: Is the server answering the AJAX request on the same domain? (The domain must be the same as in your browser test.) Usually it should not be necessary to specify the domain inside the URL, so I removed it in the code here. So after all it might be a problem due to the Same Origin Policy.
I would place my bet on this being a jQuery issue rather than a Sinatra issue. Check that the cookie is being sent for the ajax request. There are a number of reasons why the cookie is not getting sent.

Can not get json response using $.getJSON

I am currently developing a Ruby on rails 3 application.
My server controller function render a json object as response:
class DaysController < BaseController
...
def the_days
...
render :json => days
end
end
In my javascript,I use the following code to get json response from server( that's from the_day function in controller)
$.getJSON(
url,
{emp_id: emp_id},
function(data) {
var result = data.response;
alert(result)
alert(data)
},
"json"
);
I use firefox browswer and checked with Firebug, in Firebug Net->XHR, I see the Get request is successful, and the response "days" is there. That's both request and response are successful.
But I did not see the two alert window defined in the above $.getJSON function, why? Why I can not get the response "days" in $.getJSON function??
-----------------Edited------------------
I edited my code to this one:
$.ajax({
url: myURL,
type: 'GET',
data: {
emp_id: emp_id
},
dataType: "json",
success: function(data) {
alert("hi");
alert(data)
}
});
When I run this code, the browser is stuck at success: function(data)
If data is coming back null, but the response was otherwise successful, I'd say that you're sending the request in a manner that violates the Same Origin Policy.
The request needs to be sent to the same host/port/protocol that served the original page.
If this is only an issue in your development environment, you can test in Chrome by launching it from a Terminal application with --disable-web-security.
EDIT: Try changing the parameter name from data to something else, like dat or whatever.
Then try an alert:
alert( dat );
I've heard of some browsers having trouble with the data parameter when you utilize the data property of an AJAX call.
I'm guessing that the problem is that data does not have a response property. Try alerting just the data variable. It should be the days object itself.
I wish I could just leave a comment but I guess I don't have access to that yet.
Anyway, I'd start with something even more basic. Add some text alerts just to make sure you're actually making it to where you think you are. ie...
$.getJSON(
url,
{emp_id: emp_id},
function(data) {
alert('hi') // add this
var result = data.response;
alert('bye') // add maybe even this
alert(result)
alert(data)
},
"json"
);
Sometimes when I'm debugging I find that even my most basic assumptions are wrong.
Edit: here's some sample code from working code I recently implemented
$.ajax({
url: 'users/check_username',
type: 'GET',
data: {
username: username
},
dataType: "json",
success: function(user_exists) {
alert(user_exists) // CHANGE THIS PART
}
});
It sounds like you are not sending the correct header in your ruby application. Firebug should report the response Content Type as application/json because that is what jquery is expecting it to be.
You could try changing the datatype in your ajax call to html to see if your alerts work with that, but that doesn't really help with the json parsing.
ALL, finally, I figured out the root cause. The reason is simply because of "Invalid json data" returned in server. That's in rails controller function 'def the_days':
render :json => days
should be modified to
render :json => days.to_json
Then, everything works smoothly:) Thank you all anyhow!

Categories

Resources