I have built a custom registration form which creates a new WordPress user account and redirects the user to the /my-account/ area on completion. The issue I have is that I am not displaying any information on the front-end when the form is not submitted correctly i.e. the account creation process failed.
I am trying to log the AJAX response to console so I can see what I'm working with but it appears I'm not getting a response at all.
The code that I currently have in place:
<script>
jQuery('form[name="form-new-customer"]').on('submit', function() {
let form_data = jQuery(this).serializeArray();
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: form_data,
success: function(response) {
console.log(response);
window.location.replace('<?php echo get_site_url(); ?>/my-account/');
},
fail: function(err) {
console.log(err);
}
});
return false;
});
</script>
As you can see, I have a redirection for 'success' but this redirection also happens when the account user process fails. I'm assuming it's always a success because the AJAX request was carried out correctly and it's not able to know whether or not the PHP function ran or not?
I need to somehow get the User ID (if an account is created) and then check if it exists. This would determine if the function was successful or not. If not, then I can display a message to the end user?
Related
I'm new to this community and a beginner with programming. I'm trying to post a JSON data with AJAX to another PHP file and my code is as follow:
--- AJAX code ---
<?php session_start(); ?>
//other codes in between
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
//alert('Transaction completed by ' + details.payer.name.given_name);
alert(data.orderID);
// Call your server to save the transaction
return fetch('/paypal-transaction-complete', {
method: 'post',
body: JSON.stringify({
orderID: data.orderID
})
});
});
var orderid_data = data.orderID;
$.ajax({
url: "test_parse.php",
type: "POST",
data: {'order_ID': orderid_data },
success: function(data){
alert(data);
});
--- PHP code ---
var_export($_POST);
echo $_POST["order_ID"];
I've realised that my $_POST return an empty array.
Any help would be greatly appreciated :)
Since you open [...]test_parse.php directly in your browser, there is no POST-data present anymore, therefor its empty.
The POST-Data is part of the request. If you open it manually in the browser you perform a GET request.
What can you do to see the var_export?
You can use Chrome or Firefox for example both have Developer-Tools which allow you to trace the exact POST-Request you performed via ajax.
For Chome:
Hit F12 to open the Dev Tools
Navigate to Network
Now perform your Ajax-Post-Request and find it in the Network list. By clicking on the requests you will see all details you will need. Most Imporant for you is Response
I have a PHP File that get id and remove user.like this:
$user_id = $_GET["id"];
remove_user($user_id); //this function remove user by that id
i send data to this PHP file using JQuery.like this:
$.ajax({
url: "http://example.com/delete-user.php",
type: "GET",
dataType: "html",
data: "id=" + user_id,
success: function(data) {
location.reload();
},
error: function(error) {
console.log("Error:");
console.log(error);
}
});
But I know this has a security problem.
If user enter this link in address bar:
http://example.com/delete-user.php?id=10
delete-user.php File execute and this user(with id=4) will be deleted.
how i cant prevent this?
in other words how i can check User who sent the request, do it through the form?
You can use $_SESSION to check if the user submitting the id is logged in and if it is, check if that user has the permission to perform this action.
But without knowing how your system / application is working, there isn't much information we can provide to you.
I am using Laravel as a PHP framework and I have Jquery set up so it prompts the user if they want to confirm redirecting away from the page or not.
The problem is that if the user confirms the redirect away from the page, I need to somehow perform some database operations to set various statues to closed on my tables.
How is this possible?
My Jquery code prompting the user
<script type="text/javascript">
$(window).bind('beforeunload', function(){
return 'Are you sure you want to leave?';
});
Just make an Ajax request to inform the server that the user will be redirectd.
$(window).bind('beforeunload', function(e){
if ( confirm("Are you sure you want to leave?") ) {
e.preventDefault();
// make ajax request to inform the server
$.ajax({
type: "POST",
url: reqUrl,
data: reqBody,
dataType: "json",
success: function(data, textStatus) {
// handle things
}
});
// Redirect.
window.location.href = someURL;
}
});
Situation :
My web application is password protected.For each http request we make to server, it is being checked against session existence. If session has been expired then the user is forwarded to login page.
This goes fine for http requests. But if it is an AJAX request, then just like http request, if session has been expired, it is also forwarded to login page.
Problem :
if we are directly showing AJAX response in browser, then in place of our expected response will show the login page content in your browser.And if you would be fetching data of any expected format, then it would throw JavaScript error.
My Code :
<script>
function details() {
var xyz = document.getElementById("name").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name=' + xyz;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "user.php",
data: dataString,
cache: false,
success: function(html) {
document.getElementById("content").innerHTML=html;
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.status === 401) {
location.href = 'index.php';
}
}
});
return false;
}
</script>
on Session time out when i call Ajax request through my code. It loads the login.php content into the current page instead of forwarded the user to login Page.
Guide me where i am doing something wrong.
Thanks.
If your are working with multiple ajax request, then you can use jquery ajaxComplete function.
This function run every time after ajax call but before the success or failure function attached to that ajax event.
eg for this code is :
jQuery("body").ajaxComplete(
function(event, request, options) {
if (request.responseText == "login_required") {
window.location.href = "login.php";
}
}
);
And on your server side, you just have to check if the request is an ajax request and if user is not logged in, just print "login_required" and stop the execution of code(exit the code).
User will redirect to login.php page
I've got some data that will be used as part of an image gallery but I don't want to refresh the page between loading the data (there are interface items that I wish to stay visible). However when I submit the data to the same page via ajax JS registers a successful execution of the code (the alert box shows up) but PHP fails to harvest the data.
My JQuery looks like this
$(".gallery_thumbnail").click(function(){
var id=$(this).attr("data-id");
$.ajax({
type: "GET",
url: "test.php",
data: {newid:id},
dataType: 'text',
success:function(result){
// Test what is returned from the server
alert(result);
}
});
});
And my PHP looks like this\
if(isset($_GET['newid'])){
echo "success";
}
else{
echo "fail";
}
I've seen similar questions and tried copy and pasting the answers but I can't seem to get this to work. I've also tried for the url parameter:
http://localhost/test.php and simply removing the url parameter altogther.
Check if the request is ajax, then do the ajax processing
// this code should go before any of the web page code
if (isset($_GET['ajax'])){
if(isset($_GET['newid'])){
echo "success";
}
else{
echo "fail";
}
exit;
}
set a param to see if it is an ajax request
$.ajax({
type: "GET",
url: "test.php",
data: {newid:id, ajax: 'true'},
dataType: 'text',
success:function(result){
// Test what is returned from the server
alert(result);
}
});
I think the problem is that you're a little mixed up about what you're trying to accomplish here or how you should do it.
Try
if(isset($_GET['newid'])){
// Do whatever you want when the script gets an AJAX request
// You want to exit early to avoid having the whole page show up in the alert()
exit;
}
// Your normal, non-AJAX PHP code goes here
Note that your page is coming back in its entirety in the alert() because you aren't exiting early, which you probably want to do for an AJAX response. The way you have it setup, the whole page is sent back as if you're requesting it from a browser viewport.