jQuery $ .post无法处理特定条件

I'm trying to insert some data into mySQL database using AJAX and jQuery $.post. My attempt to test the functionality is as follows

index.html: code fragment (already using jQuery for many other functions)

$.post( 
    "updateDatabase.php",
    { name: "Zara" },
    function(data) {
         //$('#stage').html(data);
         alert('Success');
    }
);

updateDatabase.php

<?php
if( $_REQUEST["name"] ) {

   $name = $_REQUEST['name'];
   echo "Welcome ". $name;
   echo "<script>alert('Im here')</script>";
}
?>

What I'm getting is an alert with "Success" and nothing else(It is the callback function of $.post). I already researched a lot and found some similar but different questions. However my problem left unsolved because there is no satisfactory solution for this particular issue.

You are echoing a string echo "alert('Im here')";. so,

  1. It can't be treated as a javascript function.
  2. You are not using the response in the success callback.

What you can do is:

function(data) {
     alert('Success: '+data);
     // outputs: Success: Welcome Zara I'm here
}

and at php:

echo "Welcome ". $name . " I'm here";

Change this

echo "alert('Im here')";

to

echo "Im here";// no need of alert.

function(data) {
     alert(data);
           ^// will alert Im here
}

You can also use

.done(function() {
    alert("Success");
})

Final code

$.post( "example.php", function() {
   alert( "success" );
})
.done(function() {
    alert( "second success" );
})

Try this safe way using a json as a return data

$.post( 
    "updateDatabase.php",
    { name: "Zara" },
    function(data) {//data is all the echoed text from the updateDatabase.php in our case a json string
         alert(data.message);
    }
);

<?php
if( $_REQUEST["name"] ) {

   $name = $_REQUEST['name'];
   echo json_encode([message =>"Welcome ". $name])

}
?>