chrome popup extension not sending data on the api.php file - ajax

I am using chrome popup extension but no data is sent to the php file named api.php.I have searched on stackoverflow and found ajax related content but nothing is working.here is my popover.js file which uses ajax.I used $_POST['data'] to grab the data in api.php file
var api_url = "https://localhost/psol/api.php";
window.onload = function () {
$("#checkout_btn").click(function () {
chrome.runtime.sendMessage({
'btnClicked': true
}, function () {});
});
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
console.log(request);
if (request.message === "show-loading") {
$(".psol-button").addClass('hide');
$(".psol-loader").removeClass("hide");
}
if (request.message === "hide-loading") {
$(".psol-button").removeClass('hide');
$(".psol-loader").addClass("hide");
}
if (request.message === "post-cart") {
console.log(request.data);
alert(JSON.stringify(request.data));
chrome.runtime.sendMessage({
'postCartDone': true,
'redirectTo': api_url
}, function () {});
$.ajax({
url: api_url,
type: "POST",
data: request.data,
// data:{name:'uzair'},
success: function (result) {
// alert("all done");
console.log(1, result);
}
}).done(function (result) {
console.log(2, result);
if (result.cartCount === 0) {
alert('There are no items in cart to checkout');
}else {
alert("this is also redirect");
}
});
}
});
};

Related

Laravel and AJAX 401 Unauthorised

How do i get my code so that if the 401 error appears with my AJAX button click code, then it either throws an error message when the button is clicked and says "you need to log in" or it redirects the user to login? at the moment it just throws the error in the dev console so a user has no idea on why the button isnt working.
Ajax js:
$('.visit').on('click', function (event) {
event.preventDefault();
// Make the button a variable here
var buttonToChange = $(this);
$.ajax({
method: 'POST',
url: urlVisit,
data: {
place_id: $(event.target).data("id"),
_token: token
},
success: function(){
// Change the button here
if(buttonToChange.hasClass('btn-visited')){
buttonToChange.addClass('btn-not-visited');
buttonToChange.removeClass('btn-visited');
buttonToChange.html('Not Visited');
//Count will go down
}
else{
// Do the opposite
buttonToChange.addClass('btn-visited');
buttonToChange.removeClass('btn-not-visited');
buttonToChange.html('Visited');
//count will go up
}
},
});
You could try the statusCode part of jQuery AJAX.
$('.visit').on('click', function (event) {
event.preventDefault();
// Make the button a variable here
var buttonToChange = $(this);
$.ajax({
method: 'POST',
url: urlVisit,
data: {
place_id: $(event.target).data("id"),
_token: token
},
statusCode: {
401: function() {
alert( "Not authenticated" );
}
}
success: function(){
// Change the button here
if(buttonToChange.hasClass('btn-visited')){
buttonToChange.addClass('btn-not-visited');
buttonToChange.removeClass('btn-visited');
buttonToChange.html('Not Visited');
//Count will go down
}
else{
// Do the opposite
buttonToChange.addClass('btn-visited');
buttonToChange.removeClass('btn-not-visited');
buttonToChange.html('Visited');
//count will go up
}
},
});
simple example
you can test this code by inspect in browser:
welcome.blade.php :
<script>
var urlVisit="{{route('route_test')}}"
var token = "{{csrf_token()}}"
$.ajax({
method: 'POST',
url: urlVisit,
data: {
place_id: 1,
_token: token
},
success: function (response) {
alert('ok')
},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.status == 419)
{
alert(xhr.responseText) // text of error
// do something
}
else if(xhr.status == 401)
{
// do something
}
}
});
</script>
web.php (route) :
use Illuminate\Http\Request;
Route::get('/', function () {
return view('welcome');
});
Route::post('test', function (Request $request) {
$place_id= $request->get('place_id');
return ('yes');
})->name('route_test');

Ajax call to Webmethod, cross domain

I have two Asp projects. On close of a dialog box in project A I am trying to call a static webmethod in project B using ajax call.
Instead of calling the Webmethod it is calling the PageLoad.
Any ideas what I am doing wrong?
WebMethod
[WebMethod]
public static string UpdateSession()
{
return "Test";
}
$(function () {
$('div#DialogDiv').on('dialogclose', function (event) {
CloseDialog("http://localhost:1330/Application_Default.aspx/UpdateSession");
return false;
});
});
function CloseDialog(URL) {
jQuery.support.cors = true;
$.ajax({
type: "GET",
url: URL,
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (response) {
alert("success");
},
failure: function (response) {
alert("Failed to trying to find the method: " + URL );
}
});
return false;
}
Try this with pure javascript
function CloseDialog(URL) {
var request = new XMLHttpRequest();
request.open("GET", URL);
request.onload = function() {
if (request.status === 200) {
alert(request.responseText);
// to convert to JSON object-> JSON.parse(request.responseText);
} else {
alert("Failed to trying to find the method: " + URL );
}
};
request.send();
return false;
}
With jQuery I would just do this, you don't need more. It should work with cross-domain too.
function CloseDialog(URL) {
$.ajax({
url: URL,
success: function (response) {
jQuery.each(result.list, function(i, val) {
// iterate the JSON object
// val.node;
});
},
failure: function (response) {
alert("Failed to trying to find the method: " + URL );
}
});
return false;
}

Common beforeSend in Ajax call and abort if conditions not satisfied

I am trying to write a common functionality to all Ajax call as below.
The abort is not working when I write it separately like below,it works if I add the beforesend in the same ajax as below, which is commented
$(document).ready(function () {
$.ajax({
beforeSend: function (jqXHR, settings) {
check = TestCallMethod();
if (check.responseText != "true") {
alert("Call Failed");
jqXHR.abort(event);
}
}
});
$.ajax({
// beforeSend: function (jqXHR, settings) {
// debugger;
// check = TestCallMethod();
// if (check.responseText != "true") {
// alert("Call Failed");
// jqXHR.abort();
// }
// },
cache: false,
url: '#Url.Action("TestCall2", "Home")',
success: function (data) {
alert(data);
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
function TestCallMethod()
{
return $.ajax({
url: '#Url.Action("TestCall", "Home")',
async: false,
cache: false,
success: function (data) {
return data;
},
error: function (request, status, error) {
alert(request.responseText);
return false;
}
});
}
How to achieve the abort for common ajax beforsend?
You can apply common settings to global on Ajax . I hope it would be helpful.
$.ajaxSetup({
global: true,
beforeSend: function (jqXHR, settings) {
check = TestCallMethod();
if (check.responseText != "true") {
alert("Call Failed");
jqXHR.abort(event);
}
}
});

show ajax-loader.png on a MVC3 form submit in a Jquerymobile application

I have a mobile application with MVC3 and Jquerymobile. At form submission (with ajax function) I want to display loading icon (ajax-loader.png) while submit and redirect.
Thanks!
my ajax function:
$("#add").click(function () {
$.validator.unobtrusive.parse($('form')); //added
if ($("form").valid()) {
var IDs = new Array($("#SelectedProduct").val(), $("#SelectedAccount").val(), $("#SelectedProject").val(), $("#SelectedTask").val(), $("#date").val(), $("#duration").val());
$.ajax({
url: '#Url.Action("SaveLine", "AddLine")',
type: 'post',
data: { ids: IDs },
dataType: 'json',
traditional: true,
success: function (data) {
if (data.success == true) {
$("#ajaxPostMessage").html(data.Success);
$("#ajaxPostMessage").addClass('ajaxMessage').slideDown(function () {
window.location.href = '#Url.Action("Index", "AddLine")';
}).delay(1800)
}
else {
$("#ajaxPostMessage").html(data.Error);
$("#ajaxPostMessage").addClass('ajaxMessage');
$("#ajaxPostMessage").show();
}
}
});
}
return false;
});
I would do something like this:
Ajax = {
Submit: function() {
Ajax.Loading();
//ajax stuff
//Ajax.Message('form complete, blah blah');
},
Loading: function() {
$('#ajax').html('ajax-loader.png');
},
Message: function(msg) [
$('#ajax').html(msg);
}
}

Ajax Form Submit

the form is submiting as normal request instead of Ajax.
$(document).ready(function () {
StatusComments();
});
function StatusComments() {
$('.comment').submit(function () {
$(this).ajaxSubmit(options);
return false;
});
var options = {
beforeSubmit: showRequest,
success: showResponse,
resetForm: true
};
function showRequest(formData, jqForm, options) {
var textbox = $('#StatusMessageReplyMessage').val();
alert(textbox);
}
function showResponse(responseText, statusText, xhr, $form) {
}
}
i have a similar one for Status update like this
function StatusUpdates() {
$('#updateStatus').submit(function () {
$(this).ajaxSubmit(options);
return false; // prevent a new request
});
var options = {
target: '.user-status',
// target element(s) to be updated with server response
beforeSubmit: showRequest,
// pre-submit callback
success: showResponse,
// post-submit callback
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
function showRequest(formData, jqForm, options) {
var textbox = $('#StatusMessageMessage').val();
if ((textbox == '') || (textbox == "What have you been eating ?")) {
alert('Please Enter Something and click submit.');
return false;
} else {
$('#StatusMessageMessage').attr('disabled', true);
}
}
function showResponse(responseText, statusText, xhr, $form) {
$('#StatusMessageMessage').attr('disabled', false);
$('.share').slideUp("fast");
$('#StatusMessageMessage').animate({
"height": "18px"
}, "fast");
}
}
Instead of
$('.comment').submit(function () {
$(this).ajaxSubmit(options);
return false;
});
Try
$('.comment').click(function(e) {
e.preventDefault();
$(this).ajaxSubmit(options);
return false;
});

Resources