1

I have a javascript function that takes information from a form and send it to my database. I would like to add a PHP Exception to it. Something like "if "whatever" execute the javascript function, else throw the Exception message". I'm kinda new to javascript and I don't know what is a good way to call a javascript function from a php file.

Here's the code:

index.php

<?php
/*
Template Name: X
*/
get_header(); ?>

<!DOCTYPE html>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>X</title>
    <script src="jquery-1.10.2.min.js"></script>

</head>

<body>

<div style="margin-top:30px;" align="center">

<form id="myForm" action="sendMessage.php" method="post">
<textarea style="resize:none" cols="80" rows="4" name="message" placeholder="Entrez votre message ici"></textarea><br />
<button   style="margin-top:2px; margin-bottom:10px;" id="sub">Envoyer</button>
</form> 

</div> 

<script src="sendMessage.js"></script>

<div id="output">
</div>

</body>  
</html>

<?php get_footer(); ?>

sendMessage.js

$("#sub").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(), 
function(info) { $("#result").html(info); } );
clearInput();
clickSub();     
});
$("#myForm").submit( function() {
    return false;   
});


function clickSub(){
$.ajax({
            url: "showMessage.php",
            type: "POST",
            async: true, 

            dataType: "html",

            success: function(data) {
                $('#output').html(data); 
            }
});
}

Basically what I'd like to do is to execute the javascript / ajax with a PHP condition.

Matt
  • 5,478
  • 9
  • 56
  • 95
abouletcouture
  • 71
  • 1
  • 1
  • 6
  • 6
    php can't execute javascript. javascript can't execute php. the only communication that happens between the two (in your case) is over http requests. You can have your php generate javascript code, then have your javascript execute it when it gets received, but it's generally better to instead return text data and parse it. – Kevin B Dec 12 '13 at 19:32
  • 2
    I think you are on the right path - cause you are trying to use AJAX. Depending on the response from the PHP Script - your script should return some kind of value - you can define what JS function should do. – mic4ael Dec 12 '13 at 19:34
  • 1
    To expand a bit on @KevinB's comment: PHP executes on the web server, and JavaScript executes on the client side (ie. in a web browser). So they are disconnected environments. – Asaph Dec 12 '13 at 19:34
  • The only place that javascript gets executed is at client side "for this case", and the only place that PHP gets executed is at the server, put that in mind while you write your code :) – Ma'moon Al-Akash Dec 12 '13 at 19:34
  • I think you've got a communication issue here when you talk about PHP and javascript interacting. PHP handles **requests** and sends **responses**. But this is possible. Javascript can look at the response from the server (it doesn't matter that it is PHP, or Ruby, or .NET, etc.) and act accordingly. – Matt Dec 12 '13 at 19:38
  • It sounds to me like what you're reaching for is almost a realtime kind of thing? If so, **yes, PHP can do this but it's not exactly the easiest way to achieve this.** (PHP can provide a socket server to the client, and listen for and handle events on said socket.) ALSO, it is technically inaccurate to say "PHP can't execute Javascript." In my experience, this is not a simple undertaking in PHP. You might be better served using server-side javascript (Node.js) for this. If changing tech stacks is not an option, however, http://socketo.me/ <- php sockets and eventing, and good luck. – OpenSorceress Dec 12 '13 at 19:52

2 Answers2

1

Aside from the weird phrasing on "execut[ing] javascript with PHP", this is pretty simple.

On the PHP side, showMessage.php should send back a non-2xx HTTP status code in the header. Like a 5xx error probably. Then the ajax handles the error or specific statusCode (see http://api.jquery.com/jQuery.ajax/).

In general, PHP should handle exceptions and report them as HTTP errors with the proper status code (similar to how you should send 404 with your route not found errors).

EDIT: And to clarify, you send headers in php with header(...). http://php.net/manual/en/function.header.php

Though you really should abstract this if you are not already using a framework that will abstract it for you. For example Symfony/Silex has controllers which return Response objects with HTTP status codes. The status is sent via the header, but this detail is abstracted out of the application business logic.

Matt
  • 5,478
  • 9
  • 56
  • 95
0

You can just generate you JS using php, and echo it in the HTML part , but remember JS is client side and PHP is server side, they both cant play with each other, although if you want to execute your JS on some HTML , you can echo with the html .

Eg:

   <?php 
    dynamic_code='
     $("#sub").click( function() {
     $.post( $("#myForm").attr("action"),
     $("#myForm :input").serializeArray(), 
     function(info) { $("#result").html(info); } );
     clearInput();
     clickSub();     
     });
     $("#myForm").submit( function() {
     return false;   
   });


      function clickSub(){
      $.ajax({
        url: "showMessage.php",
        type: "POST",
        async: true, 

        dataType: "html",

        success: function(data) {
            $("#output").html(data); 
        }
  });
   } '

 ?>

you can just echo this in your header section,

    <?php echo dynamic_code ?>
CleanX
  • 1,158
  • 3
  • 17
  • 25