JQuery $.post not sending data to $_POST global - javascript

The send() function is my JavaScript function which uses AJAX $.post. Though the function(data) is successful, everything I intend it to do is working fine. But the data being sent, in my example, recipient && chat_sent && date is not being sent to the global variable $_POST. The second part of the code is my PHP code. Though since the data is not being sent, the if statement IN MY PHP CODE cannot be executed. What could be the problem?
function send(){
var datetemp= new Date();
var tempUser = "<? echo $user ?>";
var tempRecipient = document.getElementById("recipient_chat").value;
var chat_message= document.getElementById("chat_area").value;
$.post("searchPresentation.php", {chat_sent: chat_message, date: datetemp,
recipient:tempRecipient}, function( data ) {
$("#window").text(datetemp + $("#window").text() + tempUser + " - " + chat_message);
});
}
This is searchPresentation.php:
if (isset($_POST['chat_sent']) && isset($_POST['date']) && isset($_POST['recipient']))
{
//DO SOMETHING
}

if (!empty($_POST['chat_sent']) && !empty($_POST['date']) && !empty($_POST['recipient']))
{//DO SOMETHING}
all of param already set! "document.getElementById("chat_area").value" maybe is ' ' but it is set so use empty()

Related

unset $_POST inside javascript if statements

i need to unset $_POST['u'] but only inside a javascript function, now $_POST ARRAY unsets itself automatically after the page is ready...
function resetChat(cod_c){
if(confirm('are you sure?')){
if (sendReq.readyState == 4 || sendReq.readyState == 0) {
sendReq.open("POST", 'getChat.php?chat='+cod_c+'&last=' + lastMessage, true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.onreadystatechange = handleResetChat;
var param = 'action=reset';
param += '&user=' + document.getElementById('cod_user').value;
sendReq.send(param);
document.getElementById('txt_message').value = '';
}
<?php unset($_POST['u']); ?> // this only 1 time after confirm???
}
}
function handleResetChat() {
}
PHP is server side language and JavaScript is on client side :) You need learn more about webdev ;)

Send a string from javascript to php (in the same file)

So basically, I got a php file where I create a script in the header.
In this script, I take the value of two textbox with document.getElementByID and I concatenate them in a variable. But now, in the same script, I want to send that var to a php section to use it.
I tried the ajax way, but since the php and the javascript is in the same file, it make an error.
Here is what the script section looks like :
IN FILE.PHP
<script type="text/javascript">
rowNum = 0;
function some_function()
{
var command = "somebasiccommand";
if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
{
command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
}
<?php
$parameter = command; <----- obviously not working, but that's basically what im looking for
$output = exec("someExecutable.exe $parameter");
(...)
?>
}
</script>
EDIT 1
So here it is, I tried to use ajax this time, but this isn't working, seems like i miss something. Here is the server.php:
<?php
$parameter = $_POST['command'];
$output = exec("someexecutable.exe $parameter");
$output_array = preg_split("/[\n]+/", $output);
print_r($parameter);
?>
And here is my ajax call in my client.php (in a js script):
var command = "find";
if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
{
command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
}
var ajax = new XMLHttpRequest;
ajax.open("POST", "server.php", true);
ajax.send(command);
var output_array = ajax.responseText;
alert(output_array);
For some reason, it doesn't go farther then the ajax.open step. On the debugger console of IE10, i got this error : SCRIPT438: Object doesn't support property or method 'open' .
You are trying to run a serverside script in your ClientSide script,
that's never going to work.
https://softwareengineering.stackexchange.com/questions/171203/what-are-the-differences-between-server-side-and-client-side-programming
If you want to do something with the data from text_1 and text_2, you should create a php file that can handle a post/get request via AJAX or a simple submit, featuring the data from those elements, and make it return or do whatever it is you want it to end up doing.
You can't use javascript variable (client) from php (server). To do that, you must call ajax.
<script type="text/javascript">
rowNum = 0;
function some_function()
{
var command = "somebasiccommand";
if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
{
command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
}
//AJAX call to a php file on server
//below is example
var ajax = window.XMLHttpRequest;
ajax.open("POST", "yourhost.com/execute.php", true);
ajax.send(command);
}
</script>
And this is execute.php on server
<?php
$parameter = $_POST['command'];
$output = exec("someExecutable.exe $parameter");
(...)
?>
Alright... I pretty much changed and tested many things and I found out that the problem was the async property of the .send command. I was checking the value of the respondText too fast. Putting the third property of .open to false made the communication sync, so I receive the infos properly. I got another problem right now, but its not the same thing, so I will do another post.

Passing a JavaScript value to PHP on completion of quiz

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");
});

Why isn't my Javascript Ajax call posting values to my PHP script?

This is a very strange issue. The Javascript IS calling the PHP script, and the PHP script IS returning "something" (it returns array ()). The issue is, when I try to get the value of the posted data via $_POST['ID'] it basically says that there is no posted value, even though sendData does contain a value for ID. The full string of sendData (obtained through alert(sendData)) is as follows:
ID='1'&Invoice=''&FirstName=''&LastName=''&Description=''&Testimonial=''&ScreenRoom='false'&GlassWindow='true'
Javascript File: admin.js
function saveChanges() {
var sendData='ID=\'' + document.getElementById("ID").value + '\'';
sendData+='&Invoice=\'' + document.getElementById("Invoice").value + '\'';
sendData+='&FirstName=\'' + document.getElementById("FirstName").value + '\'';
sendData+='&LastName=\'' + document.getElementById("LastName").value + '\'';
sendData+='&Description=\'' + document.getElementById("Description").value + '\'';
sendData+='&Testimonial=\'' + document.getElementById("Testimonial").value + '\'';
sendData+='&ScreenRoom=\'' + document.getElementById("ScreenRoom").checked + '\'';
sendData+='&GlassWindow=\'' + document.getElementById("GlassWindow").checked + '\'';
var req = new XMLHttpRequest();
req.open("POST","scripts/saveChanges.php",true); //true indicates ASYNCHRONOUS
req.send(sendData);
req.onreadystatechange = function() {
//Is request finished? Does the requested page exist?
if(req.readyState==4 && req.status==200) {
//Your HTML arrives here
alert(sendData);
alert(req.responseText);
}
}
}
PHP File (that is being posted to): saveChanges.php (located in /scripts/)
<?php
session_start();
if (!isset($_SESSION['group']) || $_SESSION['group'] != 'admin') {
die ('You do not have permission to access this page!');
}
print_r($_POST);
$ID=$_POST['ID'];
$Invoice=$_POST['Invoice'];
$FirstName=$_POST['FirstName'];
$LastName=$_POST['LastName'];
$Description=$_POST['Description'];
$Testimonial=$_POST['Testimonial'];
$Date=$_POST['Date'];
$GlassWindow=$_POST['GlassWindow'];
$ScreenRoom=$_POST['ScreenRoom'];
?>
I normally only come here in a state of desperation, and being I've spent about 3 hours now working on trying to figure this out, I consider myself fairly desperate. Any help would be greatly appreciated and please ask if you need more information.
You have to set the content type for php to read the variables
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
Remove the quotes from the posted data and properly encode it
var sendData='ID=' + encodeURIComponent(document.getElementById("ID").value);
sendData+='&Invoice=' + encodeURIComponent(document.getElementById("Invoice").value);
sendData+='&FirstName=' + encodeURIComponent(document.getElementById("FirstName").value);
sendData+='&LastName=' + encodeURIComponent(document.getElementById("LastName").value);
sendData+='&Description=' + encodeURIComponent(document.getElementById("Description").value);
sendData+='&Testimonial=' + encodeURIComponent(document.getElementById("Testimonial").value);
sendData+='&ScreenRoom=' + document.getElementById("ScreenRoom").checked;
sendData+='&GlassWindow=' + document.getElementById("GlassWindow").checked;
Set the ready state listener before you send the request
req.onreadystatechange = function() {
//Is request finished? Does the requested page exist?
if(req.readyState==4 && req.status==200) {
//Your HTML arrives here
alert(sendData);
alert(req.responseText);
}
}
req.send(sendData);
Try to set HTTP header:
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");

Ajax not working with javascript. What am I supposed to do?

This is my code where I call the Request for Ajax, than a simple input button which on onClick event send some data to a function called setValue();
This is the code (JS):
//request for ajax XML
<script type='text/javascript'>
function callAjax(){
var XMLObj = false;
if(window.XMLHttpRequest)
XMLObj = new XMLHttpRequest();
else if(window.ActiveXObject)
XMLObj = new ActiveXObject('Microsoft.XMLHTTP');
if(!XMLObj)
return false;
return XMLObj;
}
//var for ajaxobject handle;
var objAjax = callAjax();
function setValue(value, id, num, item){
if(objAjax){
if(objAjax.readyState == 4 || objAjax.readyState == 0){
objAjax.open('POST', 'addview.php', true);
objAjax.send('value=' + val + '&id='+id+'&num='+num+'&item='+item);
}
}
}
//input for sending value to function setValue();
<input type='button' onClick='setValue(1, 2, 3, 4)' />
//and this is where I handle the sent data via php
<?php
if(!$_POST['value'] || !$_POST['id'] || !$_POST['num'] || !$_POST['item'])
exit();
include('config.php');
$value = mysql_real_escape_string($_POST['value']);
$id = mysql_real_escape_string($_POST['id']);
$num = mysql_real_escape_string($_POST['num']);
$item = mysql_real_escape_string($_POST['item']);
mysql_query("UPDATE `window` SET window_val = window_val + ".$value." WHERE window_id = '".$id."' AND window_num = '".$num."' AND window_item = '".$item."' ") or die(mysql_error() );
mysql_close($con);
?>
The php script is working, I tried it with sending data manually ($_GET['']) and it's working. Also I checked the URL with alert('value='+value+'&id='+id...) and all variables are Ok, but the database won't be queried.
If you see, I don't add any function for response, reply from the server. I just only want to send those data and query the data base.
Thank you !
You may be missing
objAjax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
Consider improving your function names: callAjax doesn't call Ajax, it returns a reference to the XHR object. Call it getXhr or something more like what it's actually doing.
If you're ok with jQuery, just call
function setValue(value, id, num, item){
$.post('addview.php', 'value=' + val + '&id='+id+'&num='+num+'&item='+item);
// or the cleaner version
$.post('addview.php', {value: val, id: id, num: num, item:item});
}

Categories