I have a simple if statement where when i send this certain data to the database, i want the php code to send bake a code that tells javascript its ok to continue, but if the php script sends back a bad code, javascript is to now move forward and display a certain text or something.
The php code works fine but for some reason my javascript files would not work at all.
My javascript is suppose to ajax request to parse.php and receive the data that parse.php sends back to it, if parse.php says 200 its suppose to load in specific items.
Here is the code for one of my systems:
$(document).ready(function(){
$("#chatForm").submit(function(){
var chatHash = $("#chatHash").val();
var body = $("#chatPoster").val();
var by = $("#userBy").val();
if(chatHash != "" && body != ""){
$.post('parse.php',{chatHash: chatHash, body: body, userBy: by},function(data){
if(data == "200"){ // Right here is where its messing up
$("#chatPoster").val("");
$.get('getChatMessages.php?hash=' + chatHash,function(data2){
$(".allMsgs").html(data2);
});
} else {
alert('Critical error');
}
});
} else {
alert('Error');
}
});
});
Here is the code for the parse.php page:
$chat = new ChatSystem;
if(isset($_POST['chatHash']) && isset($_POST['body']) && isset($_POST['userBy'])){
$chat->sendMessage($_POST['userBy'],$_POST['chatHash'],$_POST['body']);
}
Here is the code from the class ChatSystem that the parse.php page is referring to:
public function sendMessage($user,$hash,$body){
global $db;
$date = date("Y-m-d");
$time = date("H:i:s");
$timestamp = "$date $time";
if(empty($user) == false && empty($hash) == false){
$db->query("INSERT INTO chat_messages VALUES('','$user','$body','$timestamp','','0','$hash')") or die("error");
echo '200';
}
}
Even though my php code works perfectly the javascript still messes up. My php code sends back 200 like i ask it to but yet the jquery messes it up
Have a look here, http://api.jquery.com/jquery.post/.
You need a second parameter to the success callback function to be able to catch the response status code.
I.E. function(data,statusCode){ // check the status code here}
Related
I am working in a Wordpress project where I want to load something via ajax in my site. I am loading many sections via ajax, but I have never encountered an error before. Here, also, I am doing everything how it should be done, but I don't know why I am getting a 400 bad request error. Here is the code:
if(!function_exists('enque_this')){
function enque_this(){
wp_enqueue_style( 'style-name', MY_PLUGIN_LOCATION.'css/style.css');
wp_enqueue_script('my_script_file',MY_PLUGIN_LOCATION.'js/md-referral.js','jQuery','',true);
wp_localize_script('my_script_file','ajax_object',array('ajax_url' => admin_url('admin-ajax.php'),'we_value'=>1234));
}}
add_action('wp_enqueue_scripts','enque_this');
if(!function_exists('enque_single_prod_page')){
function enque_single_prod_page(){
wp_enqueue_script('my_script_file_2nd',MY_PLUGIN_LOCATION.'js/md-single.js','jQuery','',true);
}}
add_action('wp_enqueue_scripts','enque_single_prod_page');
function how_much_dis(){
echo 'really .. . .!!! i Got SomeTHing ??';
};
add_action('wp_ajax_how_much_dis','how_much_dis');
jquery code
jQuery(document).on("click","#submit_reff_code",function(){
var codes = jQuery("#input_reff_code").val();
var button_text = jQuery("#submit_reff_code").val("Please Wait . . .");
var is_disabled = jQuery('[name="add-to-cart"]').prop('disabled');
var product_id = jQuery('[name="add-to-cart"]').val();
var variation_id = jQuery('[name="variation_id"]').val();
if( codes != "" && codes.length > 2 && is_disabled == false && jQuery.isNumeric(product_id)){
var data = {
'action' : 'how_much_dis',
'product_id_from_prod' : product_id,
'variation_id_from_prod': variation_id,
'code' : codes
};
jQuery.post(ajax_object.ajax_url, data , function(response){
console.log(response);
});
}else{
alert("please enter valid code");
};
});
Your help would be appreciated, thanxx
400 means that action is wrong. The code in the question should work when user is logged in. To make it working when user is not logged in, you have to add the line
add_action('wp_ajax_nopriv_how_much_dis','how_much_dis');
Maybe this is the reason.
I got this JS:
<script>
jQuery(document).ready(function(){ // we wait until DOM is ready
jQuery('#veranstort').change(function(){ // fire when input is filled
origin = "55767 Schwollen";
destination = "13509 Berlin";
jQuery.ajax({ // we build the AJAX request
method:"POST",
url:"index.php?option=com_rsform&formId=6&action=ajax",
data: {origin, destination},
success: function(results) {
console.log("results: " + results);
}
});
});
})
</script>
which fires this php script:
$action = JRequest::getWord('action'); // we will need a parameter to run the script
if ($action == "ajax") { // if condition is met, run the script
$origin = $_POST['origin']; // get the origin
$destination = $_POST['destination']; // get the destination
var_dump("destination: ".$destination); // this gives me NULL!!
$distance = file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$origin."&destinations=".$destination."&key=GMAPSKEY"); // build the URL according to the API
$distance = json_decode($distance); // decode the response from JSON
print_r($distance->rows[0]->elements[0]->distance->text);die(); // print the result so we can catch it in the AJAX call
}
This has worked for a while, but now it does not. I cant access the destination or origin value in php.. What am I doing wrong?
The Error came from the missing / in the URL. It got redirected, and the POST data got lost with this process.
correct URL:
url:"/index.php?option=com_rsform&formId=6&action=ajax"
Script file it's fine . Please change the ajax file condition.
$action = $_GET['action'];
if ($action == "ajax") { // if condition is met, run the script
//// Here process your code
}
suppose I work with some kind of API and my file server.php handles the connection to the API service. on my client side I use AJAX call like this:
$http({
url : 'server/server.php',
method : 'GET',
data : { getContent : true }
});
in my server.php I handle it like this:
if(isset($_GET['getContent'])){
$content = get_content();
}
function get_content(){...}
i just wonder what prevents any one send AJAX call with the same getContent parameter and get all my data? how can i secure it and make sure only calls from my application will get the relevant data back?
thank you!
I guess you are concerned about CSRF attacks. Read more about this here: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet
One of the mostly used option to secure your request will be:
- Generate a token and send it with the request for a session. This token can be identified by your WebServer as originating from a specific client for a specific session
2022 Update
This is a 7 year old post and the link in the link-only "accepted" answer is broken.
So, I'm going to offer a basic walkthrough and a complete model.
Remember, the $_SESSION will be preserved even in the AJAX handler, if it's all from the same domain. So, you can use that to check things.
Use $_POST
I presume you're using $_POST and not $_GET since you're concerned about security. If not, then much of this might not be important anyway.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$post_method = true;
}
Ensure the $_SERVER['HTTP_REFERER'] is from your own site
if ( (!empty($_SERVER['HTTP_REFERER']))
&& ($_SERVER['HTTP_REFERER'] === "https://example.tld/my_sending_page.php") ) {
$from_my_server = true;
}
If you're not sure what this should be, run a test on your own server to see what this should be:
echo $_SERVER['HTTP_REFERER'];
Verify XMLHTTP/AJAX request via $_SERVER array
if ( (!empty($_SERVER['HTTP_X_REQUESTED_WITH']))
&& ( strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') ) {
$ajax = true;
} else {
$ajax = false;
}
Use a token
This is the hard part, but not too hard.
Create the token
Set the token in $_SESSION
Put the token in the AJAX header
AJAX responder: confirm the AJAX header token with the $_SESSION token
send_from_me.php
// Create the token
//$token = md5(rand(10000,99999)); // Not recommended, but possible
$token = bin2hex(random_bytes(64));
// Store in SESSION
$_SESSION["token"] = $token;
// Assuming your AJAX is this
const AJAX = new XMLHttpRequest();
// This goes inside your AJAX function somewhere before AJAX.send
//
AJAX.setRequestHeader("ajax-token", "<?php echo $_SESSION["token"]; ?>");
//
// That creates $_SERVER['HTTP_AJAX_TOKEN'] which we can use later
ajax_responder.php
session_start(); // Must have
if ($_SERVER['HTTP_AJAX_TOKEN'] === $_SESSION["token"]) {
$token_match = true;
} else {
echo "No script kiddies!";
exit();
}
// Now it's safe for your AJAX responder to proceed
Let's put all of this into a working example
sending_from.php
<?php
session_start();
$token = bin2hex(random_bytes(64));
$_SESSION["token"] = $token;
?>
<!DOCTYPE html>
<html>
<head>
<title>My AJAX Sender</title>
</head>
<body>
<script>
function ajaxFormData(formID, postTo, ajaxUpdate) {
// Bind a new event listener every time the <form> is changed:
const FORM = document.getElementById(formID); // <form> by ID
const FD = new FormData(FORM); // Bind to-send data to form element
const AJAX = new XMLHttpRequest(); // AJAX handler
// This runs when AJAX responds
AJAX.addEventListener( "load", function(event) {
document.getElementById(ajaxUpdate).innerHTML = event.target.responseText;
} );
// This runs if AJAX fails
AJAX.addEventListener( "error", function(event) {
document.getElementById(ajaxUpdate).innerHTML = 'Oops! Something went wrong.';
} );
// Add your token header
AJAX.setRequestHeader("ajax-token", "<?php echo $_SESSION["token"]; ?>");
// Open the POST connection
AJAX.open("POST", postTo);
// Data sent is from the form
AJAX.send(FD);
}
</script>
<div id="ajax_changes">Replace me with AJAX</div>
<form id="ajaxForm">
<input type="text" name="the_simple_response">
<button type="button" onclick="ajaxFormData('ajaxForm', 'ajax_responder.php', 'ajax_changes');">Send my Secure AJAX</button>
</form>
</body>
</html>
ajaxcheck.inc.php
<?php
$mysite = 'https://example.tld';
// All in one test
if (($_SERVER['REQUEST_METHOD'] == 'POST')
&& ((!empty($_SERVER['HTTP_REFERER'])) && ($_SERVER['HTTP_REFERER'] === "$mysite/my_sending_page.php"))
&& ((!empty($_SERVER['HTTP_X_REQUESTED_WITH'])) && ( strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'))
&& ($_SERVER['HTTP_AJAX_TOKEN'] === $_SESSION["token"])) {
$ajax_legit = true;
} else {
echo "No script kiddies!";
exit();
}
?>
ajax_responder.php
<?php
session_start();
// Do all that checking we're learning about by neatly including the file above
require_once('ajaxcheck.inc.php');
// Process your AJAX
echo $_POST['the_simple_response'];
?>
i just wonder what prevents any one send AJAX call with the same getContent parameter and get all my data?
Nothing. This URL is public thus anyone can make requests to it.
how can i secure it and make sure only calls from my application will get the relevant data back?
You can pass additional data (for example, some hashed value) that is verified on the server side.
$http({
url : 'server/server.php',
method : 'GET',
data : { getContent : true, hash : '0800fc577294c34e0b28ad2839435945' }
});
and
if(isset($_GET['getContent']))
{
if(isset($_GET['hash']) && validateHash($_GET['hash']))
{
$content = get_content();
}
}
function get_content(){...}
i just wonder what prevents any one send AJAX call with the same getContent parameter and get all my data?
The same way you would protect the data in any other request (e.g. with user authentication). There's nothing special about Ajax in regards to HTTP as far as the server is concerned.
how can i secure it and make sure only calls from my application will get the relevant data back?
You can't. The user can always inspect what their browser is asking the server for and replicate it.
Generally, people authenticate users rather than applications.
I have a web page that allows users to complete quizzes. These quizzes use JavaScript to populate original questions each time it is run.
Disclaimer: JS Noob alert.
After the questions are completed, the user is given a final score via this function:
function CheckFinished(){
var FB = '';
var AllDone = true;
for (var QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] < 0){
AllDone = false;
}
}
}
if (AllDone == true){
//Report final score and submit if necessary
NewScore();
CalculateOverallScore();
CalculateGrade();
FB = YourScoreIs + ' ' + RealScore + '%. (' + Grade + ')';
if (ShowCorrectFirstTime == true){
var CFT = 0;
for (QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] >= 1){
CFT++;
}
}
}
FB += '<br />' + CorrectFirstTime + ' ' + CFT + '/' + QsToShow;
}
All the Javascript here is pre-coded so I am trying my best to hack it. I am however struggling to work out how to pass the variable RealScore to a MySql database via PHP.
There are similar questions here on stackoverflow but none seem to help me.
By the looks of it AJAX seems to hold the answer, but how do I implement this into my JS code?
RealScore is only given a value after the quiz is complete, so my question is how do I go about posting this value to php, and beyond to update a field for a particular user in my database on completion of the quiz?
Thank you in advance for any help, and if you require any more info just let me know!
Storing data using AJAX (without JQuery)
What you are trying to do can pose a series of security vulnerabilities, it is important that you research ways to control and catch these if you care about your web application's security. These security flaws are outside the scope of this tutorial.
Requirements:
You will need your MySQL database table to have the fields "username" and "score"
What we are doing is writing two scripts, one in PHP and one in JavaScript (JS). The JS script will define a function that you can use to call the PHP script dynamically, and then react according to it's response.
The PHP script simply attempts to insert data into the database via $_POST.
To send the data to the database via AJAX, you need to call the Ajax() function, and the following is the usage of the funciton:
// JavaScript variable declarations
myUsername = "ReeceComo123";
myScriptLocation = "scripts/ajax.php";
myOutputLocation = getElementById("htmlObject");
// Call the function
Ajax(myOutputLocation, myScriptLocation, myUsername, RealScore);
So, without further ado...
JavaScript file:
/**
* outputLocation - any HTML object that can hold innerHTML (span, div, p)
* PHPScript - the URL of the PHP Ajax script
* username & score - the respective variables
*/
function Ajax(outputLocation, PHPScript, username, score) {
// Define AJAX Request
var ajaxReq = new XMLHttpRequest();
// Define how AJAX handles the response
ajaxReq.onreadystatechange=function(){
if (ajaxReq.readyState==4 && xml.status==200) {
// Send the response to the object outputLocation
document.getElementById(outputLocation).innerHTML = ajaxReq.responseText;
}
};
// Send Data to PHP script
ajaxReq.open("POST",PHPScript,true);
ajaxReq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajaxReq.send("username="username);
ajaxReq.send("score="score);
}
PHP file (you will need to fill in the MYSQL login data):
<?php
// MYSQL login data
DEFINE(MYSQL_host, 'localhost');
DEFINE(MYSQL_db, 'myDatabase');
DEFINE(MYSQL_user, 'mySQLuser');
DEFINE(MYSQL_pass, 'password123');
// If data in ajax request exists
if(isset($_POST["username"]) && isset($_POST["score"])) {
// Set data
$myUsername = $_POST["username"];
$myScore = intval($_POST["score"]);
} else
// Or else kill the script
die('Invalid AJAX request.');
// Set up the MySQL connection
$con = mysqli_connect(MYSQL_host,MYSQL_user,MYSQL_pass,MYSQL_db);
// Kill the page if no connection could be made
if (!$con) die('Could not connect: ' . mysqli_error($con));
// Prepare the SQL Query
$sql_query="INSERT INTO ".TABLE_NAME." (username, score)";
$sql_query.="VALUES ($myUsername, $myScore);";
// Run the Query
if(mysqli_query($con,$sql))
echo "Score Saved!"; // Return 0 if true
else
echo "Error Saving Score!"; // Return 1 if false
mysqli_close($con);
?>
I use these function for ajax without JQuery its just a javascript function doesnt work in IE6 or below. call this function with the right parameters and it should work.
//div = the div id where feedback will be displayed via echo.
//url = the location of your php script
//score = your score.
function Ajax(div, URL, score){
var xml = new XMLHttpRequest(); //sets xmlrequest
xml.onreadystatechange=function(){
if (xml.readyState==4 && xml.status==200){
document.getElementById(div).innerHTML=xml.responseText;//sets div
}
};
xml.open("POST",URL,true); //sets php url
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xml.send("score="score); //sends data via post
}
//Your PHP-script needs this.
$score = $_POST["score"]; //obtains score from POST.
//save your score here
echo "score saved"; //this will be displayed in the div set for feedback.
so call the javascript function with the right inputs, a div id, the url to your php script and the score. Then it will send the data to the back end, and you can send back some feedback to the user via echo.
Call simple a Script with the parameter score.
"savescore.php?score=" + RealScore
in PHP Side you save it
$score = isset ($_GET['score']) ? (int)$_GET['score'] : 0;
$db->Query('INSERT INTO ... ' . $score . ' ...');
You could call the URL via Ajax or hidden Iframe.
Example for Ajax
var request = $.ajax({
url: "/savescore.php?score=" + RealScore,
type: "GET"
});
request.done(function(msg) {
alert("Save successfull");
});
request.fail(function(jqXHR, textStatus) {
alert("Error on Saving");
});
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I hope to run a php code inside a javascript code too and I do like that :
<?php function categoryChecking(){
return false;
}?>
....
function openPlayer(songname, folder)
{
if(<?php echo categoryChecking() ?> == true)
{
if (folder != '')
{
folderURL = "/"+folder;
}else
{
folderURL = '';
}
var url = "/users/player/"+songname+folderURL;
window.open(url,'mywin','left=20,top=20,width=800,height=440');
}else{
alerte('you should click on a subcategory first');
}
}
....
<a href='javascript:void();' onClick="openPlayer('<?php echo $pendingSong['id']; ?>','')">
finally I get this error instead the alert message "you should click on a subcategory first"
ReferenceError: openPlayer is not defined
openPlayer('265','')
You're reduced your test case too far to see for sure what the problem is, but given the error message you are receiving, your immediate problem has nothing to do with PHP.
You haven't defined openPlayer in scope for the onclick attribute where you call it. Presumably, the earlier JS code is either not inside a script element at all or is wrapped inside a function which will scope it and prevent it from being a global.
Update: #h2ooooooo points out, in a comment, that your PHP is generating the JS:
if( == true)
Check your browser's error console. You need to deal with the first error messages first since they can have knock on effects. In this case the parse error in the script will cause the function to not be defined.
Once you resolve that, however, it looks like you will encounter problems with trying to write bi-directional code where some is client side and some is server side.
You cannot run PHP code from JavaScript, because PHP is a server-side language (which runs on the server) and JavaScript is a client-side language (which runs in your browser).
You need to use AJAX to send a HTTP request to the PHP page, and then your PHP page should give a response. The easiest way to send a HTTP request using AJAX, is using the jQuery ajax() method.
Create a PHP file ajax.php, and put this code in it:
<?php
$value = false; // perform category check
echo $value ? 'true' : 'false';
?>
Then, at your JavaScript code, you should first add a reference to jQuery:
<script type="text/javascript" src="jquery.js"></script>
Then, use this AJAX code to get the value of the bool:
<script type="text/javascript">
$.ajax('ajax.php')
.done(function(data) {
var boolValue = data == 'true'; // converts the string to a bool
})
.fail(function() {
// failed
});
</script>
So, your code should look like this:
function openPlayer(songname, folder) {
$.ajax('ajax.php')
.done(function (data) {
var boolValue = data == 'true'; // converts the string to a bool
if (boolValue) {
if (folder != '') {
folderURL = "/" + folder;
} else {
folderURL = '';
}
var url = "/users/player/" + songname + folderURL;
window.open(url, 'mywin', 'left=20,top=20,width=800,height=440');
} else {
alert('you should click on a subcategory first');
}
})
.fail(function () {
// failed
});
}