Ajax signup issue [duplicate] - javascript

This question already has answers here:
The 3 different equals
(5 answers)
Closed 6 years ago.
I'm trying to correct a login/sign up issue i'm having, and having trouble. I've included a jsfiddle with the code, but im not sure what I'm missing.
https://jsfiddle.net/Zemanor/fuzrkw16/1/
I am consistently able to insert users into the correct db table on submit, but it gives the "You have already created an account!" alert and inserts the info, even if the account is not in the table pre-submit. I want to reject the account if there is one in the database, or accept it if it doesn't currently exist. How do I correct this problem? (php incl in jsfiddle)
//signup js
$(document).ready(function(){
var url="http://localhost/auth.php";
$("#signup").click(function(){
var fullname=$("#fullname").val();
var email=$("#email").val();
var password=$("#password").val();
var dataString="fullname="+fullname+"&email="+email+"&password="+password+"&signup=";
if($.trim(fullname).length>0 & $.trim(email).length>0 & $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: url,
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function(){ $("#signup").val('Connecting...');},
success: function(data){
if(data=="success")
{
alert("Thank you for registering with us! you can login now");
}
else if(data="exist")
{
alert("You already created an account!");
}
else if(data="failed")
{
alert("Something Went wrong");
}
}
});
}return false;
});

Use double == to compare
else if(data=="exist")
{
alert("You already created an account!");
}
else if(data=="failed")
Also use double && in if to check multiple and condition.
Check this for more detail : http://www.w3schools.com/js/js_comparisons.asp

Related

attempts to trigger "click" on enter not working [duplicate]

This question already has answers here:
How to prevent ENTER keypress to submit a web form?
(29 answers)
Closed 3 years ago.
I am trying to trigger my onclick of a button when i hit enter to make my site more user friendly. I have tried all of the below methods and all of them have the same error
this is my html (please note im using pug)
input#userInterests.form-control(type='text' placeholder='Interests' name='userInterests')
button#AddInterest.btn.btn-success.btn-block.btn-lg(type='button', onclick='add_interest()', value='interests') Update Interests
this is the posting function:
function add_interest() {
var interests = document.getElementById('userInterests').value;
interests = interests.split(" ");
interests.forEach(function (data) {
if (!validInterest(data))
{
swal(
'Error!',
`${data} is not a correctly formatted interest`,
'error'
)
return ;
}
});
interests.forEach(function (data) {
if (validInterest(data))
{
let form =
{
interest: data
}
$.ajax({
type: "POST",
url : '/user/account/addinterest',
data: JSON.stringify(form),
contentType: "application/json; charset=utf-8",
dataType: "json",
});
}
});
document.getElementById("interestsPara").innerHTML = "Updated your interests";
$('#userInterests').val('');
}
these are all the methods ive attempted and none of them work. please note i am obviously not doing all of these at the same time and uncommented each one one at a time for testing. I have tested all of these with and without $(document).ready
$(document).ready(function(){
$("#userInterests").keyup(function(event) {
if (event.keyCode === 13) {
$('#AddInterests').trigger("click");
$('#AddInterests').click(add_interest());
$("#AddInterests")[0].click();
$("#AddInterests").click();
setTimeout(function(){ $('#AddInterests').click()}, 100);
setTimeout(function(){ $('#AddInterests')[0].click()}, 100);
add_interest();
document.getElementById("AddInterests").onclick();
document.getElementById("AddInterests").onclick = add_interest();
$('#AddInterests').trigger('click');
$("#AddInterests")[0].click(add_interest());
}
})
});
This is my 'error'
Cannot POST /user/account
my function does work and posts correctly when i manually click the button
(this is a group project and some of this isnt mine so please dont flame me too hard and give constructive criticism)
Thank you #freedomn-m
The problem was the default form behaviour to submit on enter that i didnt realise existed. I set my form to onsubmit return false as follows and this worked
<form onsubmit="return false;">
as described by This Post
I tried to use event.preventDefault() but it did not work

Ajax POST no success nor error not DUPLICATE [duplicate]

This question already has answers here:
How to prevent buttons from submitting forms
(20 answers)
Closed 5 years ago.
Im experiencing a weird error in an ajax request. upon calling an alert in both error and succes, the alerts arent displayed. This implies that the ajax request isn't processed. But I have no clue whatsoever why this is the case. Code is below.
var bool;
function set(n, thread_id) {
bool = n;
// update_upvotes(thread_id);
}
function vote(thread_id) {
if (bool == 1) {
alert("begin ajax");
$.ajax({
type: "POST",
url: "../includes/thread_upvotes.inc.php",
data: {
thread_id: thread_id
},
succes: function(data) {
alert("data:"+data);
},
error: function() {
alert("hi, im broken");
}
});
} else {
$.ajax({
type: "POST",
url: "../includes/thread_downvotes.inc.php",
data: {
thread_id: thread_id
}
});
}
}
Here the form which calls the function
<iframe class="foo" name="foo" id="foo"></iframe>
<form class="voteform" target="foo" onsubmit="vote('.$thread_id.') & update_upvotes('.$thread_id.');">
<button onclick="set(1);" id="'.$thread_id.'1" name="upvote" type= "submit" class="vote right up" value="'.$thread_id.'"> '.$num_upvotes.' </button>
<button onclick="set(0);" id="'.$thread_id.'0" name="downvote" type= "submit" class="vote left down" value="'.$thread_id.'"> '.$num_downvotes.' </button>
</form>
Thanks in advance.
EDIT: This post has been marked as a duplicate, the answer provided by the person who marked this as a duplicate is not satisfactory. We removed the form out of our code and the ajax request is still not being processed...
It seems this url "../includes/thread_upvotes.inc.php", is wrong. Remove the dots

Detecting if a user has logged out (got no session) using php via JS, and if so - stopping the execution of the remainder of the JS function

I am trying to find a way to detect if a user has no session (which can happen in 2 ways - if the sessions expired OR if the user logged out in another browser window/tab) while running specific JS/jQuery functions.
If the user has no session, the function should stop executing at that point (return false).
I tried using AJAX like so:
function CheckForSession() {
var str="chksession=true";
jQuery.ajax({
type: "POST",
url: "chk_session.php",
data: str,
cache: false,
success: function(res){
if(res == "0") {
alert('Your session has been expired!');
}
}
});
}
chk_session.php is
require('includes/application_top.php');
$session_test = $_SESSION['customer_id'];
if($session_test == '') {
//session expired
echo "0";
} else {
//session not expired
echo "1";
}
Then I am calling that function inside:
jQuery('body').on('click','.cart_icon_div1.active.selected', function(){
CheckForSession();
//if the session doesn't exist, stop running this function, else continue to do more cool stuff
});
The problem is that I am unable to get this to work. Frankly, my js/jQuery skills are quite limited.
Any help is greatly appreciated.
Here's a callbacky version:
function CheckForSession(onLoggedIn, onLoginExpired) {
var str="chksession=true";
jQuery.ajax({
type: "POST",
url: "chk_session.php",
data: str,
cache: false,
success: function(res){
if(res == "0") {
onLoginExpired();
} else {
onLoggedIn();
}
}
});
}
jQuery('body').on('click','.cart_icon_div1.active.selected', function(){
CheckForSession(function() {
// Do any important session-required stuff here
},
function() {
alert('Your session has been expired!');
});
});
A couple things you could do:
Check login status on page load and have the status ready to go when the user clicks
pass a callback into CheckForSession which it runs when the server gives a response.
Personally I would go with option 1.

submit multiple forms using JQuery ajax [duplicate]

This question already has answers here:
jQuery Multiple Forms Submit
(2 answers)
Closed 8 years ago.
I have this code to submit 1 form on click.
$('#verify_id').click(function() {
var formData = new FormData($('form#verify_id_form')[0]);
$.ajax({
type: 'post',
url: '/public_transaction/verify_id',
data: formData,
async: false,
success: function (res) {
alert(res);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
But, I want to submit 2 more forms with this. How can I change data to submit multiple forms?
ID of other 2 forms are: #form1 and #form2. How can I modify this line?
var formData = new FormData($('form#verify_id_form')[0]);
EDIT
there is a option in ajax to do something like this...
var dataString = $("#filter-group1, #filter-group2").serialize();
(here 2 forms are getting submitted bu just 1 click)
But, I don't know how to achieve this in my case?
If you don't use "ajax:false" and submit all 3 forms, as $.ajax is asynchronous all the forms will be submitted in non-blocking way.
$('#verify_id').click(function() {
$.ajax({
//code for form 1
});
$.ajax({
//code for form 2
});
$.ajax({
//code for form 3
});
return false;
});

Ajax request is not working php [duplicate]

This question already has an answer here:
ajax request without data not working
(1 answer)
Closed 8 years ago.
I have asked this earlier but still I wasn't lucky to get it work. Simply I am trying to update profile picture with a default picture when Delete button is clicked and I am trying to use ajax to do this, however whenever I click on the button nothing happens and the picture is not updated. I have tested the php page by itself and it works nicely but the js isn't working so could someone spot what I am doing wrong here?
html
<button href="javascript:void(0);" onclick="delete;" class="btn btn-default delbutt">Delete</button>
js
function delete()
{
$.ajax({
type: "POST",
url: "test.php?action=delete",
cache: false,
success: function(response)
{
var $divs = $("<div>" + response + "</div>");
$("#phd").fadeOut('slow');
$(".suc_pic").fadeIn('slow').empty().append($divs.find("#msg"));
}
});
}
and here is the php lastly
$username = $_SESSION["userCakeUser"];
if(isset($_POST["action"]) && !empty($_POST["action"]) || isset($_GET["action"]) && !empty($_GET["action"]))
{
if(isset($_GET["action"]) == "delete")
{
$profile = 'default.jpg';
$pp = $db->prepare("update users set profile = ? where username = ?");
echo $db->error;
$pp->bind_param('ss', $profile, $username->username);
$pp->execute();
}
}
else {
echo "Something is wrong. Try again.";
}
POST queries are by default not cached in jQuery ajax (1), so you probably should just use the $.post helper instead. Also, querystring values are not parsed to the $_POST super-global, so your code as-is will always read null from $_POST["action"].
function delete(){
$.post(
"test.php",
{
action: 'delete'
},
success: function(response){
var $divs = $("<div>" + response + "</div>");
$("#phd").fadeOut('slow');
$(".suc_pic").fadeIn('slow').empty().append($divs.find("#msg"));
}
);
}
(1) As defined in the API reference:
Pages fetched with POST are never cached, so the cache and ifModified
options in jQuery.ajaxSetup() have no effect on these requests.
It is my understanding that jQuery AJAX requests should have a data: option in there somewhere. Also, I see you're using GET to make the request, but tell jQuery to use POST.
$.ajax({
type: "GET",
url: "test.php",
cache: false,
data : {
action : 'delete'
success : function(response)
{
etc...
I'm no jQuery expert, but I think that may be your problem. The only other thing I can think of is the success function isn't working properly. Check your F12 menu and post any warnings/errors so we can see it.

Categories

Resources