0

this is my variable in setings.php

$error = output_errors($errors);

i want to echo out in my jQuery file 'settings.js'

   $('#save_settings').click(function(){

    var first_name = $('#first_name').val();
    var last_name = $('#last_name').val();
    var email = $('#email').val();

    $.post('settings.php', { first_name: first_name, last_name: last_name, email: email}, function(data){
        $('#show').html('settings saved').fadeIn(500).delay(2000).fadeOut(500);
        alert(data);
    });


});
  • 2
    So what's the problem? Simply echo it out from your page. Your ajax request will receive it as a response. – MD Sayem Ahmed Aug 31 '13 at 10:38
  • echo $error; in your php and you'll get it in your post ajax in success paramter – Deepanshu Goyal Aug 31 '13 at 10:40
  • sorry i dont undersand. like this. var error = ''; alert(error); –  Aug 31 '13 at 10:40
  • if you are wanting to get the response from settings.php you have to add in a callback function after your data variables list, http://api.jquery.com/jquery.post/ – Patrick Evans Aug 31 '13 at 10:42
  • possible duplicate of [Pass a PHP string to a Javascript variable (and escape newlines)](http://stackoverflow.com/questions/168214/pass-a-php-string-to-a-javascript-variable-and-escape-newlines) – putvande Aug 31 '13 at 10:43

4 Answers4

1

If you want to communicate between JavaScript and PHP, the best way is to create a hidden-inputfield in fill in the errors-variable. And then you can read out the value with jQuery.

The inputfield:

<input type="hidden" value="<?php echo $error; ?>" id="errors" />

And the jQuery-Code:

var errors = $("input#errors").val();
Mainz007
  • 533
  • 5
  • 16
0

You can't place PHP code inside "javascript" file, PHP code must be in PHP file. The below code can work if it's placed in .php file:

<html>
    <head>
        <title>javascript test</title>
        <script>
            var error = '<?php echo $error;?>';
            alert(error);
        </script>
    </head>
<body>
</body>
</html>
evilReiko
  • 19,501
  • 24
  • 86
  • 102
0

I am assuming that your $error will by different depending on the $_POST values. If your response header is in HTML, then you can do something like this.

// in your JS codes.
$.post('settings.php', function(response) {
  $('#show').html(response).fadeIn(500).delay(2000).fadeOut(500);
});

// in your php codes.
<?php if(isset($error)) { echo($error); } else { echo("setting saved"); }  die(); ?>
Patrick Thach
  • 138
  • 1
  • 1
  • 6
-1

Anything you want in your js from server side has to come as AJAX or JSON response. echo it from your php function and get it as AJAX or JSON in javascript.

$.getJSON('url for the php file', function(data){}

And in the php file just echo the value

see http://php.net/manual/en/function.json-encode.php

Or take a hidden input field and put the value there. You can get that value from js using the 'id' or 'class' attribute

rove101
  • 11
  • 2