La fonction ajax se trouve dans l'en-tête de ma page d'index fonction.
<?php require ('connection.php'); if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === "XMLHttpRequest") { if (isset($_GET['postId']) && !empty($_GET['postId'])) { $postId= mysqli_real_escape_string($link, $_GET['postId']); if (isset($postId) && !empty($postId)) { mysqli_query = ($link, "UPDATE posts SET postVotes = postVotes + 1 WHERE postId = {$postId}"); } } } else { die("You are not allowed to access this file..."); } ?>
Je reçois une alerte d'url et un succès lors du déclenchement de la fonction, mais les identifiants ne sont pas interprétés par file.php.
Quelqu'un peut-il m'aider? p>
Le script PHP
myFunction(theVar) { var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); var url = "includes/file.php"; if (theVar.includes("postId")) { url = url + "?postId" + "=" + theVar.substr(theVar.length - 1); } else if (theVar.includes("userId")) { url = url + "?userId" + "=" + theVar.substr(theVar.length -1); } else if (theVar.includes("commentId")) { url = url + "?commentId" + "=" + theVar.substr(theVar.length -1); } alert(url); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { alert("Success!"); } }; xhr.open('GET', url, true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.send(); return xhr; }
4 Réponses :
L'erreur est ici:
<?php require ('connection.php'); if (isset($_GET['postId'])) { // no need for && !empty($_GET['postId']) if isset is used $postId = mysqli_real_escape_string($link, $_GET['postId']); if (isset($postId)) { // no need for && !empty($postId) if isset is used //mysqli_query = ($link, "UPDATE posts SET postVotes = postVotes + 1 WHERE postId = {$postId}"); echo "UPDATE posts SET postVotes = postVotes + 1 WHERE postId = {$postId}" // test } else { echo "postId is empty!"; } }
Cela devrait être:
url = url + "?commentId" + "=" + theVar.substr(theVar.length -1);
Du côté PHP, vous devez "attraper" votre variable avec $ _GET ["commentId"]
Référence: http://php.net/manual/de/reserved.variables.get.php
Edit:
url = url + "commentId" + "=" + theVar.substr(theVar.length -1);
Maintenant, testez-le en utilisant par exemple localhost/your.php?postId=2
Si ma réponse mise à jour fonctionne, ce sont les variables $ _SERVER
qui causent des problèmes.
Cela semble être une manière particulière de structurer la variable, d'autant plus que vous devez la traiter plus avant pour obtenir l'ID dont vous avez besoin. Vous pourriez le rendre plus simple comme ça? L'avantage de ceci serait que vous pouvez envoyer de nombreux paramètres sans avoir à modifier la partie interne de la fonction - ajoutez simplement plus de paramètres / valeurs à l'objet variable theVar
.
Le html p >
<?php if ( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && !empty( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && $_SERVER['HTTP_X_REQUESTED_WITH'] === "XMLHttpRequest" ) { ob_clean(); $postId = filter_input( INPUT_GET, 'postId', FILTER_SANITIZE_NUMBER_INT ); $commentId = filter_input( INPUT_GET, 'commentId', FILTER_SANITIZE_NUMBER_INT ); $userId = filter_input( INPUT_GET, 'userId', FILTER_SANITIZE_NUMBER_INT ); /* here you would con */ $output=array( 'post' => $postId, 'comment' => $commentId, 'user' => $userId ); echo json_encode( $output ); exit(); } ?> <!DOCTYPE html> <html lang='en'> <head> <meta charset='utf-8' /> <title>ajax</title> <style> body{display:flex;flex-direction:column;padding:1rem;margin:0;box-sizing:border-box;font-family:cursive;font-size:1rem;} div{display:flex;flex-direction:row;justify-content:center;align-content:space-between;align-items:center;flex:1;order:1;width:100%;} output{display:flex;flex:2;order:2;width:100%;justify-content:center;margin:1rem auto;} button{padding:1rem;margin:auto} </style> <script> const callback=function(r){ if( r ){ document.querySelector( 'output' ).innerHTML=r; } }; const myFunction=function(theVar){ var xhr=new XMLHttpRequest(); var url = location.href; if (theVar.includes('postId')) { url = url + '?postId=' + theVar.substr(theVar.length - 1); } else if (theVar.includes('userId')) { url = url + '?userId=' + theVar.substr(theVar.length -1); } else if (theVar.includes('commentId')) { url = url + '?commentId=' + theVar.substr(theVar.length -1); } xhr.onreadystatechange = function() { if( this.readyState == 4 && this.status == 200 ) { callback( this.response ) } }; xhr.open('GET', url, true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.send(); }; const myOtherFunction=function( theVar ) { var xhr=new XMLHttpRequest(); var url = location.href; var query=[]; Object.keys( theVar ).map( function( key ){ query.push( key+'='+theVar[key] ) } ); url+='?'+query.join('&'); xhr.onreadystatechange = function() { if( this.readyState == 4 && this.status == 200 ) { callback( this.response ) } }; xhr.open('GET', url, true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.send(); } </script> </head> <body> <div> <button type='button' onclick='myOtherFunction( { postId:808 } );'>Click me [POSTID]</button> <button type='button' onclick='myOtherFunction( { commentId:909 } );'>Click me [COMMENTID]</button> <button type='button' onclick='myOtherFunction( { userId:303 } );'>Click me [USERID]</button> <button type='button' onclick='myOtherFunction( { postId:808,commentId:909,userId:303 } );'>Click me [ALL]</button> </div> <div> <button type='button' onclick='myFunction( "postId808" );'>Click me [STRING - POSTID]</button> <button type='button' onclick='myFunction( "commentId909" );'>Click me [STRING - COMMENTID]</button> <button type='button' onclick='myFunction( "userId303" );'>Click me [STRING - USERID]</button> </div> <output></output> </body> </html>
le javascript
<?php if ( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && !empty( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && $_SERVER['HTTP_X_REQUESTED_WITH'] === "XMLHttpRequest" ) { require 'connection.php'; $postId = filter_input( INPUT_GET, 'postId', FILTER_SANITIZE_NUMBER_INT ); $commentId = filter_input( INPUT_GET, 'commentId', FILTER_SANITIZE_NUMBER_INT ); $userId = filter_input( INPUT_GET, 'userId', FILTER_SANITIZE_NUMBER_INT ); $sql=false; if( $postId ){ $sql='update `posts` set `postVotes` = `postVotes` + 1 where postId=?;'; $id=$postId; } /* assumed similar table called comments */ if( $commentId ){ $sql='update `comments` set `commentVote` = `commentVote` + 1 where `commentId`=?;'; $id=$commentId; } /* etc - users too?? */ if( $userId ){ $sql='.... etc etc '; $id=$userId; } if( $sql ){ $stmt=$link->prepare( $sql ); $stmt->bind_param('i', $id ); $res=$stmt->execute(); } } else { exit( header( 'HTTP/1.1 403 Forbidden', true, 403 ) ); } ?>
Cela dit, après une modification mineure, ce qui suit a fonctionné pour moi tout à l'heure. Le code PHP que j'ai utilisé est également ci-dessous ...
{"postId":"4"}
Cible du test PHP
<?php echo json_encode( $_REQUEST ); ?>
La réponse
const myFunction=function( theVar ) { var xhr=new XMLHttpRequest(); var url = 'includes/file.php'; if (theVar.includes('postId')) { url = url + '?postId=' + theVar.substr(theVar.length - 1); } else if (theVar.includes('userId')) { url = url + '?userId=' + theVar.substr(theVar.length -1); } else if (theVar.includes('commentId')) { url = url + '?commentId=' + theVar.substr(theVar.length -1); } xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { alert('Success!'); } }; xhr.open('GET', url, true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.send(); }
Vous pouvez modifier le PHP pour le rendre un peu plus sécurisé en utilisant des instructions préparées.
<script> const myFunction=function( theVar ) { var xhr=new XMLHttpRequest(); var url = 'includes/file.php'; var query=[]; Object.keys( theVar ).map( function( key ){ query.push( key+'='+theVar[key] ) } ); url+='?'+query.join('&'); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { alert('Success!'); } }; xhr.open('GET', url, true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.send(); } </script>
Pleine page, une seule démo
<button type='button' onclick='myFunction( { postId:<?php echo $post['postId']; ?> } );'>Click me</button>
Je suppose que la variable que vous passez à votre fonction ajax vient de cette manière, c'est-à-dire que si son postId
il se présente sous la forme postId23
, alors vous lorsque vous utilisez if (theVar.includes ("postId")
pour vérifier s'il contient les mots-clés postId
alors vous essayez d'obtenir le numéro d'identification en faisant cette fonction theVar.substr (theVar.length - 1);
C'est là que vous vous trompez car lorsque vous utilisez la fonction substr (theVar.length-1);
cela retournera toujours le dernier caractère de cette chaîne donc si theVar
est postId23
la fonction substr () renverra 3 comme identifiant puis vous obtiendrez l'url comme ? postId = 3
mais vous vous attendiez à ce qu'il retourne 23. moyen simple si postId, commentId, userId sont des constantes, vous devrez savoir où se termine la position du tableau de chaînes, c'est-à-dire si son postId la position à laquelle il se termine est 5, alors le code de la fonction substr () sera comme tel theVar .substr (5);
si la chaîne est commentId alors compter le tableau position de fin de chaîne qui sera à la position 8 alors le code sera theVar.substr(8);
Ce n'est pas non plus une bonne manière de traiter les requêtes. Vous devrez peut-être changer la façon dont vous envoyez vos variables à la fonction et comment obtenir les variables. À l'avenir, cela pourrait provoquer des erreurs. J'espère que cela vous aidera, vous et n'importe qui d'autre.
Essayez de jouer avec cet exemple sur la fonction substr ()
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_substr
je pense que la fonction n'envoie pas l ' url
qu'en est-il de cette variable $ link où la définissez-vous avant de l'assigner à $ postId?
connection.php contient la variable
essayez d'ajouter ceci xhr.onload = function () {console.log (xhr.responseURL)}
cela affichera votre URL dans la console Web si elle a réussi à envoyer l'URL. alors vous pouvez voir ce qu'il a vraiment envoyé à votre fichier.
placez-le après send ();
j'obtiens l'url comme en alerte
continuons cette discussion dans le chat
D'accord! Un problème est survenu i
nécessitait un fichier dans le fichier php de connexion
et le fichier de script php
n'a pas trouvé
le fichier
déjà vérifié pour l'en-tête de la requête dans file.php
pouvez-vous montrer comment cela est invoqué?
btw: le php est vulnérable à l'injection SQL ~ envisagez d'utiliser une instruction préparée au lieu d'incorporer des variables dans le sql lui-même ...