1

I am having a form which gets value from the user and stores it to the database. On submitting the form ,it calls the action.php file using ajax call.

e.preventDefault();

$.ajax({

    type: "POST",
    url: "action.php",
    data: senData,
    dataType: "JSON",

    success: function(data) {

        $("#name").val("");
        $('.msg').fadeIn(500);
        $('.msg').text("" + data.result + "");

    }

});

The values are stored in the database without any errors, but I want to display a notification to the user after submitting the form inside the msg div.

In my action.php file I have added a JSON Encode statement to return a message too.

$msg = 'Thanks Yo Yo';
echo json_encode(array("result" => $msg));

But it is not working i.e, when I submit the form, it stores the data to the database and the webpage refreshes itself without displaying any message inside the .msg div.

Am I doing something wrong and is there a better way to do it??

5
  • your page is not supposed to refresh. right ? Commented Aug 7, 2016 at 5:09
  • can you post your complete function, which is making a ajax call? Commented Aug 7, 2016 at 5:10
  • Please submit your HTML code as well Commented Aug 7, 2016 at 5:14
  • There is no problem with the HTML code or AJAX function, as the data get perfectly stored in the database. I just don't want the page to be refreshed and to display a return message from the PHP inside the msg div. Commented Aug 7, 2016 at 5:20
  • Have u tried adding alert(data) inside success in ajax call? Commented Aug 7, 2016 at 5:29

1 Answer 1

1

You need to parse the JSON when it is returned to your javascript.

// Parse the response to JSON
var res = JSON.Parse(data);
$('.msg').text(res.result);

Your code should look like this.

e.preventDefault();

$.ajax({
 type: "POST",
 url: "action.php",
 data: senData,
 dataType: "JSON",

 success: function(data) {
    var res = JSON.Parse(data);
    $("#name").val("");
    $('.msg').fadeIn(500).text(res.result);

 }

});
Sign up to request clarification or add additional context in comments.

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.