Irina Farcau Irina Farcau - 5 months ago 11
PHP Question

getting data using ajax php jquery

I made a submit form using php and ajax and don't get it why it doesn't work.

My code:

ex1.php

<form id="myForm">
<p> Firstname: <input type="text" name= "firstName"</p>
<p> Lastname<input type="text" name = "lastName" id="lastName"</p>
<p> Password: <input type="password" name= "password" id="myPass"> </p>
<p> Email: <input type="text" name="email" id="myEmail"></p>
<p> Age: <input type="text" name="age" id="myAge"> </p>

<input type="submit" value="submit" id="subm">
</form>

<script>

$(document).ready(function(){
$("#subm").click(function(){

var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var password = $("#myPass").val();
var email = $("#myEmail").val();
var age = $("#myAge").val();

var dataString = "Firstname: " + firstName + ", Lastname: " + lastName + ", Email: " + email + " , Password: " + password + "Age: " + age;

$.ajax({
type: "POST",
url: "ex1Ex.php",
data: dataString,
cache: false,
succes: function(result){
alert(result);
}
});
});
});


externFile:

<?php


$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$password = $_POST['password'];
$email = $_POST['email'];
$age = $_POST['age'];
echo 'jsjsjs';

?>


When I enter the values, after pressing the button, in console it appears

ex1?firstName=a&lastName=ww&password=111&email=a&age=11:59 POST http://local.healix/ex1Ex.php 500 (Internal Server Error)


The problem must be with the file ex1Ex.php, but I don't get it what.Any suggestions?

Answer

Change your jquery function like following.

$(document).ready(function () {

    $("#subm").click(function (event) {

        event.preventDefault();    

        var firstName = $("#firstName").val();
        var lastName = $("#lastName").val();
        var password = $("#myPass").val();
        var email = $("#myEmail").val();
        var age = $("#myAge").val();

        var dataString = "Firstname: " + firstName + ", Lastname: " + lastName + ", Email: " + email + " , Password: " + password + "Age: " + age;

        $.ajax({
            type: "POST",
            url: "ex1Ex.php",
            data: dataString,
            cache: false,
            success: function (result) {
                alert(result);
            }
        });
    });
});

I think you have to prevent the default php form submission using event.preventDefault();

Also, please correct the spelling mistake; you have written succes: instead of success: