Hayush!
Been trying to transfer my Chrome extension to manifest 2. Everything is working except for one script which calls an ajax. I have a variable that contains a JSON content which needs to be transferred to the server.
function sendlist(list){
jsontext = JSON.stringify(list);
$.ajax({
url: amfurl + "user/listbookmarks/",
dataType: 'text json',
async: true,
type: 'POST',
processData: false,
data: {'folders': jsontext},
success: function(data){
$('#importing').css('display','none');
$('#importdone').css('display','block');
console.log(data);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
For some reason the ajax part is not executed at all. No error message was triggered, nor in the server error log.
All of the inline scripts and scripts in general were included in the popup.js. So it's probably not the issue.
Any thoughts?
Thanks!
The following code works perfectly on previous manifest
function importbookmarks(){
$('#formadd').css('display','none');
$('#importing').css('display','block');
_gaq.push(['_trackEvent', 'chromextension','importbookmarks', username]);
chrome.bookmarks.getTree(function(bookmarks) {
sendlist(bookmarks);
});
}
function sendlist(list){
jsontext = JSON.stringify(list);
$.ajax({
url: amfurl + "user/listbookmarks/",
dataType: 'text json',
async: true,
type: 'POST',
// processData: false,
data: {'folders': jsontext},
success: function(data){
$('#importing').css('display','none');
$('#importdone').css('display','block');
console.log(data);
}
});
}
The problem wasn't with the function. The button execution wasn't calling it correctly.
Here is the code I used to get the function to work in manifest 2
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("import-bookmarks").addEventListener("click", function () {
importbook();return;
});
Related
I have called ajax request in some interval of time. Now, if I pressed the back button after success ajax then, the browser displayed all of my HTML code instead of displaying HTML elements.
<script>
window.setInterval(function () {
$.ajax({
method: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '{{route('devices.index')}}',
dataType: 'json',
success: function (data) {
}
});
}, 1000);
</script>
if($request->ajax()){
foreach ($devices as $device){
$latestUpdate = Carbon::parse($device->updated_at);
$diff = Carbon::now()->diffInMinutes($latestUpdate);
if($diff > 2){
Device::where('id',$device->id)->update(['status'=>'3']);
}
}
return response()->json(['msg' => "successfully checked"]);
}
I had expected to render the HTML elements, but it displayed.
{
"msg": "successfully checked"
}
Same things happened when I send HTML in json.
if($request->ajax()){
$returnHtml = view('alerts.index', compact('threshold'))
->with('alerts', $alerts)->render();
return response()->json(['html' => $returnHtml, 'data' => $alerts]);
}
window.setInterval(function () {
$.ajax({
method: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '{{route('alerts.index')}}',
dataType: 'json',
success: function (data) {
var formatedhtml = $('<div>').html(data.html).find('table');
$('table').html(formatedhtml);
}
});
}, 5000);
In this case it display
Instead of returning as json return data as array:
Try something like this
return ['html' => $returnHtml, 'data' => $alerts];
There's nothing wrong with how you are receiving the data when you use return response()->json(['html' => $returnHtml, 'data' => $alerts]);
If you want to actually put the html that you received from your server into an element in your page, you will need to use Element.innerHTML (https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) so that the html will not be escaped by the browser.
window.setInterval(function () {
$.ajax({
method: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '{{route('devices.index')}}',
dataType: 'json',
success: function (data) {
// this is the table where you want to place the received table contents
var my_table=$('#my-table')
// we turn the data we received from the server into a jQuery object, then find the table we want data from
var received_table=$(data.html).find('table')
// switch out the table contents
my_table.html(received_table.html())
}
});
}, 1000);
EDIT: Since you are using jQuery, I changed the answer to fit.
When a user clicks 'buy now', I want the transaction to happen and the div to eventually be faded out and removed once being processed by the controller. Everything in the controller works as it should, but when I put the function in the success, it isn't called. However it works when the function is placed outside the success. Additionally, a window.alert() somehow works when there's a success.
Here is my script, everything works in regards to the controller etc
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('form.buy-product-form').on('submit', (function (e) {
e.preventDefault();
var product_id = $(this).attr("id");
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data: {'id': product_id},
dataType: 'json',
success: function () {
window.alert("THIS ALERT COMMAND WORKS BUT THE FUNCTION DOESN'T!");
$(this).closest('.product').fadeOut("normal", function() {
$(this).closest('.product').remove();
});
}
});
}));
});
Everything above in the controller works fine as well, here is what it returns:
return response()->json(['ok' => 'ok']);
You cannot use this under success function because this is out scope . Just change your code like below :
$('form.buy-product-form').on('submit', (function (e) {
e.preventDefault();
var product_id = $(this).attr("id");
var element=this;//getting current element click in variable
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data: {'id': product_id},
dataType: 'json',
success: function () {
window.alert("THIS ALERT COMMAND WORKS BUT THE FUNCTION DOESN'T!");
//passing variable
$(element).closest('.product').fadeOut("normal", function() {
$(element).closest('.product').remove();
});
}
});
}));
I try using different instructions to use a JSON API from a Wordpress-System in a HTML-Teamplate. Unfortunately I do not succeed. Does anyone have any idea how I can read the section "Content" of http://www.earnyour21.de/api/get_page/?id=1588?
blog: function () {
$.ajax({
url: 'http://www.earnyour21.de/api/get_page/?id=1588',
type: 'GET',
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
}
If the data structure of the JSON will always be the same, you can simply access the object directly using the objects name in JS.
blog: function(){
$.ajax({
url: 'http://www.earnyour21.de/api/get_page/?id=1588',
type: 'GET',
dataType: 'json',
success: function(data){
$('#content_test').append(data['page']['content']);
},
error: function(data){
$('#content_test').append(data['page']['content']);
}
});
}
Basically you need to use jquery to grab the div with an id of content_test and then append your data from the json. http://api.jquery.com/append/ and http://www.json.com/ for further reference.
Code below works fine in IE, but onsuccess(...) method is not getting called in Chrome. Does any one know the solution?
$(document).ready(
function (e) {
$.support.cors = true;
$.ajax({
dataType: "JSON",
type: "GET",
crossDomain: true,
url: "http://localhost:36730/home/GETaaa",
success: function (data) {
//console.log(data);
alert(data);
},
Error: function (xhr, error, message) {
alert(xhr);
}
});
}
)
I'm using jQuery 1.9.1 performing jsonp against the Etsy API. Below is a routine used to call into the API; it accepts a signed request (url), a jsonp callback name and an error handler.
call: function (signedOAuthRequest, callback, errorFn) {
$.ajax({
url: signedOAuthRequest,
type: "GET",
dataType: "jsonp",
jsonpCallback: callback,
jsonp: false,
crossDomain: true,
cache: true,
processData: false,
error: function (jqXHR, textStatus, errorThrown) {
if (errorFn != undefined) {
errorFn(jqXHR, textStatus, errorThrown);
}
}
});
Usage:
call("http://the.api/?signedrequest", "myCallback", myErrorHandler);
And it works. myCallback fires, the json object received looks good. Everything's fine.
Except...
Immediately after myCallback completes, the error handler runs. In the error handler, the status code is 200 and the error message is "parsererror". errorThrown.message is "myCallback was not called". Thing is, myCallback was definitely called and the json object passed to it was parsed just fine, so I don't get this at all.
Why is this error being thrown on an otherwise successful call?
Based on comments and what's in your question, this is how i would write that code:
function (signedOAuthRequest, callbackName, successFn, errorFn) {
$.ajax({
url: signedOAuthRequest,
type: "GET",
dataType: "jsonp",
jsonpCallback: callbackName,
jsonp: false,
cache: true,
success: successFn,
error: function (jqXHR, textStatus, errorThrown) {
if (typeof errorFn !== 'undefined') {
errorFn(jqXHR, textStatus, errorThrown);
}
}
});
}
I made the following changes:
Added an additional parameter to pass a success callback. This is required because jQuery will define the callback for you so that it can retrieve the successful response and parse it.
Removed crossdomain: true because it is redundant
Removed proccessData: false because it doesn't affect jsonp requests and you aren't passing any data
Added success: successFn so that jQuery will execute successFn on success with the parsed json data.
Renamed callback to callbackName so that it's more obvious about what it contains.
An alternate solution if you still insist on defining the callback yourself is to use the script dataType (taken from comments below)
$.ajax({
url: signedOAuthRequest,
dataType: "script",
cache: true
});