У меня проблемы с ajax и php. Я видел много тем для этого, но мне ничего не помогло.
У меня есть страница index.ph, и в JS есть переменная, я пытаюсь отправить ее на php с помощью ajax и повторить ее с помощью php на этой странице. Это мой запрос ajax:
var id = 5;
$.ajax({
type: "POST",
url: 'post.php'
data: {
identify: id
},
error: function() {
alert("Ошибка мой друг!");
},
success: function(data) {
alert(id);
}
});
А это код post.php:
if (isset($_POST['identify'])){
echo $id = $_POST['identify'];
}
Возврат ajax успешен, но php не отображает переменную
Тот же принцип, я ответил на этот вопрос и не хочу его повторять. Кроме того, я предоставил там убойный код



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Измените свой код:
var id = 5;
$.ajax({
url: "post.php",
type: "POST",
data: {"identify": id},
success: function (data) {
if (data) {
alert(data);
}
}
});
Он должен работать.
Получил свою ошибку в функции успеха ajax, вы получаете ответ в данных, и вы написали: alert (id) только что написал: alert (data); а также измените строку: data: {"identify": id},
Рагбендра Наяк, в моем php-файле у меня есть: if (isset ($ _ POST ['identify'])) {echo $ id = $ _POST ['identify']; } echo "хорошо"; Когда я изменяю свой код, как вы его написали, предупреждение JS показывает мне: 5good. Но php не повторяет этого
Пожалуйста, обновите свой код здесь, чтобы я мог проверить, где вам что-то не хватает
Я думаю, что если вы получили предупреждение 5good, значит, ваш код работает нормально.
Используйте data в функции успеха ajax. Вот откуда вы получаете все echo, print из URL-адреса запроса ajax.
На вашем ajax success
success: function(data) {
alert(data); // before: "alert(id);" -> assuming you have a variable outside your ajax function, you can still use it.
}
Примечание*: успех может иметь до 3 аргументов. Данные, возвращаемые сервером, отформатированные в соответствии с параметром dataType или функцией обратного вызова dataFilter.
Узнайте больше об использовании других аргументов $.ajaxуспех
Пожалуйста, обратитесь к моему другому сообщению
Как выполнить эхо-запрос SQL SELECT из файла PHP, вызываемого AJAX?
Тем не менее, я только что обновил код для него и поместил его на свой GitHub, вы можете найти здесь исходный код.
https://github.com/ArtisticPhoenix/MISC/blob/master/AjaxWrapper/AjaxWrapper.php
И размещено ниже
<?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;
}
}
Как вы это используете (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.
});
Следует отметить, что это также перехватит exceptions и превратит их в data.error, а также попытается отловить ошибки json_encode.
И да, это довольно мило. Однажды мне надоело переписывать весь этот код и создавать его на работе, теперь я поделюсь им с вами.
вы получаете данные об успехе в форме данных, а не в идентификаторе, вы возвращаете данные, а не идентификатор, который вы получаете из post.php
var id = 5;
$.ajax({
type: "POST",
url: 'post.php',
data: {identify: id},
error: function(){
alert("Ошибка мой друг!");
},
success: function(data)
{
alert(data);
}
});
Возможный дубликат Как выполнить эхо-запрос SQL SELECT из файла PHP, вызываемого AJAX?