Redirecting after Ajax post - ajax

I want the success on ajax post to go to the home page. For some reason I keep doing it wrong. Any idea what I should do to fix this?
window.APP_ROOT_URL = "<%= root_url %>";
Ajax
$.ajax({ url: '#{addbank_bankaccts_path}',
type: 'POST',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', '#{form_authenticity_token}')},
dataType: "json",
data: 'some_uri=' + response.data.uri ,
success: function(APP_ROOT_URL) {
window.location.assign(APP_ROOT_URL);
}
});

success: function(response){
window.location.href = response.redirect;
}
Hope the above will help because I had the same problem

You can return the JSON from server with redirect status and redirect URL.
{"redirect":true,"redirect_url":"https://example.com/go/to/somewhere.html"}
And in your jQuery ajax handler
success: function (res) {
// check redirect
if (res.redirect) {
window.location.href = res.redirect_url;
}
}
Note you must set dataType: 'json' in ajax config. Hope this is helpful.

Not sure why, but window.location.href did not work for me. I ended up using window.location.replace instead, which actually worked.
$('#checkout').click(function (e) {
e.preventDefault();
$.ajax('/post/url', {
type: 'post',
dataType: 'json'
})
.done(function (data) {
if (data.cartCount === 0) {
alert('There are no items in cart to checkout');
}
else {
window.location.replace('/Checkout/AddressAndPayment');
}
});
});

Related

Variable loses some value when used in Ajax API Call

I have an issue that causes my variable “tempid” to lose some of its values when put into the second API call. As you can see from my image, if I log the variable to console (console.log(tempid)) it shows just fine. However, as soon as I place it in an API call it has some of the value but not all. Could you please help me by explaining why this would happen?
[console example][1]
$(document).ready(function() {
$.ajax({
url: "/api/Template/GetTemplates?classId=7ac62bd4-8fce-a150-3b40-16a39a61383d",
async:true,
dataType: 'json',
success: function(data) {
$(data).each(function (data) {
if (this.Name === "Name of Template"){
var tempid = this.Id
console.log (tempid)
var tempurl = "/api/V3/Projection/CreateProjectionByTemplate?id=" + tempid + "&createdById=703853d4-ffc4-fce3-3034-0b838d40c385"
$.ajax({
url: tempurl,
async: false,
dataType: 'json',
success: function(data) {
}
});
}
});
}
});
})
[1]: https://i.stack.imgur.com/gyesK.png
I found the answer, the console is just showing a shortened version of the URL and happened to cut off part of the tempid. Thank you

Detect successful response from ajax function

I have a function which is triggered via AJAX and will run the following when successful:
wp_send_json_success();
I am then doing a console log of the response and trying to detect if success = true:
.done(function (response) {
if( response['success'] == true ) {
console.log('add to cart successful');
} else {
console.log('add to cart failed');
}
Currently I am getting "add to cart failed" despite the output of response looking like it should be successful:
console.log(response);
// Response in the browser console:
{"success":true}
Am I detecting the true response incorrectly?
Update - PHP function the AJAX is triggering. Removed most code just as a test.
function fbpixel_add_to_cart_event_conversion_api() {
echo 'hello world';
wp_send_json_success();
die();
}
add_action('wp_ajax_fbpixel_add_to_cart_event_conversion_api', __NAMESPACE__.'\\fbpixel_add_to_cart_event_conversion_api');
add_action('wp_ajax_nopriv_fbpixel_add_to_cart_event_conversion_api', __NAMESPACE__.'\\fbpixel_add_to_cart_event_conversion_api');
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'fbpixel_add_to_cart_event_conversion_api',
product_id: productId,
variation_id: variationId,
},
})
.done(function (response) {
console.log(response);
console.log(productId);
console.log(variationId);
console.log(response.success);
if( response.success === true ) {
I always use dot notations to check the response returned from wp_send_json_success, and it always works. So use it like this:
if( response.success === true ) {
console.log('add to cart successful');
} else {
console.log('add to cart failed');
}
Give it a shot and let me know if you were able to get it to work!
I should have pasted the entire code sorry. I had the wrong dataType set within $.ajax:
Before
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'html',
})
After
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'json',
})

WordPress - Get server time using ajax and admin-ajax.php

I am new to using Ajax to get WordPress data.
The following code should return the server time but the response always is "400 Bad Request".
$.ajax({
url: obj + "?action=wps_get_time&format=U",
success: function(data) {
console.log(data);
}
});
Also tried it as POST and it was the same.
$.ajax({
url: obj,
method: "post",
data: { action: "wps_get_time", format: "U" },
success: function(data) {
console.log(data);
}
});
Any suggestions what's wrong please? Can't figure.
I always thought there are actions I can use always such as wps_get_time, without using a plugin. Am I wrong?
Ist there any easy way to get the server time by ajax?
Thank you all in advance.
The code below will return server time in Indochina and log it to console.
$.ajax({
type: 'GET',
cache: false,
url: location.href,
complete: function (req, textStatus) {
var dateString = req.getResponseHeader('Date');
if (dateString.indexOf('GMT') === -1) {
dateString += ' GMT';
}
var date = new Date(dateString);
console.log(date);
}
});```

Check Form Before Submit Use Ajax Django

I use Ajax to send data from form to server. But I want to check data in form before Submit by Ajax:
<form id='#id_form' onsubmit='return checkInputSubmit();' >
...
</form>
In Ajax:
$('#id_form').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: $('#id_form').serialize(), // serializes the form's elements.
success: function(data) {
if(data.result == true) {
//My code
}
else {
//My code
}
}
});
});
But checkInputSubmit() can't prevent submit from Ajax. You can explain for me and give me solution to check data in form before Submit by Ajax.
Thanks.
in the $('#id_form').submit(function(e) event, you can check/edit/return... any thing you want before call Ajax. Within Ajax, i think it won't work and don't good. (we just check ajax result, not input)
#Blurp, I found the solution by use your help.
$('#id_form').validate({
submitHandler: function(form) {
e.preventDefault();
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: $('#id_form').serialize(), // serializes the form's elements.
success: function(data) {
if(data.result == true) {
//My code
}
else {
//My code
}
}
});
}
});

MVC2: Ajax call runs always in error function. Why? Whats wrong?

aspx site:
<script type="text/javascript">
function AjaxTest() {
var codeVal = "hello world";
if (codeVal) {
$.ajax({
type: "POST",
url: "CheckAge",
data: { code: codeVal },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert("in ajax success");
},
error: function () {
alert("error");
}
});
}
}
Its double checked that the javascript function is called.
Controller:
[HttpPost]
public JsonResult CheckAge(String code)
{
return Json("abc");
}
It ended up always in the ajax - error - function.
The Controller function isnt called anyway. Why?
Why get I always an error?
What is wrong?
Check your url that you are posting to. It seems that you are missing the controller part. E.g. it should read /{controller}/{action}.
If that script is directly in the view (i.e. not in an external javascript file) you could have something like:
$.ajax({
type: "POST",
url: <%= Url.Action("CheckAge", "ControllerName") %>,
data: { code: codeVal },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert("in ajax success");
},
error: function () {
alert("error");
}
});
Also, I find it advantageous to use firebug to debug ajax stuff. You can set break points in your javascript and also see all the requests and responses.
HTHs,
Charles
EDIT: Try simplifying things... e.g.
$.post('<%= Url.Action("CheckAge", "ControllerName") %>',
{ code: codeVal },
function (data) {
alert("in ajax success");
},
"json");

Resources