3

I am a student and am using jquery and php to add records to database. Records are being added, but i want to display a message "Record inserted" in the if the the record has been successfully been added and an error message if an error occurs.

This is my html code:

<form id="forn-newsletter" class="form-horizontal" method="POST">
<div class="form-group">
    <label id="name_label" class="control-label col-xs-2">Name</label>
    <div class="col-xs-10">
        <input type="text" class="form-control" id="news_name" name="news_name" placeholder="Name" onblur="checkName();"/><font color="red"  id="name_error"></font>
    </div>
</div>

<div class="form-group">
    <label id="email_label" class="control-label col-xs-2">Email</label>
    <div class="col-xs-10">
        <input type="text" class="form-control" id="news_email" name="news_email" placeholder="Email" onblur="vali()"/><font color="red"  id="email_error"></font>
    </div>
</div>

<div class="form-group">
    <div class="col-xs-offset-2 col-xs-10">
        <button id="register-newsletter" type="submit" class="btn btn-primary">Register for Newsletter</button>

    </div>
</div>

<div id="dialog"></div>
</form>

This is my registration-newsletter.php

<?php
include('connect.php');

$name=$_POST['name'];
$email=$_POST['email'];
$val=md5($name.$email);
$query = "INSERT INTO newsletter (Id,Name,Email,Val) VALUES('','$name','$email','$val')";


$result=mysql_query($query);
if(!$result){
    echo "Some error Occured..Please try later";
}
else{
    echo "Your details have been saved. Thank You ";
}

mysql_close($con);
?>

This is my JQuery code

$(document).ready(function(){
$("#register-newsletter").click(function(){
    var name=$("#news_name").val();
    var email=$("#news_email").val();

    var dataString="name="+name+"&email="+email;
    var request;
        request = $.ajax({
        url: "registration-newsletter.php",
        type: "POST",           
        data: dataString
        });

    //return false;
});

});
5
  • Read $.ajax() documentation and parse the response from PHP, then display respective error messages accordingly. Commented Sep 3, 2014 at 7:32
  • 2
    sidenote: use mysqli_* or PDO and use prepared statements instead, by the way, use the number of inserted rows instead, then send an boolean in a json_encoded return, then just use an if else on the success block Commented Sep 3, 2014 at 7:32
  • 1
    Prepared statements are not mandatory. Commented Sep 3, 2014 at 7:33
  • Also, <font> tag is deprecated long long time ago. Use CSS instead. Commented Sep 3, 2014 at 7:34
  • And you can probably combine the JS validation functions: vali() and checkName(); weird to have 1 JS function for 1 input field Commented Sep 3, 2014 at 7:37

5 Answers 5

3

Add a span to your html code for displaying error.

<span id="error"></span>

Already you are echoing the message from PHP page to ajax. You can do mysql_affected_rows() to check whether the query updated the table.

$result=mysql_query($query);
if(mysql_affected_rows()>0){    // return the number of records that are inserted
   echo "Your details have been saved. Thank You ";    // success
}
else{
    echo "Some error Occured..Please try later";   // failure
}
exit;

Then you can simply show the echoed message in the span with id error as:

request = $.ajax({
        url: "registration-newsletter.php",
        type: "POST",           
        data: dataString,
        success:function(response)     // response from requested PHP page
        {
           $('#error').html(response);  // set the message as html of span
        }
        });
Sign up to request clarification or add additional context in comments.

5 Comments

Shouldn't you throw the error and provide a handler for ajax 'error', rather than forcing all responses into a span marked as error?
Nothing is being displayed.
are you getting any response from the page. Put an alert after the success:function(response) {
I tried with an alert but the alert is not displayed
Was the query successful?
2
  $.ajax({
                url: 'registration-newsletter.php',
                 type: 'post',
                 data:  dataString ,
                 success: function (msg) {
                  alert(msg);
                },
                error:function(msg)
                {
                alert(msg);
                }

            });

1 Comment

where do you get ../PackAssetMap/GetSubcate ? Totally not related
1
jQuery.ajax({
    url: "myfile.php",
    type: "POST",           
    data: dataString,
    success:function(response)     /* this response is an array which is returning from the myfile.php */
    {
    $status = response['status'];
    if($status == 'success')
        {
        $('#message').html(response['msg']);
        }
    else 
        {
        $('#message').html(response['msg']);
        }
    }
    });

The function which you have added success will handle the "text to be append" or "alert to be show". Its quite equal to if condition, If the response came successfully, It will go into the condition.

Comments

1

This is what worked for me for form submit (see those 2 parameters to .then function):

<span id="result">Loading...</span>
<div id="form">
    <form>
        <input id="personId"> <-- put personID here<br>
        <input id="submit" type="submit" value="Generate">
    </form>
</div>

<script type="application/javascript">
    $(document).ready(function() {
        var submit = $('#submit');
        var res = $('#result');
        $('#form').submit(function() {
            submit.prop('disabled', true);
            res.text("Sending message...");

            $.ajax({
                url: '/rest/message',
                contentType: "application/json;charset=UTF-8",
                method: "POST",
                data: JSON.stringify({'personId': $('#personId').val()})
            }).then(function(result) { // OK
                res.text("Message was generated");
                submit.prop('disabled', false);
            }, function(reason) { // ERROR
                res.css('color', 'red').css('font-weight','Bold');
                res.text("An error has occurred: " + reason.responseJSON.message);
                submit.prop('disabled', false);
            });
            return false; // prevent default action
        });
    });
</script>

Comments

0
error: function(xhr) {
    alert(xhr.responseText);
}

You can also get the HTTP status code or the generic message sent by your server (such as "Internal Server Error") in this XHR object if needed. More info : https://api.jquery.com/jQuery.ajax/#jqXHR

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.