Correct ajax post syntax? - javascript

Hello I'm trying to post data to a database and it's working with get, but not with post.
Here's my javascript:
function updateShout(id)
{
var http = new XMLHttpRequest();
http.open("POST", location.href);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send("edit="+document.getElementById("EDITM").value+"&id="+id);
return false;
}
I'm making an ajax request to the current page with: index.php?edit=message&id=X
PHP is working fine, but I believe it's something with this line:
http.send("edit="+document.getElementById("EDITM").value+"&id="+id);
PHP (if needed):
if($_SESSION['signedin'])
{
if(!is_blank($_REQUEST['edit'])) //if empty($value) && !is_numeric($value);
{
$id = toNum( $_REQUEST['id'] ); //if(!is_numeric($val)) return -1; return (int)$val;
$msg = htmlentities($_REQUEST['edit']); //secure dis
$query = $db->query("UPDATE shouts SET shout='$msg' WHERE shoutid='$id'");
$db->close();
exit;
}
}
please close.. found my issue. my had name instead of id as "EDITM"

Related

Ajax. Sending data to php file

Good day, I'm trying to use Ajax in my web application. But I have a little problem with it. I try to control a form if some username has already been registered or not. But my JavaScript seem does not send $_POST value to PHP. And responses that user in not defined on the line where I have $_POST['user'].
Here what I have.
PHP:
<?php
$opt = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$dsn ='mysql:dbname=someone;host=127.0.0.1;charset=utf8';
$user='someone';
$pswd='aaa';
$dbh = new PDO($dsn, $user, $pswd, $opt);
$query="SELECT 1 FROM users WHERE username = :username";
$query_p=array(':username' => $_POST['user']);
try
{
$statment = $dbh->prepare($query);
$result = $statment->execute($query_p);
}catch(PDOException $e)
{
echo "Can't run query: " . $e->getMessage();
}
$row = $statment->fetch();
if($row){
return 0;
}else {
return 1;
}
?>
So it opens a connection to database and runs a query
JavaScript:
function checkUser(e){
var state1 = document.getElementById("alert_text");
var u = document.getElementById("user").value;
if(u != ""){
state1.innerHTML = 'processing...';
var request = new XMLHttpRequest();
request.open("POST", "validation.php", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var result=request.responseText;
alert(result);
if(result==1){
state1.innerHTML="OK";
}else{
state1.innerHTML="Alredy exists!";
}
}
};
request.send(u);
var slova = request.responseText;
}
}
document.getElementById("user").addEventListener("blur",checkUser,false );
So technically it is ajax.
HTML:
<form id="check" name="signUp" method="post">
<p class="alert_text"></p>
<label for="user">Username:</label><br />
<input id="user" name="user" type="text" ><br />
</form>
I don't really see what's the problem...
You're not passing the username into the PHP script. Your PHP is looking for a POST variable, $_POST['user'] – in your JavaScript you make a GET request, so the PHP script has nothing to look up.
Based on the edited question: You are not sending any key-value pairs to the server, just a single value.
You need to change:
var u = document.getElementById("user").value;
to:
var u = 'user=' + encodeURIComponent(document.getElementById("user").value);
And then later on the pair will be sent correctly:
request.send(u); // sends a single key-value pair
Note that I have just added the encodeURIComponent function to make sure the value gets encoded correctly.

Session variable not being updated after being used

I am trying to check the result from a function and determine where on my page it should go by using the Session Variable "alernativeRD". It goes to the correct element on the first try, but after that it keeps going only to the first element regardless of whether its right or not. After some testing I've found that "alernativeRD" does get changed every time in the PHP function, but it doesn't change in the Javascript part.
PHP PART
function firstSignInDefault(){
global $con;
$clubUsername= $_SESSION['clubUsername'];
$_SESSION['alternativeRD']='false'; //sets it back to false to avoid having alternativeRD be true for next user
$lastName= mysqli_real_escape_string($con, $_POST['lastNameF']);
$firstName= mysqli_real_escape_string($con, $_POST['firstNameF']);
$memberID= mysqli_real_escape_string($con, $_POST['idNumberF']);
if(!(is_numeric($memberID))){
die("<h3> Student ID must be a number </h3>");
}
$getMemberRow= mysqli_query($con, "SELECT * FROM memberstable WHERE MemberMadeID='$memberID' AND Club='$clubUsername'");
if(mysqli_num_rows($getMemberRow)==0){
$sql="INSERT INTO memberstable (MemberMadeID,FirstName,LastName,Club)
VALUES ('$memberID','$firstName','$lastName', '$clubUsername')";
$test=false; //checks to make sure sql statement runs fine
if(mysqli_query($con,$sql))
$test=true;
else {
echo "<h3> Error running sql </h3>";
}
$date=date("Y-m-d h:i:sa");
$getMemberRow= mysqli_query($con, "SELECT * FROM memberstable WHERE MemberMadeID='$memberID' AND Club='$clubUsername'");
$memberRowArray=mysqli_fetch_array($getMemberRow);
$memberPanID=$memberRowArray['UniquePanDBID'];
$sql2="INSERT INTO signinstable (TimeOfSignIn, UniquePanDBID, ClubUsername, FirstName, LastName) VALUES ('$date','$memberPanID','$clubUsername', '$firstName', '$lastName')";
//THE FOCUS OF THIS QUESTION IS BELOW THIS COMMENT
if(mysqli_query($con, $sql2) && $test==true){
$_SESSION['alternativeRD']='true';
echo " <h2 id='signedInPeople' >".$date. " ".$firstName ." ". $lastName ."</h2>";
}
}
else {
echo "<h3> ID Number already in use</h3>";
}
}
JAVASCRIPT/AJAX PART
function processFSIF(){
var xmlHttp= makeXMLHTTP();
// Create some variables we need to send to our PHP file
var url = "signInDataPlace.php";
var idNumberF = document.getElementById("idNumberF").value;
var lastNameF = document.getElementById("lastNameF").value;
var firstNameF = document.getElementById("firstNameF").value;
var typeSignIn="first";
var vars = "idNumberF="+idNumberF +"&lastNameF="+lastNameF +"&firstNameF="+firstNameF +"&typeSignIn=" +typeSignIn;
xmlHttp.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var return_data = xmlHttp.responseText;
//AREA OF PROBLEM BELOW
<?php
if($_SESSION['alternativeRD']=='true'){ ///YOU ARE HERE, alternativeRD is acting stupid
?>
document.getElementById("serverInputList").innerHTML = return_data;
<?php
}else{
?>
document.getElementById("serverInputFSIF").innerHTML = return_data;
<?php
}
?>
}
}
// Send the data to PHP now... and wait for response to update the status div
xmlHttp.send(vars); // Actually executes the request
document.getElementById("serverInputFSIF").innerHTML = "processing...";
}
Your Javascript was printed only once, before you use AJAX. You can return the session value together with response, or you can set the cookie in PHP, than use it in javascript.

Is it possible to call PHP-Script from JavaScript section of JSP page..?

I have written following script on server-
<?php
//Create an array
$json_response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$status = "In Progress";
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if (!$con)
{
die('Could not connect to database: ' . mysql_error());
}
//Query to select pending queries database
$result = mysqli_query($con, "SELECT * FROM tbl_query_master WHERE status='".$status."' ORDER BY query_date DESC");
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
$row_array['query_id'] = $row['query_id'];
$row_array['sender_mobile_no'] = $row['sender_mobile_no'];
$row_array['sender_name'] = $row['sender_name'];
$row_array['query_string'] = $row['query_string'];
$row_array['action_taken'] = $row['action_taken'];
$row_array['status'] = $row['status'];
$row_array['query_date'] = $row['query_date'];
$row_array['action_date'] = $row['action_date'];
$row_array['view_status'] = $row['view_status'];
$row_array['read_status'] = $row['read_status'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
?>
Above script returns one JSON object which is useful for me in JavaScript section of my JSP page, but I don't know how to call php-script from the java script section, so need your guidance for the same. Hope you understand what I'm saying Thank you..!
Suppose your php script is deployed to a web server (apache with php mod) and is triggered by some URL, e.g. http://localhost/script.php
Then in your javascript you can do POSt request using jquery:
$.getJSON('http://localhost/script.php', function(json) {
// do what you need with your json data
});
Finally I solved it using AJAX as follows, I don't know whether performance wise this method is correct or not, but perfectly worked for me. Write the following code in your JavaScript section.
var xmlHttp;
//FUNCTION TO CREATE BROWSER COMPATIBLE OBJECT.
function createBrowserObject()
{
if (typeof XMLHttpRequest != "undefined") //Object for Netscape 5+, Firefox, Opera, Safari,and Internet Explorer 7
{
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) //Version for Internet Explorer 5 and 6.
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp == null) //Fails on older and nonstandard browsers
{
alert("Browser does not support XMLHTTP Request");
}
}
function getDataChange()
{
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") //Check whether server response came back with no errors.
{
//THE RESPONSE FROM SERVER. DO YOUR STUFF WITH xmlHttp.responseText
alert("Responce= "+xmlHttp.responseText);
//document.getElementById("cart_div").innerHTML = xmlHttp.responseText;
}
}
function getData()
{
createBrowserObject();//CREATE BROWSER COMPATIBLE OBJECT.//
var url = "http://yourdomain.com/your_script.php"; // URL of server-side resource.
// Using following way you can send parameter to your script.
//url += "?param1=" + param1 + "&param2=" + param2;
xmlHttp.onreadystatechange =getDataChange; //ASSIGN RESPONSE HANDLER FUNCTION NAME TO ONREADYSTATECHANGE//
xmlHttp.open("GET", url, true); //INITIATE GET or POST REQUEST. (Here GET)
xmlHttp.send(null); // SEND DATA. (Always null in case of GET.)
}
And finally create event to call "getData()" function. That's it. Thank you..!

PHP not receiving JSON from Ajax post

I am trying to send some JSON to a PHP processing code via Ajax. Here is my JavaScript:
var j = {"a":"b"};
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
};
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
console.log(xmlhttp.responseText)
};
};
xmlhttp.open("POST", "server.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xmlhttp.send({
"json": j
});
And the PHP:
$json = $_POST["json"];
echo $json;
But this echoes null. What have I done wrong? This seems like it should work. Thanks!
Please no jQuery. And if you vote down, please tell me why so I can improve.
Your j variable is a object. You need to encode this into a json string before you post it.
Okay I have re-written my answer from scratch.
Update your server.php like this:
<?php
// Request Handler
if (count($_POST))
{
$json = isset($_POST['json']) ? $_POST['json'] : '';
if (!empty($json))
{
$jsonObj = json_decode($json);
print_r($jsonObj);
}
else
{
echo "No json string detected";
}
exit();
}
?>
Change your ajax request like this:
<script type="text/javascript">
var j = {"a":"b"};
var xmlHttp = new XMLHttpRequest();
var parameters = "json="+ encodeURIComponent(JSON.stringify(j));
xmlHttp.open("POST", "server.php", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameters.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
console.log(xmlHttp.responseText);
}
}
xmlHttp.send(parameters)
</script>
Here's a demo of it working:
So, in the PHP script, I am printing the $jsonObj and it's contents. If you want to use it in your script; you'd do this:
e.g.
<?php
if ($jsonObj->a == 'b') {
// do something ?
}
?>
If you want an associative array to work with (instead of an object), you can do this:
Change: $jsonObj = json_decode($json); To: $jsonObj = json_decode($json, true);
Now you can do this:
<?php
if ($jsonObj['a'] == 'b') {
// do something ?
}
?>
Javascipt :
encode en JSON with JSON.stringify(j);
if j contain & in string and not a separator de data :
j.split("&").join("%26");
in php
$json = $_REQUEST['json'];
$json = str_replace("%26","&",$jsonData);
$json = html_entity_decode($json,ENT_NOQUOTES,'UTF-8');
$data = json_decode($json,true);
the value of json as array of data.
To submit JSON properly, it'd be:
xmlhttp.send(JSON.stringify({"json": j});
Then for the PHP:
$json = json_decode(file_get_contents('php://input'));
The problem is that when sending JSON (if it's a proper JSON request), PHP won't automatically parse it.

AJAX not passing variable to PHP for MySQL query

I am trying to get the below AJAX script to pass a dropdown ID to PHP to run a query on, however it doesnt appear that the variable is actually being passed. When I hardcode the PHP file the query runs correctly, but when I try to do it dynamically the query returns "undefined" or nothing at all.
AJAX code
function ajax_post(){
var request = new XMLHttpRequest();
var id = document.getElementById("editorginfo").value;
alert (id);
request.open("POST", "parse.php", true);
request.setRequestHeader("Content-Type", "x-www-form-urlencoded");
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200) {
var return_data = request.responseText;
alert (return_data);
document.getElementById("orgeditname").value = return_data;
document.getElementById("orgeditphone").value = return_data;
}
}
request.send("id="+id);
}
PHP Parse Code
<?php
include_once('../php_includes/db_connect.php');
$searchid = $_POST['id'];
//$searchid = 1;
$sql = 'SELECT * FROM orginfo WHERE id = $searchid';
$user_query = mysqli_query($db_connect, $sql) or die("Error: ".mysqli_error($db_connect));
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$orgid = $row["id"];
$orgname = $row["orgname"];
$orgphone = $row["orgphone"];
echo $orgname, $orgphone;
}
?>
Not really sure where the information is getting lost. When I alert the id out it is capturing the right information, so I assume the issue is in my send portion, but I can't figure out what I'm doing wrong. Any help would be appreciated.
Thanks in advance.
Your request header is wrong. Change this line -
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
^^^^^^^^^^^^

Categories