Able to receive data using $_GET but not $_POST [duplicate] - php

This question already has answers here:
Send POST data using XMLHttpRequest
(13 answers)
Closed 9 years ago.
Using Ajax to communicate with server,
I am trying to pass a value to dat.php using AJAX and get another value from dat.php back. The below code works fine when I use GET but doesn't work work with POST. I need to use POST as this is sensitive information I am trying to pass. Any idea hwy this is happening.
This is my code on test.php
<html>
<body>
<form action="<?php echo $_SERVER['$PHP_SELF'];?>" method="post">
<input type="text" name="value" onchange="ch_email1(this.value)"></input>
</form>
<script>
function ch_email1(str){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
var xl=xmlhttp.responseText
alert("Something Went wrong");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var xl=ajaxRequest.responseText;
alert (xl);
}
}
ajaxRequest.open("POST","dat.php?q="+str, true);
ajaxRequest.send(null);
}
</script>
</body>
</html>
This is dat.php
<?php
$q=$_POST['q'];
echo $q;
?>
Please note that above code works fine when I replace POST with GET. Any ides why this is happening.

This might help:
ajaxRequest.open("POST","dat.php", true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send("q="+str);

Take a look at this page.
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
Right now, you're sending a post request with nothing in it. Appending to the url just changes the $_GET variables.

You are mixing POST Ajax call with GET way
When you send an AJAX call with POST, you don't have to put parameter on the URL, but you must send parameters using the .send() method.
exemple:
ajaxRequest.open("POST","dat.php",true);
ajaxRequest.send("q=" + str);
You should use a JS librairy like jQuery or other, that will make it for you, instead of re-inventing the wheel and have common problems.

Related

Web Shoutbox Idea

Hello I was thinking about making a shoutbox for my site. I don't want to use any others because it doesn't fit in well with my pre-existing members database. I thought of some ideas but I'm not really sure on a better way of doing this. I want to submit a form and without 'GET' send a shout. I also can't re-load the page. That's where AJAX comes in :p
I thought of setting up the form on my webpage as:
<form method="post" onsubmit="return sendShout()" >
<input type="text" name="Shout" id="Shout" />
</form>
With my javascript being the following:
<script>
function sendShout()
{
if(ShoutTime == 0)
{
var http = new XMLHttpRequest();
http.open("GET", location.href+"?shout="+encodeURIComponent(document.getElementById("Shout").value)+"&name="+encodeURIComponent(document.getElementById("username").value), true);
http.send();
ShoutTime = <?php echo $shoutWait;?>+1;
ShoutWait();
unidle();
document.getElementById("Shout").value='';
}
else
{
ShoutWaitNote();
getLogs();
}
return false;
}
</script>
then on the page I could put into the databse like $_GET['shout']... etc.
Now is there a better way to use ajax to send a shout to a mysql database without having the shout as a GET in the url?
I suspect there are bigger problems at hand here, but you can do a POST with XMLHttpRequest like so:
var http = new XMLHttpRequest();
http.open("POST", location.href);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send("shout=something&name=something");
As opposed to the GET version:
var http = new XMLHttpRequest();
http.open("GET", location.href + "?shout=something&name=something");
http.send();
You'll want to apply URL encoding in both cases. Good luck.

Getting trouble in saving data to a mysql using AJAX

I am using the very basic technique of AJAX to save the form into a database using AJAX.
However I am having some trouble.
All I searched, I was getting jQuery code, but I want to do this with simple AJAX only.
HTML FORM:
<form id="submitcourse" name="submitcourse" method="get">
<p>Course Name: <input type="text" name="cvalue" id="cvalue" /></p>
Successfull
</form>
<span id="result">.</span>
AJAX CODE:
<script type="text/javascript">
function GetXmlHttpObject()
{
if(window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if(window.ActiveXobject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function submitformwithajax()
{
var myAjaxPostrequest=new GetXmlHttpObject();
var coursename=document.submitcourse.cvalue.value;
var parameter="cvalue="+coursename;
myAjaxPostrequest.open("GET", "do.php", true)
myAjaxPostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjaxPostrequest.send(parameter)
myAjaxPostrequest.onreadystatechange=function{
if(myAjaxPostrequest.readyState==4){
if(myAjaxPostrequest.status==200){
document.getElementById("result").innerHTML=myAjaxPostrequest.responseText;
document.getElementById("submitcourse").style.display="none";
}
else
document.getElementById("submitcourse").innerHTML="An error has occured making the request";
}
}
}
</script>
The purpose of the above AJAX code is to send the form details to do.php File, where I can work on the data received.
do.php File :
<?php
$course=$_REQUEST['cvalue'];
echo "dddd".$course;
?>
Right now I am not able to get the value in the do.php file, Please help me out,
NOTE: I have the code to do this using jQuery, but I want to do it in this method only. Since it is for teaching students about Basic AJAX.
Right off the bat I'm noticing that you don't have () after your function definition...
myAjaxPostrequest.onreadystatechange=function{
Should be
myAjaxPostrequest.onreadystatechange=function(){
Let me know if this helps!
The problem is: you put your parameter inside send(), which is not correct, because you sending GET request, change your code to:
myAjaxPostrequest.open("GET", "do.php?"+parameter, true)
myAjaxPostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjaxPostrequest.send()
Using Ajax GET, the parameter should be mixed with the URL, however, your code is correct for POST method.
or if you want to use POST
myAjaxPostrequest.open("POST", "do.php", true)
myAjaxPostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjaxPostrequest.send(parameter)
See if you can't get away with using getElementsByName instead
var coursename=document.getElementsByName('cvalue')[0].value;

How to pass javascript variables to a database

i have an application in javascript. I follow some tutorial to do it, but i really don't have experience with the javascript code. The problem is that i need to pass the variables results from javascript to mysql database. I have found some answers in this site and i try to do what i found with no luck. What i found is that i need ajax and php. I never use ajax and because of that i dont understand what i'm doing wrong.
Maybe if i put the code here, someone can help me with a solution.
This is the javascript code:
function ajaxFunction(){
var ajaxRequest;
try{
Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
ds = new Date();
e_time = ds.getTime();
var res = new Object();//This are the results variables that i need to pass to my database
res.bytes_transfered =;
res.total_time_seconds = (e_time-s_time)/1000;
res.generatied_in = ;
res.ip = "";
-->
var res1= 'res.bytes_transfered';
var res2= 'res.total_time_seconds';
var res3= 'res.generatied_in';
var res4= 'res.ip';
$.post('insert.php',{res.bytes_transfered:res1,res.total_time_seconds: res2, res.generatied_in: res3, res.ip:res4});
var queryString = "?res.bytes_transfered=" + res.bytes_transfered + "&res.total_time_seconds=" + res.total_time_seconds + "&res.generatied_in =" + res.generatied_in + "&res.ip =" + res.ip;
ajaxRequest.open("POST", "insert.php" + queryString, true);
ajaxRequest.send(null);
new Ajax.Request('insert.php', {
onSuccess : function(xmlHTTP) {
eval(mlHTTP.responseText);
}
});
This is the insert.php:
$fecha= date("Y-m-d H:i:s");
$connnect= mysql_connect("localhost", "root", "xxxxxxxxx");
mysql_select_db("dbname");
$res1= mysql_real_escape_string($_POST['res1']);
$res2= mysql_real_escape_string($_POST['res2']);
$res3= mysql_real_escape_string($_POST['res3']);
$res4= mysql_real_escape_string($_POST['res4']);
$queryreg=mysql_query("INSERT INTO grafico(Cantidad, Tiempo, IP, Bajada, Subida, Fecha) VALUES ('$res1','$res2','$res3','$res4','0','$fecha') ");
if (!$queryreg) {
die('No se ha podido ingresar su registro.');
}
else{
die("Usted se ha registrado exitosamente!");
}
I hope that somebody can help me. I dont know what to do!
It looks like your POST data has the keys and values backwards. In the data passed to $.post the key name needs to come first and the value after the :. So I think it should be:
$.post('insert.php',{res1:res.bytes_transfered,res2:res.total_time_seconds,res3:res.generatied_in, res4: res.ip});
What you need to do is have JavaScript pass your variables to PHP, which in turn will use it in your MySQL statements (most probably via PDO in PHP).
Now, what is AJAX then? Well it is the modern way that will help you send data from JavaScript to PHP and get a response back from PHP to JavaScript WITHOUT the need to refresh or reload the page.
So in conclusion, JavaScript makes an AJAX call, that call will send data to PHP which will do something with MySQL, and then respond back to JavaScript with your results.
You need to comment out a couple of lines so that it won't be interpreted as code
//Opera 8.0+, Firefox, Safari
Your Ajax code only creates the ajax object and sets up an event listener, it never actually makes a request, so of course it cannot work. The request would look something like this
ajaxRequest.open("post", "/myphppage.php", true);
...
ajaxRequest.send("somevariable=" + variable);

inserting javascript variable into php/mysql

I have two file one is index.php another one is dbsubmit.php
In my index.php i got some javascript variable in between script tag..
var address = "Address of some places";
var latitude = 79.00256978;
var longitude = 125.89564725;
i want to pass these variables into my php script (dbsubmit.php) so that i can populate MySQL database. How can i solve this problem?? can anybody help me??
You could use something like this and than in php using $_GET you can retrieve the values
<script>
function send(url){
var request;
try{
request= new XMLHttpRequest();
} catch (e){
try{
request= new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
request= new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
return false;
}
}
}
request.onreadystatechange = function(){
if(request.readyState == 4){
//alert(request.responseText); this would be the value we get back, anything php would print would be alerted here
}
}
request.open("GET", url, true);
request.send(null);
}
send("dsubmit.php?address="+address+"&latitude="+latitude+"&longitude"+longitude);
</script>
You can use AJAX to pass the variables to a PHP script, which in turn will be able to write them to a database.
Are you using some sort of javascript framework (jQuery, etc.) ? Because they make it really easy.
You just have to make another php script to get the variables from $_GET or $_POST and save them. AJAX effectively calls the php script passing it those vars.

[HTML/PHP]: Abort refresh of page

In a Form, I am calling a PHP file if the validation passes. My Form header looks like this:
<form method="POST" action="inst.php" style="margin:0px;"name="form1" onSubmit="return CheckUsername(document.getElementById('username').value);">
</form>
The problem is that even if the validation fails, it shows a blank page in an attempt to open the PHP file, when it must remain on the same page. The PHP file contains code to access the database to check whether the user exists or not.
Is there any way to check the database for value without refreshing the page?
It is very likely that the JavaScript function has an error. The validation function will then not be executed and the form sent (!). Check Firefox's Javascript console for errors, they will appear there even if the page has already reloaded.
You should however never rely on client side validation. I would highly recommend checking in the PHP script as well.
While you should never rely upon client-side verification alone and should definitely treat all data as "dirty" in the PHP, there is another way using JavaScipt that you can prevent the browser from directly posting the form. Rather than setting the form's method and action, simply define its onsubmit function to construct an XmlHttpResponse object, set the method to POST and set data to your form.serialize(), and send the appropriate POST request. Or, if the PHP script will accept GET or REQUEST parameters, you can (after your verification) construct the URL query and simply set window.location to redirect to the PHP page with the appropriate data.
EDIT - Here is my illustration - this uses Prototype's Form.serialize function.
<form id="my_form" onSubmit="return checkUsername();">
Username: <input type="text" name="username" id="username" />
</form>
<script type="text/javascript">
var xhr; // global XMLHttpRequest object
var formElem = $('my_form'); // our form element
function checkUsername() {
var formData = formElem.serialize();
sendPOSTRequest('http://mydomain.com/mypath/myscript.php', formData);
}
function sendPOSTRequest(toURL, sendData) {
xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!xhr) {
alert('Cannot create XHR');
return false;
}
xhr.onreadystatechange = handleResponse;
xhr.open('POST', toURL, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", sendData.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(sendData);
}
function handleResponse() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var result = xhr.responseText;
// result is now whatever content was returned by the PHP script
// do whatever you want with the result here
// for example, you might have the PHP return 'true' or some such thing, and then
// change window.location, or perhaps if it returns 'false' you put up an alert('No!')
// use your imagination, go nuts
} else {
alert('The script returned an error.');
}
}
}
</script>
There are some more sophisticated ways to create and handle the XMLHttpRequest object. I might post an update later with some pointers.
Once the POST request has been sent then it is up to the browser how it handles the response, but in every browser I have come across it will display the result of the request in some for be it a message saying it recieved a response (200,404, etc), a blank page or whatever, so I'm afraid you will have to reconstruct your page and send it back to the client (complete with invalid entries in the form elements) as a response.
Its a pain, but that's how HTTP works.

Categories