OtagoHarbour
OtagoHarbour

Reputation: 4183

Trying to call PHP file using jQuery Ajax

I am developing using jQuery 2.0.2 on Debian 7.0.0.

I am trying to call a PHP script from a JavaScript file using jQuery.ajax. My code is as follows.

    jQuery.ajax({
    type: "POST",
    url: "DisplayParameters.php",
    data: { LUT:lut, 
        Brightness: brightness,
        Gamma: gamma,
        Background: background}
    }).done(function( result ) {
    $("#msg").html( " Ajax called" );
    });  

At the beginning of DisplayParameters.php, I have the following.

?>
<script language="JavaScript">
alert('DisplayParameters');
</script>
<?php

but the alert box is not called. Firebug proceeds without any errors and shows the DisplayParameters.php text (with a +/- control to collapse and expand it). But the alert box is not called. I cannot get any feedback from DisplayParameters.php to trace what is happening.

What would be the best way for me to get feedback (like alert boxes or console.log) from DisplayParameters.php?

Upvotes: 0

Views: 3554

Answers (2)

kevinandrada
kevinandrada

Reputation: 499

The alert() should happen inside .done() on the ajax call. Like the following:

.done(function(result) {
    alert(result);
    $("#msg").html( " Ajax called" );
}); 

And instead of alerting on DisplayParameters.php, use echo so that that will be the returned value for result. Like the following:

<script language="JavaScript">
    //...some JS codes here
    <?php echo 'DisplayParameters'; ?>
</script>

Upvotes: 1

Ast Derek
Ast Derek

Reputation: 2729

Your ajax call returns the contents of DisplayParameters.php as text, console.log(result) would show:

<script language="JavaScript">
alert('DisplayParameters');
</script>

If you want to add this extra code to the page (which I don't recommend unless you are sure you won't break the current page), you can try:

jQuery.ajax({
    type: "POST",
    url: "DisplayParameters.php",
    data: { LUT:lut, 
        Brightness: brightness,
        Gamma: gamma,
        Background: background}
}).done(function( result ){
    $("#msg").html( " Ajax called" );
    $("body").append(result);
});

Another approach would be to serialize (JSON) the information you need, set the dataType: "json" option, and act based on this information.

If you will send HTML, ensure your PHP code doesn't shows any error or warning messages.

Upvotes: 2

Related Questions