Url parameter not received by server via ajax - php

I am not able to send parameters to server file via ajax. i have checked comment.php with get parameters its working fine. But with ajax post parameter are not received by comment.php and else condition executes
Request Payload inside headers show url parameters received by server but when i echo $_POST array die(print_r($_REQUEST)); it gives me empty array
Here is the code i am using
<input type="text" name="comment" id="q_comment" placeholder="Add a comment" onKeyPress="postComment('q_comment')" autocomplete="off">
<script>
function $(id){
return document.getElementById(id);
}
document.onkeydown = function(event){
key_code = event.keyCode;
}
function postComment(comment_type){
if(key_code == 13){//If enter is pressed
if(comment_type == "q_comment"){//if comment added in question
var comment = $("q_comment").value;
}
else{//if comment added in answer
var comment = $("a_comment").value;
}
if(comment != ""){
var question_id = "<?php echo $id; ?>";//Returns current question id
//var params = "comment="+comment+"&question_id="+question_id;
var params = "question_id="+question_id+"&comment="+comment;//data to send to server
var ajax = new XMLHttpRequest();
ajax.open("POST","/ajax_call_files/comment.php",true);
ajax.setRequestHeader("Content-type","application/x-www-url-encoded");
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
var response = ajax.responseText;
console.log(response);
}
}
ajax.send(params);
console.log(params);
}
}
</script>
Comment.php
if(isset($_POST['comment']) && isset($_POST['question_id']) && !empty($_POST['comment']) && !empty($_POST['question_id'])){
require_once('../db_conn.php');
$user_id = $_SESSION['id'];
$comment = substr($_POST['comment'],0,530);
$comment = htmlspecialchars($comment);
$comment = mysqli_real_escape_string($conn,$comment);
$question_id = preg_replace('#[^0-9]#','',$_POST['question_id']);
$sql = "INSERT INTO comments(question_id,user_id,comment,date_time) VALUES('$question_id','$user_id','$comment',now())";
$query = mysqli_query($conn,$sql);
if($query){
echo mysqli_insert_id($conn);
}
else{
echo "Comment not added. Try again later";
}
}
else{
echo "no data recieved";
}
i have rewrite rule on file from which i am calling ajax. could it be the reason why url parameters are not received by the server
this is the rule i am using
RewriteRule ^questions/([0-9]+)/([a-zA-Z0-9_]+) questions.php?id=$1&title=$2 [NC,L]

Change the line.
ajax.setRequestHeader("Content-type","application/x-www-url-encoded");
to
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");

After
ajax.open("POST","/ajax_call_files/comment.php",true);
you need to add the url parameter as:
ajax.send(params);
After the above line of code when you are using the open() function, after you set the headers of the ajax call
At present you are trying to send the the url parameters to the server after ajax call

Related

AJAX with XMLHttpRequest doesn't send data

I want to build a simple program using XMLHttpRequest to calculate the area of the triangle. I used this code for client-side;
<body>
<form>
<label for="txtLength">Length</label>
<input type="text" id="txtLength" name="txtLength"><br><br>
<label for="txtWidth">Width</label>
<input type="text" id="txtWidth" name="txtWidth"><br><br>
<input type="hidden" name="submitted" value="1">
<input type="button" name="Calculate" value="Calculate" onclick="calArea();">
</form><br><br>
<div id="showArea">Enter Values and click Calculate.</div>
<script type="text/javascript">
function calArea() {
var len = document.getElementById("txtLength").value;
var wid = document.getElementById("txtWidth").value;
var sub = 1;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.readyState == 200) {
document.getElementById("showArea").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "calculate_area.php", true);
xhttp.send(len&wid&sub);
}
</script>
</body>
This code is for the server side.
<?php
print_r($_POST);
if (isset($_POST['sub'])) {
$len = $_POST['len'];
$wid = $_POST['wid'];
$area = (($len*$wid)/2);
echo $area;
}
else{
echo "Not input detected.";
}
?>
Even tried so many codes, It doesn't send the data to server side.
I found the mistake. I was sending the parameters as part of the URL, but need to send them as part of the request body.
Client-side code;
function calArea() {
var len = document.getElementById("txtLength").value;
var wid = document.getElementById("txtWidth").value;
var sub = 1;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("showArea").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "calculate_area.php", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send(JSON.stringify({len: len, wid: wid, sub: sub}));
}
Server-side code;
if (isset($_POST['sub'])) {
$len = $_POST['len'];
$wid = $_POST['wid'];
$area = (($len*$wid)/2);
echo $area;
}
else{
echo "Not input detected.";
}
len&wid&sub
Taking some variables and putting the Bitwise & between them is not going to give you a useful value to submit to the server.
You need to encode the data in a format that you can transmit over HTTP and which your server-side code can read.
PHP supports URL Encoded and Multipart Form Encoded data natively so pick one of those.
The URLSearchParams API will generate URL Encoded data for you.
e.g.
xhttp.send(new URLSearchParams({ len, wid, sub }));
Passing a URLSearchParams object will also let XHR automatically set the correct Content-Type request header so PHP will know what it needs to do to decode the data and populate $_POST with it.
You need to put all the parameters into a string of the form name=value with each one separated by &. And the values should be encoded in case they contain special characters.
You also need to set the content type so this data will be parsed correctly.
So change
xhttp.send(len&wid&sub);
should be:
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send(`len=${encodeURIComponent(len)}&wid=${encodeURIComponent(wid)}&sub=${encodeURIComponent(sub)}`);

Send image to other page using $.post() method

I have two pages first page has a form which accepts information like name,mobile-no etc and an image from user.
I want to access the image using jquery and send it other page using $.post() method there i want to access the image and insert it into database
First File
<script>
$(function(){
$("#add_staff").click(function(){
event.preventDefault();
var regex_mobile=/^\d{10}$/;
var regex_email = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var insti=$("#inst_id").val();
var name=$("#Staff_name").val();
var pwd=$("#Staff_pwd").val();
var add=$("#staff_address").val();
var dob=$("#Staff_dob").val();
var mail=$("#Staff_mail").val();
var role=$("#Staff_role").val();
var mobile=$("#Staff_mobile").val();
var img = $('#image').prop('files')[0];
if(name=="" || pwd=="" || add=="" || dob=="" || mail=="" || role=="" || mobile=="")
{
alert("All fields are compulsory");
}
else{
if(!regex_mobile.test(mobile)) {
alert("Mobile Number invalid");
}
else if(!regex_email.test(mail)){
alert("Email Invalid");
}
else{
$.post("add_faculty2.php",
{
insti: insti,
name:name,
pwd:pwd,
add:add,
dob:dob,
mail:mail,
role:role,
mobile:mobile,
img:img
},
function(data,status){
$("#msg").text(data);
alert(data);
alert(status);
});
}
});
});
</script>
In the above file all the information is accepted from the user and in the jquery i have tried to access all the information and image then i am trying to send the data to other page using $.post() method.
Second File
<?php
$insti =$_POST['insti'];
$name =$_POST['name'];
$pwd =$_POST['pwd'];
$add =$_POST['add'];
$dob =$_POST['dob'];
$mail =$_POST['mail'];
$role =$_POST['role'];
$mobile =$_POST['mobile'];
$img =$_POST['img'];
$today = date("Y-m-d H:i:s");
include_once 'conf.php';
$q="insert into tbl_staff_details(inst_id,name,pwd,email,phone,photo,address,dob,role,created_date) values('".$insti."','".$name."','".$pwd."','".$mail."','".$mobile."','".$img."','".$add."','".$dob."','".$role."','".$today."')";
echo $q;
$r=mysqli_query($con,$q);
if($r)
{
echo "Success";
}
else
{
echo "Fail";
}
?>
In the above file i am accessing all the information using $_POST[] sent by the $.post() method in the first file then i am trying to insert all the data in the database
Problem is that the data is not inserted in the database
But when i omit the image all the other data is inserted in the database
Ok first you need to use FormData() in your javascript
example
// formdata
var formdata = FormData();
var insti=$("#inst_id").val();
var name=$("#Staff_name").val();
var pwd=$("#Staff_pwd").val();
var add=$("#staff_address").val();
var dob=$("#Staff_dob").val();
var mail=$("#Staff_mail").val();
var role=$("#Staff_role").val();
var mobile=$("#Staff_mobile").val();
var img = $('#image').prop('files')[0];
formdata.append('upload[insti]', insti);
formdata.append('upload[name]', name);
formdata.append('upload[pwd]', pwd);
formdata.append('upload[add]', add);
formdata.append('upload[dob]', dob);
formdata.append('upload[mail]', mail);
formdata.append('upload[role]', role);
formdata.append('upload[mobile]', mobile);
formdata.append('upload[img]', img);
// now send
$.post("add_faculty2.php", formdata,
function(data,status){
$("#msg").text(data);
alert(data);
alert(status);
}
);
And in your php script you can access the image by calling
$img = $_FILES['upload']['img']['name'];
$img_tmp = $_FILES['upload']['img']['tmp_name'];
others
$insti = $_POST['upload']['insti'];
$name = $_POST['upload']['name'];
$pwd = $_POST['upload']['pwd'];
$add = $_POST['upload']['add'];
$dob = $_POST['upload']['dob'];
$mail = $_POST['upload']['mail'];
$role = $_POST['upload']['role'];
$mobile = $_POST['upload']['mobile'];
$today = date("Y-m-d H:i:s");
// you can see the image printed here..
var_export($img);
Hope this helps.

why is ajax not passing input field value to php parser?

I am building an account sign-up page that checks the users email address against the db to ensure said user isn't creating a duplicate account. Using ajax to report if email exists in the db. When typing the email address into the form I always get "email is ok". Meaning that it doesn't exist in the db. However, it is incorrect. If I assign the email as a variable in the php parser like $email="email#exists.com" then it will actually report back the correct result. I'm guessing that the parser isn't getting the value from the form in order to add to the query. Do you know why this isn't working?
<input type="text" id="password" class="form-control" name="password" value="" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" placeholder="password" autocomplete="off" required />
Ajax:
<script>
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "email_check.php";
var fn = document.getElementById("firstname").value;
var ln = document.getElementById("lastname").value;
var e = document.getElementById("email").value;
var pwd = document.getElementById("password").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
and the parser:
<?php
include 'db.php';
$test= $_POST['email'];
$sql="SELECT email FROM users where email = '$test' LIMIT 1";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0)
{
echo 'email is in use.';
exit();
} else if(mysqli_num_rows($result) < 1){
echo 'email is ok';
exit();
}
?>
You didn't add the email field to your vars when you sent the request, in this line:
var vars = "firstname="+fn+"&lastname="+ln;
You need to send email to your parser not firstname/lastname
var vars = "email="+e;

php is not sending data to javascript

I honesty did every possible search, watched lots of tutorials, but still cant make it work. The mistake is somewhere in connetion between javascript and php. The strange point is that connection is successfull and script works if I click the submit button when the page is in a process of reloading.
Please, help.
I call two variables, $l1 and $l2 from the php require-once which do some work on the page, then I use them in Java script to send to PHPfile onclick of submit button;
Button:
<input class ="button vote" type = "submit" onClick= "javascript: somefunction();" value = "do it" />
Function:
function somefunction(){
var hr = new XMLHttpRequest();
var url = "index.php";
var wn = "<?php echo $l1 ?>";
var ls = "<?php echo $l2 ?>";
var vars = "wn="+wn+"&ls="+ls;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars); // execute the request
document.getElementById("status").innerHTML = "processing...";
}
php acceptor on the same page:
<?php if (isset ($_POST ["wn"])){
$wnn = $_POST['wn'];
$lss = $_POST['ls'];...
try this:
var wn = document.getElementById("wn").value;
var ls = document.getElementById("ls").value;
I presume you ar calculating these either diectly, or from a $_SESSION variable perhaps? When you view the source on the completed page check if the variables are present, perhaps just after you assigne the variables within php.
<?PHP
if (isset($l1) && !empty($l1)) {
echo "L1 is $l1";
} else {
echo "L1 wasnt set";
}
?>
then make sure the value up top matches that you're seeing in your javascript

PHP In ajax responseText take all the html cose instead of ONLY the echo passed trought PHP

Using that javascript ajax function I pass the content of a form, that contain
the dato value, to the PHP login.php than trought the echo pass back the content
(the insert form) that I want to be switched to the cancel form, using
the content respondText (that may take only the echo of the PHP).
BUT INSTEAD the responseText contain ALL the html code, with the old html
plus the cancella_form passed by the echo, that's also out of the div
with id=visibile.
Any ideas why? D:
//ajaxSubmit(dato)
function ajaxSubmit( url , divId , hideId ) {
//in setXmlHttpObject() I just control the user's browser
// and assign the right XmlHttp Object
var ajaxRequest = setXmlHttpObject();
var dato = 'nome='+document.getElementsByName('dato')[0].value;
ajaxRequest.open("POST", url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(dato);
ajaxRequest.onreadystatechange = function() {
//Comunication complete
if (ajaxRequest.readyState == 4 && ajaxRequest.status==200) {
//Comuncation succesfull
if(ajaxRequest.statusText === "OK"){
var str= ajaxRequest.responseText;//<<<HERE///////
$(str).replaceAll("#visibile");
}
//Comuncation failed
else{
var str= "ERROR: Ajax: "+ajaxRequest.responseText;
document.write(str);
}
}
}
}//FINE ajaxRequest();
<?php
include("prova_login_adv.php");
$conn= mysql_connect('localhost','root','');
mysql_select_db('db_prova',$conn ) or die(mysql_error());
//
if(isset($_POST['nome'])){
$dato= $_POST['nome'];
mysql_query(" INSERT INTO test (valore) VALUES ('$dato') ") or die(mysql_error());
/// NOW I declare what I want to be replaced in the div id="visibile"
echo "
<form id='form_cancella' name='form_cancella' action='' methos='POST' onSubmit=' return false;' >
<text name='dato' value='".$dato."' >Benvenuto <b>".$dato."</b></text>
<input type='submit' name='cancella' value='cancella' onClick=\" ajaxSubmit('logout.php','visibile','form_cancella');\" />
</form>
";
}
?>

Categories