0

I have some button and on click JS for it:

<button id="trigger">Send</button>

and JS to invoke simple action

$('#trigger').on("click", function(event){ 
                    jQuery.ajax({
                        type: "POST",
                        url: 'functions.php',
                        dataType: 'json',
                        data: {functionname: 'add', arguments: [1, 2]},

                        success: function (obj, textstatus) {
                            alert('test success');
                        },
                        complete: function (obj, textstatus) {
                            alert('test complete');
                        }
                    });
                });

In above ajax I put functions.php with other simple function:

<?php

$message = "PHP Funtion Alert";
echo "<script type='text/javascript'>alert('$message');</script>";

?>

But, I got only alert invoked from alert('test complete'); How invoke alert from PHP file?

PS. this is only example. In PHP file will be some DB functions.

2
  • What exactly are you trying to do? Run the alert message spit out from the php file? If so, you should just echo some text, then through jQuery alert the message. Commented Aug 28, 2017 at 21:05
  • I try to run PHP functions from functions.php file, when I click on the button Commented Aug 28, 2017 at 21:12

1 Answer 1

1

You're expecting JSON, hence the

dataType: 'json',

Yet, you're returning a script tag?

echo "<script type='text/javascript'>alert('$message');</script>";

And that's an error. What you want is to return valid JSON

$message = array("message" => "PHP Funtion Alert");
echo json_encode($message);

Then catch in the ajax function

jQuery.ajax({
  type     : "POST",
  url      : 'functions.php',
  dataType : 'json',
  data     : {
    data : 'to be sent'
  }
}).done(function(data) {
  console.log(data.message);
}).fail(function() {
    console.log(arguments);
});
Sign up to request clarification or add additional context in comments.

8 Comments

can I use other dataType?
Also, I wound ommit the dataType: 'json'. Why? Because then you'll need to use JSON.parse();
then I got: test success, and then test complete. I didnt get PHP Funtion Alert
function respond($result){ header('Content-type:application/json;charset=utf-8'); exit(json_encode($result)); } use this php function to send an array JSON response back to the client.
I wouldn't leave out the dataType. It tells you what you expect back - and if you expect json, then it should be set to json. But the PHP header should be set to json, and use json_encode() and return an array - alert it in the success
|

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.