How to echo ajax variable in php?

how to pass php variable to ajax url
how to get value from ajax response in php
ajax pass variable to php
send php variable to javascript ajax
pass jquery variable to php using ajax
ajax not passing data to php
jquery ajax call php function with parameters
how to get ajax value in php

I have some problem with ajax and php. I seen many themes for this but nothing helped for me.

I have page index.ph and there is variable in JS, i'm trying to send it to php with ajax and echo it with php in this page. This is my ajax request:

 var id = 5;
 $.ajax({
     type: "POST",
     url: 'post.php'
     data: {
         identify: id
     },
     error: function() {
         alert("Ошибка мой друг!");
     },
     success: function(data) {
         alert(id);

     }
 });

And this is post.php code:

if (isset($_POST['identify'])){ 
     echo $id = $_POST['identify'];
}

The ajax return succes, but php doesn't echo variable


you are getting success data in form data not in id, You return data not id which you are getting from post.php

var id = 5;
    $.ajax({
    type: "POST",
    url: 'post.php',
    data: {identify: id},
    error: function(){
        alert("Ошибка мой друг!");
    },
    success: function(data)
    {
        alert(data);

    }   
});

PHP ajax variable - PHP, I have sample file from the internet: index.html <!DOCTYPE html> <html lang="en​"> <head> <meta charset="utf-8"> <link  The problem I'm having is that AJAX does not recognize the PHP variables like JS: With JS I can simply say echo the json encoded variables (inside PHP tags) and done but I can't find how to make that work within AJAX.


Change your code:

var id = 5;
    $.ajax({
        url: "post.php",
        type: "POST",
        data: {"identify": id},
        success: function (data) {
            if (data) {
                alert(data);
            }
        }
    });

It should work.

How to send PHP variables to Ajax(Jquery)? - PHP, php if (isset($_POST['show'])) { $date = date("d/M/Y"); echo ' function replace() { var d = "'. $date. '"; document. getElementById("show"). 1. The PHP variable needs to be defined before the JS one. 2. The JS variable needs to be defined before you actually use it anywhere. This seems obvious, but if you forget this fact and try to put this declaration into the footer of your site and then use it in the content, you’ll find it doesn’t work!


Please refer to my other post

How do you echo a SQL SELECT statement from a PHP file called by AJAX?

That said, I just updated the code for it and put it on my GitHub you can find the source here

https://github.com/ArtisticPhoenix/MISC/blob/master/AjaxWrapper/AjaxWrapper.php

And Posted below

<?php
/**
 *
 * (c) 2016 ArtisticPhoenix
 *
 * For license information please view the LICENSE file included with this source code.
 *
 * Ajax Wrapper
 * 
 * @author ArtisticPhoenix
 * 
 * 
 * @example
 * 
 * <b>Javascript</b>
 * $.post(url, {}, function(data){
 * 
 *          if(data.error){
 *              alert(data.error);
 *              return;
 *          }else if(data.debug){          
 *              alert(data.debug);
 *          }
 *          
 * 
 * });
 * 
 *
 * <b>PHP</p>
 * //put into devlopment mode (so it will include debug data)
 * AjaxWrapper::setEnviroment(AjaxWrapper::ENV_DEVELOPMENT);
 * 
 * //wrap code in the Wrapper (wrap on wrap of it's the wrapper)
 * AjaxWrapper::respond(function(&$response){
 *     echo "hello World"
 *     Your code goes here
 *     $response['success'] = true;
 * });
 *
 */
class AjaxWrapper{

    /**
     * Development mode
     *
     * This is the least secure mode, but the one that
     * diplays the most information.
     *
     * @var string
     */
    const ENV_DEVELOPMENT = 'development';

    /**
     *
     * @var string
     */
    const ENV_PRODUCTION = 'production';

    /**
     * 
     * @var string
     */
    protected static $environment;

    /**
     * 
     * @param string $env
     */
    public static function setEnviroment($env){
        if(!defined(__CLASS__.'::ENV_'.strtoupper($env))){
            throw new Exception('Unknown enviroment please use one of the '.__CLASS__.'::ENV_* constants instead.');
        }
        static::environment = $env;
    }

    /**
     * 
     * @param closure $callback - a callback with your code in it
     * @param number $options - json_encode arg 2
     * @param number $depth - json_encode arg 3
     * @throws Exception
     * 
     * @example
     * 
     * 
     */
    public static function respond(Closure $callback, $options=0, $depth=32){
        $response = ['userdata' => [
              'debug' => false,
              'error' => false
        ]];

        ob_start();

         try{

             if(!is_callable($callback)){
                //I have better exception in mine, this is just more portable
                throw new Exception('Callback is not callable');
             }

             $callback($response);
         }catch(\Exception $e){
              //example 'Exception[code:401]'
             $response['error'] = get_class($e).'[code:'.$e->getCode().']';
            if(static::$environment == ENV_DEVELOPMENT){
            //prevents leaking data in production
                $response['error'] .= ' '.$e->getMessage();
                $response['error'] .= PHP_EOL.$e->getTraceAsString();
            }
         }

         $debug = '';
         for($i=0; $i < ob_get_level(); $i++){
             //clear any nested output buffers
             $debug .= ob_get_clean();
         }
         if(static::environment == static::ENV_DEVELOPMENT){
             //prevents leaking data in production
              $response['debug'] = $debug;
         }
         header('Content-Type: application/json');
         echo static::jsonEncode($response, $options, $depth);
   }

   /**
    * common Json wrapper to catch json encode errors
    * 
    * @param array $response
    * @param number $options
    * @param number $depth
    * @return string
    */
   public static function jsonEncode(array $response, $options=0, $depth=32){
       $json = json_encode($response, $options, $depth);
       if(JSON_ERROR_NONE !== json_last_error()){
           //debug is not passed in this case, because you cannot be sure that, that was not what caused the error.
           //Such as non-valid UTF-8 in the debug string, depth limit, etc...
           $json = json_encode(['userdata' => [
              'debug' => false,
              'error' => json_last_error_msg()
           ]],$options);
       }
       return $json;
   }

}

How you use it is like this (JavaScript)

$.post(url, {}, function(data){
   if(data.error){
          alert(data.error);
          return;
   }else if(data.debug){          
          alert(data.debug);
   }
});

PHP

require_once 'AjaxWrapper.php'; //or auto load it etc...

 //put into devlopment mode (so it will include debug data)
AjaxWrapper::setEnviroment(AjaxWrapper::ENV_DEVELOPMENT);

//wrap code in the Wrapper (wrap on wrap of it's the wrapper)
//note the &$response is required to pass by reference
//if there is an exception part way though this is needed to 
//return any output before a potential return could be called.
AjaxWrapper::respond(function(&$response){
    //this will be caught in output buffering and
    //returned as data.debug
    echo "hello World";  
    //...Your code goes here...

    //any return data should be an element in $response
    //call it anything but "error" or "debug" obviously

    $response['success'] = true;
    //this will be caught in the wrappers try/catch block and
    //returned in data.error
    throw new Exception();

     //&$response- for example if you were required to return
     //data to the caller (AjaxWrapper). If you did that here
     //after the above exception is called, it would never be 
     //returned, if we pass by reference we don't need to worry
     //about that as no return is required.
});

Of note this will also catch exceptions and turn them into data.error and it will also attempt to catch json_encode errors as well.

And yes it is pretty sweet. I go sick of re-writing all this code one day and created this at work, now I share it with you.

Php variable to javascript with AJAX?, Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java  You can display the value in a PHP variable on a web page by using any of the following statements: echo, print, print_r, or var_dump. Variables in echo and print statements You can display the value in a variable on a web page with an echo or print statement. For instance, if you set the …


Use data within the success function of ajax, That's where you get all echo, print from ajax request url.

On your ajax success

success: function(data) {
   alert(data); // before: "alert(id);" -> assuming you have a variable outside your ajax function, you can still use it.
}

Note*: success can even have more up to 3 arguments. The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function

Learn more about the use of other arguments of $.ajax success

PHP - AJAX and PHP, However, if you want to pass more than one parameter to echo(), using value of the string variable ($str) to the output: <?php $str = "Hello world!"; echo $str; ?>. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML.


PHP echo() Function, php page that has a array $a with various indices value set and its value can be queried by GET/POST method using AJAX request. It returns a json string with  how to access javascript variable with php using ajax Hi, I am trying to figure out how to access a javascript variable with php, in order to then store the variable in a database. This is what I've tried.


How to get variables from PHP through AJAX, 6. Conclusion. It better to pass an extra parameter with AJAX request to avoid any conflict with <form> variable if you are handling requests  How to Use AJAX to Pass Variables from PHP to JavaScript. This method passes the variable from JavaScript to PHP without reloading the page. This method is considered the best because server and client-side scripts are entirely separate.


How to handle AJAX request on the same page - PHP, jQuery AJAX Call to PHP Script with JSON Return <form action="return.php" class="js-ajax-php-json" method="post" echo json_encode($return);. } ?>. How JavaScript variable are retrieved from PHP script? And conversely, how to use the values of PHP variables in JavaScript? Using the content of forms in PHP. Name of elements of a form are also PHP variables as soon as the PHP script is the action of the form. Example, the complete form: "mytext" is the name given to the text input