Aayushi
Aayushi

Reputation: 1816

Ajax call to a php file is not working

I am trying to implement a simple form which will eventually connect to a database and make entries in it. In the tag,I am calling the php file which will connect me to the database in the back-end.

index.html

<html>
<head>
<script>
function submitForm(formId){

    //var formData= $.(formId).serialize();
    $.ajax({
        url:'new-user.php',
        type:'POST',
        data:{
            user_name=$("#user_name").val(),
            password=$("#password").val();
        }
        success:function(response){
            alert(response);
        }
    });
}
</script>
</head>

<body>
<form onsubmit="submitForm('#myForm');" id='myForm'>
User Name: <input type="text" name="user_name" id="user_name" />
Password: <input type="text" name="password" id="password" />
<input type="submit"/>
</form>
</body>

</html>

new-user.php

<?php include 'database.php';?>

<?php 
mysqli_query($connect,"create table login(User_name varchar(50) NOT NULL,Password varchar(50) NOT NULL)");
$user_name=$_POST['user_name'];
$password=$_POST['password'];
if(empty($user_name)){
    $name_error="name is required";
}

mysqli_query($connect,"Insert into login(User_name,Password) values('$user_name','$password')");
if(mysqli_affected_rows($connect)>0){
    echo "<p>Credentials added</p>";
    echo "<a href='index.html'>Go back</a>";
}else{
    echo "<p>Error</p>";
    echo mysqli_error($connect);
}
?>

database.php

<?php
$connect=mysqli_connect('localhost','root','','testdb');
if(mysqli_connect_errno($connect)){
    echo 'failed to connect';
}
?>

The above is not creating any table in the testdb database.Neither,it is generating any alert messages.The Url however changes after clicking the submit button as http://localhost/try2/?user_name=aayushi&password=ded but after that nothing happens. This is my first php code, so I don't really know what's the meaning of this exactly.

Upvotes: 0

Views: 1951

Answers (2)

user6137123
user6137123

Reputation:

Okay, since no one seems to actually be reading your code, there's a couple of syntax errors that I missed until I threw it into PhpStorm

Change your function to this:

function submitForm(formId){

    $.ajax({
        url:'/new-user.php',
        type:'POST',
        data:{
            user_name: $("#user_name").val(),
            password: $("#password").val()
        }
    })

        .complete(function (response) {
            alert(response)
        })

   return false; // Prevents the form from submitting the standard way
}

EDIT: Change the form to this:

<form onsubmit="return submitForm('#myForm');" id='myForm'>

Upvotes: 1

Christian Valentin
Christian Valentin

Reputation: 519

In your ajax method, the success property is wrong
It is written as suceess, when it was supposed to be success

Also, to avoid refreshing the page, insert return false; at the end of the function submitForm

Upvotes: 0

Related Questions