How to debug ajax response? - console.log

I am at lost with ways to debug my Ajax callback. I'm trying to print the response from the php file to see if the call is working but without success. While the call works, the response seem to return empty... Nothing shows in the console but the response in Network tab is 200 OK and I can see the data in the response header. However not able to print it back to the console. console.log(response) should print the table but meh. What are alternative ways to debug this? Any suggestion is welcome.
js
$.ajax({
type: 'POST',
dataType : 'json',
url: 'queries/getsocial.php',
data:nvalues,
success: function(response)
{
console.log(response);//does not print in the console
}
});
So here's the proof I get that it is working server side

After a much needed 10 hour break into the night, I solved the issue with a much clearer mind. I removed the dataType row and it worked for me.
As silly as it may sound, the table in the PHP page was not in JSON format, so when jQuery tries to parse it as such, it fails.
Hope it helps for you. If not, check out more suggestions here.
Before
$.ajax({
type: 'POST',
dataType : 'json',
url: 'queries/getsocial.php',
data:nvalues,
success: function(response)
{
console.log(response);//does not print in the console
}
});
After (Works now)
$.ajax({
type: 'POST',
url: 'queries/getsocial.php',
data:nvalues,
success: function(response)
{
console.log(response);//yes prints in the console
}
});

Can you add a photo of the console? When something like that happens to me, I usually print something console.log(“Response: “+ response). At least if you see the text at least you can be sure your function is getting executed.

Related

What do I do with low Scores in reCAPTCHA v3?

I have set up reCAPTCHA v3 on my ASP.NET MVC project. Everything is working fine and is passing back data properly.
So the code below depends on another dll I have, but basically, the response is returned in the form of an object that shows everything that the JSON request passes back, as documented by https://developers.google.com/recaptcha/docs/v3
It all works.
But now that I know the response was successful, and I have a score, what do I do? What happens if the score is .3 or below? Some people recommend having v2 also set up for secondary validation (i.e. the 'choose all the stop signs in this picture' or 'type the word you see'). Is that really the only 'good' option?
Obviously the code isn't perfect yet. I'll probably handle the solution in the AJAX call rather than the controller, but still. What should I do if the score is low?
I read this article
reCaptcha v3 handle score callback
and it helped a little bit, but I'm still struggling to understand. I don't necessarily need code (although it would never hurt) but just suggestions on what to do.
VIEW:
<script src="https://www.google.com/recaptcha/api.js?render=#Session["reCAPTCHA"]"></script>
grecaptcha.ready(function () {
grecaptcha.execute('#Session["reCAPTCHA"]', { action: 'homepage' }).then(function (token) {
$.ajax({
type: "POST",
url: "Home/Method",
data: JSON.stringify({token: token }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log('Passed the token successfully');
},
failure: function (response) {
alert(response.d);
}
});
});
});
CONTROLLER:
[HttpPost]
public void ReCaptchaValidator(string token)
{
ReCaptcha reCaptcha = new ReCaptcha();
Models.ReCaptcha response = new Models.ReCaptcha();
response = reCaptcha.ValidateCaptcha(token);
//response returns JSON object including sucess and score
if (response.Success)
{
//WHAT DO I DO HERE????
}
}
Ended up getting the answer from another forum. Basically, the answer is "anything you want". There is no right or wrong when handing a successful response.
So what could be done, is if the response is successful and CAPTCHA doesn't throw a flag, do nothing. But if CAPTCHA is unhappy, you could display an alert or a banner that says 'could not process', or you could even add in CAPTCA version 2, which would make them do the picture test or the 'I am not a robot' checkbox, etc.

Rails Active Model Serializers conflict with Ajax?

When I use gem "active_model_serializers", my all Ajax can't work, my code like following:
$(document).on('change','#brand_id_dropdown', function () {
var request = "/beacons/find_beacon_uuid_given_brand_id?brand_id="
+ $('#brand_id_dropdown').val();
var aj = $.ajax({
url: request,
type: 'get',
data: $(this).serialize()
}).done(function (data) {
change_uuids(data);//modify the majors' dropdown
}).fail(function (data) {
console.log('AJAX request has FAILED');
});
});
I tried change to
data: { get_param: 'value' },
dataType: 'json'
still conflict, whenever I gem serializer and start rails server, all Ajax fail. how can I fix that?
I can't comment because I don't have enough rep. But you need to supply a little more information.
What's the failure message in the rails server logs? Check the rails server output and copy paste the errors into your question. Also, open your browser console and paste the "console" or "network" errors (in chrome: OPTION+CMD+I to show console). Lastly, throw a debugger; statement into your ajax call and play around with the variables.

Ajax call on ruby on rails

I have a ajax call using ruby on rails. I'm getting a success but I don't know how to use the data result of the ajax call.
$.ajax({
url: "/search/get_listing?listing_id" + id,
dataType: 'JSON',
success: function(data) {
var listing = JSON.parse(data);
$("#modalPrice").html(data.city);
}
});
Controller:
#listings_data = Listings.find_by(id: params[:id])
render :json => #listings_data.to_json
Using data.city won't work. I'm expecting to get the values retrieve from the model by simply putting . on the variable
var listing = JSON.parse(data);
Still no luck. Help guys. Thanks!
JSON.parse is Ruby code, API of JSON gem. How can you guys use that in Javascript :)
jQuery can process JSON object data directly. Just use:
success: function(data) {
$("#modalPrice").html(data.city);
}
For example, you can render in the controller:
render :json => { :city => #listings_data }
On the JS:
success: function(data) {
var listing = data.city;
}
I'm having similar problems everytime I use AJAX in rails since the response seems to differ depending on how you return the value or how you are handling the success in JS. Try this:
success: function(data, status, xhr) {
var listing = JSON.parse(xhr.responseText);
$("#modalPrice").html(data.city);
}
I usually use Firebug (Firefox Plugin) to set a breakpoint in my success handlers to check the arguments where exactly the response is in. Sometimes it's in the first value, sometimes in some other and then it may be xhr.response or even xhr.responseText. It's confusing me every time.
To use Firebug for this, press F12 on your page, select the 'Script' pane and find the code you want to check. Click next to the row number of your code where you want your breakpoint. In this case, you could've chosen the var listing line. When the code is executed (after your click), the browser will stop there and you can check the passed arguments on the right side.

ajax request in rails 2 not working

function ajaxRequest(){
$.ajax({
type: 'GET',
url: 'client/orders/send_mail_to_notaries',
data: { subject: "hi" }
});
return false;
}
It doesn't pass any params in controller.Can any one trigger this out?
Following the question that you have asked today morning page.replace_html method in rails 2 i guess you are using prototype.
Can you check if jQuery is included? Unless jQuery is included this ajax request will not work.
I just tried the method you're using and it worked for me. Perhaps there's a problem with the router/controller?
When debugging ajax it's very handy to use the Chrome developer toolbar. Bring it up, run the javascript and see what happens.
To see the response from the server you can then flip to the Network tab to see what the response is.

file_get_contents('YOUTUBE API') returns cached/non-updated/old information

https://gdata.youtube.com/feeds/api/users/EXAMPLE/uploads?v=2&alt=jsonc
When visiting this url direct from a browser, it will return the correct data 100% of the time. If a video has been added, it's there, if a video has been deleted, it's gone.
When getting this data through file_get_contents('https://gdata.youtube.com/feeds/api/users/EXAMPLE/uploads?v=2&alt=jsonc');
The data seems to be cached or not updated/current data...
If you continue refreshing the page, it will show/hide new videos, as well as show/hide deleted videos for about 5-10 minutes, then it will be accurate.
The same thing happens when I get data using $.getJSON(), or $.ajax()...
Shouldn't the data be the same as when visiting the url in the browser?
I'm simply trying to get the most recent video uploaded by a user "EXAMPLE".
public function ajaxUpdateVideoFeed()
{
header("Content-type: application/json");
$json = file_get_contents('https://gdata.youtube.com/feeds/api/users/EXAMPLE/uploads?v=2&alt=jsonc');
$data = json_decode($json, TRUE);
$videoId = $data['data']['items'][0]['id'];
echo json_encode($videoId);die();
}
Try appending a random number to the end of you url call. https://gdata.youtube.com/feeds/api/users/EXAMPLE/uploads?v=2&alt=jsonc&r=RAND where RAND would be some arbitrary randomly generated number each time the url is called. Not sure if this will work for you, but it may be worth a try.
I'm having a similar issue. I'm trying to retrieve current state of a specific video via $.ajax() call, and the response data appears to stay cached. If I try the url from a browser the data is updated.
$.ajax({
url: 'https://gdata.youtube.com/feeds/api/videos/YouTubeID?v=2&alt=json'
type: "post",
dataType: 'json',
cache: false,
success: function(response, textStatus, jqXHR){
var ytState = response.entry.app$control.yt$state.name;
},
error: function(jqXHR, textStatus, errorThrown){
console.log( "The following error occured: "+ textStatus + errorThrown );
},
complete: function(){
}
});
I have tried json, jsonp, cached=false, appending a time stamp, appending my developer key to url, and no success.
**EDIT
By using POST vs GET in my ajax request it seems to eliminate my similar caching issue.
EDIT EDIT
Nevermind, I suck. Using POST is producing a 400 error.

Resources