I'm trying to store my form data using ajax but it gives me error. I'm submitting form data in js file which calls another php file to perform insert operation. here is my code:
<button id="submit" class="btn btn-primary" type="submit" onclick="myFunction()" >Create an Account</button>
clicking on that button it calls the js file serve.js
function myFunction(){
var name = document.getElementById("firstName").value;
var lname = document.getElementById("lastName").value;
var mail = document.getElementById("email").value;
var password =document.getElementById("password").value;
var confpass= document.getElementById("passwordConfirmation").value;
// var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;
if(password != confpass)
{
alert ('password doesnot match!');
}
// var form_data = $('#edit_user').serialize();
var datastring= 'name1=' + name + 'name2=' + lname +'email='+mail+ 'pass='+password;
$.ajax({
url: "learnapi.php",
type: "get",
dataType: "json",
data: {type: "signup", datastring:datastring },
//type: should be same in server code, otherwise code will not run
ContentType: "application/json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (err) {
alert(JSON.stringify(err));
}
});
};
Through ajax request it perform insert operation learnapi.php
<?php
header('Access-Control-Allow-Origin: *');
mysql_connect("localhost","root","");
mysql_select_db("learnapp");
if(isset($_GET['type']))
{
$res = [];
if($_GET['type'] =="signup"){
$name = $_GET ['name1'];
$lname = $_GET['name2'];
$passW = $_GET['pass'];
// $passW1 = $_GET['Pass1'];
$mail = $_GET ['email'];
$query1 = "insert into signup(firstname,lastname,password,email) values('$name','$lname','$passW','$mail')";
$result1 = mysql_query($query1);
if($result1)
{
$res["flag"] = true;
$rest["message"] = "Data Inserted Successfully";
}
else
{
$res["flag"] = false;
$rest["message"] = "Oppes Errors";
}
}
else{
$res["flag"] = false;
$rest["message"] = "Invalid format";
}
echo json_encode($rest);
}
?>