Don't wait for form submit redirect - form-submit

i'm trying to test an application using cypress. I have an odd scenario where i have an html form with an action tag, some fields in the form and then a button for submit it.
I'm filling out all the fields in the form and click the button for submission, but i'm getting this error:
I don't wanna wait for the response, cause in this odd case the response is redirecting for a page i don't have access and the test fails, i'm just want a check the form submission response by checking something simple, for instance the response status.
Any help will be welcome...
Thanks in advance..

Can you try the below cy.request() method. I don't know if there is any authorization needed for your request. Give a try as below and let me know.
it('Check response status', function () {
cy.request({
method: 'post',
url: 'url_here',
form: true,
headers: {
accept: "application/json",
},
}).then((response) => {
expect(response.status).to.eq(200);
})
})

Related

Making an ajax post request in Wordpress

I'm trying to submit a form via ajax and post to /wp-admin/admin-ajax.php but I am getting response code 400.
I am submitting the form as so:
$.ajax("/wp-admin/admin-ajax.php", {
type: 'post',
dataType: 'json',
data: form_data,
success : function(response) {
console.log('working', responseText)
},
error: function(err){
console.log('err', err)
}
});
On my Wordpress backend I simply have an action and my handler function:
function panacea_form_process() {
// do whatever you need in order to process the form.
return 'working';
}
add_action("wp_ajax_nopriv_panacea_form", "panacea_form_process");
I was following this guide - https://teamtreehouse.com/community/submitting-a-form-in-wordpress-using-ajax but have tried to simplify it for debugging purposes.
I tried having a nonce but believe I don't require it as that is only needed for users who are logged in?
Hitting a wall so any suggestions would be appreciated. Thanks.
EDIT:
Have added localize script:
wp_localize_script( "_main-sripts",
'theUniqueNameForYourJSObject',
array(
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( "randomstring" ),
)
);
Updated my ajax call with localized admin url and also action name etc
$.ajax(theUniqueNameForYourJSObject.admin_url, {
type: 'post',
dataType: 'json',
data: data : {action: "panacea_form", form_data : form_data, nonce: theUniqueNameForYourJSObject.nonce},
success : function(responseText, statusText, xhr, $form) {
console.log('working', responseText)
},
error: function(err){
console.log('err', err)
}
});
Updated my action to return using wp_send_json and to include the action for logged in users:
function panacea_form_process() {
// do whatever you need in order to process the form.
wp_send_json('working');
}
add_action("wp_ajax_nopriv_panacea_form", "panacea_form_process");
add_action("wp_ajax_panacea_form", "panacea_form_process");
I tried having a nonce but believe I don't require it as that is only
needed for users who are logged in?
Nonce - is required. Request will be more securely.
What about your form_data? This should be json or request string.
And
function panacea_form_process() {
// do whatever you need in order to process the form.
return 'working';
}
Must have an echo, not return. Use wp_send_json() for returning data. Or wp_send_json_success() for success results or enter link description here for failed.
Your specific problem probably comes from the fact that you're missing an action.
You're using add_action("wp_ajax_nopriv_panacea_form", "panacea_form_process"); but the wp_ajax_nopriv is for non privileged users. Or users that are not logged in to the website/wp-admin
Since you're developing the site you're probably logged and so AJAX calls that should work for both logged-in en non-logged-in users you need another action so change is to
add_action("wp_ajax_nopriv_panacea_form", "panacea_form_process");
add_action("wp_ajax_panacea_form", "panacea_form_process");
Other then that you should echo results from AJAX calls, returning doesn't work properly in this case. Ideally you'd use wp_send_json as well.
Tip:
You should localize your ajax URL from where you enqueue the script to ensure the call still works when wp-admin is renamed.

Laravel ajax login empty fields

I'm using Laravel 5.2 and its Auth scafolding.
I'm trying to make the default login form, to work with Ajax (without reloading page).
I'm using reqwest.js for ajax requests.
Here's my ajax code:
<script data-cfasync="false" type="text/javascript" src="{{asset('js/lib/reqwest.min.js')}}"></script>
<script type="text/javascript">
var thisForm = document.querySelector('#authLogin');
thisForm.addEventListener('submit', function(f){
f.preventDefault();
reqwest({
url: thisForm.getAttribute('action'),
method: thisForm.getAttribute('method'),
contentType: 'application/json',
headers: {
'X-CSRF-TOKEN': document.getElementById('csrf_meta').getAttribute('content')
},
data: '_token='+thisForm.elements._token.value+'&email=myemail#live.com&password=12345',
success:function (response){
}
});
});
</script>
It uses \vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php login() function to handle the login requests: https://i.gyazo.com/bfe6790934f711f4c1d35f6670c20caa.png
Here's the problem:
1) when I use the default normal login form /login (without ajax), $request->all() in the above class returns all the form fields that were submitted (great, this is perfect)
2) but when I submit the same form /login via an Ajax POST request, $request->all() returns empty array: https://i.gyazo.com/44e2fc6f438bba27a2baab9f7d3b38d6.png
Can anyone tell what I'm doing wrong here? I'm going insane and have no idea what may going wrong. I have searched everywhere for a solution, still nothing.
Thanks.
Sorry, I'm stupid, I figured out the reason it returns empty array.
In my ajax request I had contentType: 'application/json', but my form data was not in JSON format but string params format.

prevent redirection on submit to form

I have the following code I am using to submit my form to a processing script. the form gets submitted but I am getting redirected to the response html from the server. I want to stay on the same page and run the callback function inside success:
the response header is sending
location:http://url-I-am-Redirected-to-and-don't-want-to-be.html
I am working with third party and have no control over the server side code I am submitting to.
$('#go').click (function () {
$.ajax ( {
type: 'POST',
data: $('#newsletter form').serialize(),
url: $('#newsletter').attr('action'),
success: function(){
$('#image_container').hide (1000,
);
}
});
}
At the end of the click block add
return false

Ajax request error when changepage

guys. I have a juerymobile multi-page, and I have a button in #page-index, when click it, will send a ajax request to server, and changepage to #page-column, It run will in PC, but when i deploy the multi-page in phonegap, the button click can just run only twice, code is below:
function test()
{
$.mobile.changePage('#page_column');
$.ajax({
url: "http://192.168.168.120:8090/fcmobile/getTest",
dataType: "json"
}).done(function(data) {
alert(data.content);
});
}
I found if I remove $.mobile.changePage('#page_column');, the ajax request can be run well any times. but when I add the changePage code, it only can be run twice, in third time, ajax request can't even be send. Dose anybody know reason?
AJAX is made to be asynchronous, so no need to set async to false to get it working. Use events instead.
For example:
function test () {
$.ajax({
'url': "http://192.168.168.120:8090/fcmobile/getTest",
'dataType': 'json',
'success': function (json_data) {
$(document).trigger('test_json_data_loaded');
console.log(data);
}
});
}
$(document).on('test_json_data_loaded', function () {
$.mobile.changePage('#page_column');
});
When you set async to false, you're basically making it so that every time this AJAX request is made, the user will have to wait until all the data is fully loaded before the application/website can do/execute anything else...not good.

Redirect ajax post action to some other actioin

I am using ajax post action. In this action i have used HttpContext.User.Identity.Name to get the user id. Based on the user id i get some records related to that user id in database and return that values through json type.
Sometimes session got expired, in this case the HttpContext.User.Identity.Name value became empty. If it is empty or null it will throw the exception.
So I need to null or empty check the HttpContext.User.Identity.Name value, if it is null or empty i need to redirect it to login page.
But redirecting action not works inside the ajax post action. how to solve this problem?
i need to authorize the ajax post action. Can any one give solution for that?
Regards,
Karthik.
But redirecting action not works inside the ajax post action. how to solve this problem?
You could start by decorating your controller action with the [Authorize] attribute. This ensures that only authenticated users can access it and you are guaranteed that inside User.Identity.Name will never be null:
[Authorize]
public ActionResult SomeAction()
{
string username = User.Identity.Name; // this will never throw
...
return Json(...);
}
then take a look at the following blog post by Phil Haack. Inside its post Phil presents a nice plugin that allows you to configure ASP.NET to send 401 HTTP status code when an AJAX request to a protected action is made. So in your jQuery code you could very easily detect this condition and redirect:
$.ajax({
url: '/SomeAction',
type: 'POST',
statusCode: {
200: function (data) {
alert('200: Authenticated');
// Bind the JSON data to the UI
},
401: function (data) {
// the user is not authenticated => redirect him to the login page
window.location.href = '/login';
}
}
});
And of course to avoid writing this 401 condition in all your AJAX requests you could very easily use the global .ajaxError() handler to centralize this redirection logic for all your AJAX requests in case of 401 status code returned by the server:
$(document).ajaxError(function(e, jqxhr, settings, exception) {
if (jqxhr.status == 401) { // unauthorized
window.location.href = '/login';
}
});
and now your AJAX requests become pretty standard:
$.ajax({
url: '/SomeAction',
type: 'POST',
success: function(data) {
// do something with the data returned by the action
}
});

Resources