Let say I submit data to a form with the following code
var xhr = new XMLHttpRequest(), formData = new FormData();
formData.append("img", img);
formData.append("user", localStorage["username"]);
formData.append("pass", localStorage["password"]);
xhr.onreadystatechange = function (event) {
if (xhr.readyState === 4 && xhr.status === 200) {
var value = xhr.responseText; // value should equal "1234"
alert( "value = " + value );
}else{
alert("none");
}
};
xhr.open("POST", "http://joubin.me/uploads3/upload_file.php", true);
xhr.send(formData);
After upload.php is done, it redirects to another page called giveid.php and the only thing it displays is a text string with an id
say 1234
How can I with javascript capture this exact id.
Keep in mind, a different upload.php redirect will have a different id number on giveid.php?
I looked into the xmlhtml responses and could not figure it out.
Here is what form goes
$password = $_REQUEST['pass'];
$username = $_REQUEST['user'];
$image = $_REQUEST['img'];
echo $password;
echo "<br/>";
echo $username;
echo "<br/>";
echo $image;
$con = mysql_connect("localhost","ya","right");
if (!$con)
{
die('Could not connect: ' . mysql_error());
echo "could not connect";
}
$asql = "SELECT * FROM `ashkan`.`users` where user='$username' and pass='$password';";
$result = mysql_query($asql);
echo $result;
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
echo $count;
echo 11;
if($count == 1){
$sql = "INSERT INTO `ashkan`.`goog` (`user`, `pass`, `img`) VALUES ('$username', '$passwo$
}
mysql_query($sql);
mysql_close($con);
header( 'Location: giveid.php' ) ;
and here is the content of giveid.php
1234
Any help would be great.
Thanks
You need to use xhr.onreadystatechange to retrieve the response from the server.
Something like this might work.
var value;
var formData = new FormData();
formData.append("img", img);
formData.append("user", localStorage.username);
formData.append("pass", localStorage.password);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (event) {
if (xhr.readyState === 4 && xhr.status === 200) {
value = xhr.responseText; // value should equal "1234"
alert( "value = " + value );
}
};
xhr.open("POST", "upload.php", true);
xhr.send(formData);
Info Here: http://www.tizag.com/ajaxTutorial/ajaxxmlhttprequest.php
Remember that header() must be called before any actual output is sent. So get rid of all the echos you have in the php file. Once you echo then that starts the output buffer for the response to the client.
Info Here: http://php.net/manual/pt_BR/function.header.php
I think this should be your only echo on the php page.
echo include( 'giveid.php');
Try using Google Chrome Dev Tool Network tab to view the response from your php webpage.
Launch Google Chrome,
Hit f12,
Click the network tab,
reload your page,
click on the ajax response page,
click preview to view the response.
Info Here: https://developers.google.com/chrome-developer-tools/docs/network
xhr documentation
Get xhr.response then parse it.
We usually return a json string so js can parse it easily.
googled xhr example
something like this:
xhr.onreadystatechange=function()
{
if (xhr.readyState!=4 || xhr.status!=200)
return;
var resp = xhr.responseText;
var parsed = eval(resp);
}
Related
Now I know this has been asked before, but none of the responses have offered up insight for me to date;
I have an HTML page with the script below (ultimately I shall use this script to suck data out of an app), basically testing to send some data in JSON format to a PHP page which is to populate a MYSQL database with the record.
My problem is that I get no table record update. Nada.
This has been messing me around for a few weeks now; the closest I have got is:
Send JSON data from Javascript to PHP?
My limited success to date has been to grab data from a .json file and update the database that way on a php page. So, the JSON is fine in the script, and the connection to the database is ok. I just don't seem to be able to pass it from an html page to php and populate the db. I cannot understand why this has to be that difficult.
Any suggestions/pointers would be appreciated (I need to keep this simple as I am a relative novice). Thank you in advance.
HTML page script
<script>
var jsonQuizData = {};
var qID = '9';
var learnersName = 'Bart Bundy';
var learnersEmail = 'bbundy#blue.com';
var quizName = 'SomeQuiz99';
var quizScore = '33%';
var result1 = 'Some blob data goes in here?';
var dbString, request;
jsonQuizData = '{ "id":qID, usersName":learnersName, "usersEmail":learnersEmail, "quizTitle":quizName, "qScore":quizScore, "Output1":result1 }';
dbString = JSON.stringify(jsonQuizData);
request = new XMLHttpRequest();
request.open("POST", "process.php", true);
request.setRequestHeader("Content-Type", "application/json");
request.send(dbString);
</script>
process.PHP page
<?php
header("Content-Type: application/json; charset=UTF-8");
//Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection etc. performed here
$data = json_decode(file_get_contents("php://input"));
$id = $data['id'];
$name = $data['usersName'];
$email = $data['usersEmail'];
$qtitle = $data['quizTitle'];
$result1 = $data['Output1'];
$qScore = $data['score'];
//insert into mysql table
$sql = "INSERT INTO quiz01(quiz_id, quiz_title, fName, eMail, quiz_score, q1_answer)
VALUES('$id', '$qtitle', '$name', '$email', '$qScore', '$result1')";
if(!mysqli_query($conn,$sql))
{
die('Error : ' . mysqli_error($conn));
}
else
{
echo "Data inserted successfully";
}
//Close connection
/?>
.... Brick wall time
Your stringify portion in your sample is not right, it's already a string, so I think you mean to do:
var jsonQuizData = {};
var qID = '9';
var learnersName = 'Bart Bundy';
var learnersEmail = 'bbundy#blue.com';
var quizName = 'SomeQuiz99';
var quizScore = '33%';
var result1 = 'Some blob data goes in here?';
var dbString, request;
// Here you have to stringify the data object, not a string of the data object.
jsonQuizData = JSON.stringify({"id":qID, "usersName":learnersName, "usersEmail":learnersEmail, "quizTitle":quizName, "qScore":quizScore, "Output1":result1});
request = new XMLHttpRequest();
request.open("POST", "process.php", true);
// Send the regular form header
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
// Now when it sends, it should send it properly as a post
request.send('json='+jsonQuizData);
Then in the PHP, you don't need to send the line:
header("Content-Type: application/json; charset=UTF-8");
and you can alter this line:
$data = json_decode(file_get_contents("php://input"));
to just:
$data = json_decode($_POST['json'],true);
It should now all be in the regular $_POST, then you need to bind parameters when you insert.
Update:
Right, got it working doing the following:
HTML page
<script>
var jsonQuizData = {};
var learnersName = 'Professor T';
var learnersEmail = 'prof.teerlink#pooh.com';
var quizName = 'TidlyWinks101w';
var quizScore = '100%';
var result1 = 'Balls said the crow';
var dbString, request;
jsonQuizData = JSON.stringify({"quizTitle":quizName, "usersName":learnersName, "usersEmail":learnersEmail, "qScore":quizScore, "Output1":result1 });
$(document).ready(function()
{
$("button").click(function()
{
$.post("working01.php", 'json='+jsonQuizData,
function(data,status)
{
//alert("Data: " + data + "\nStatus: " + status);
document.getElementById("AV1").innerHTML = data;
});
});
});
</script>
And PHP page...
<?php
//Set up connections to database etc...
if (isset($_POST['json']))
{
$str = $_POST['json'];
$contents = json_decode($str);
$qtitle = $contents->quizTitle;
$name = $contents->usersName;
$email = $contents->usersEmail;
$qScore = $contents->qScore;
$result1 = $contents->Output1;
}
$sql = "INSERT INTO quiz01(quiz_title, fName, eMail, quiz_score, q1_answer)
VALUES('$qtitle', '$name', '$email', '$qScore', '$result1')";
if(!mysqli_query($conn,$sql))
{
die('Error : ' . mysqli_error($conn));
}
else
{
echo "Data inserted successfully";
}
//Close connections
?>
But so want to do it utilising the XMLHttpRequest() object and send the json.
as per Rasclatt. Thanks
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
Hi i have a requirement where i need to execute mysql queries once user will confirm Ok from confirmation box.In my case what ever data i am passing to insert_details.php is not working. one more thing i would like to bring to your notice that i need to send data to different script and navigate it to different page.kindly suggest where is the problem?
<script type="text/javascript">
var r=confirm("This email address already exits in our database. Do you want to continue?");
if (r==true)
{
var dataObj = {
fname : document.getElementById('fname').value,
phone : document.getElementById('phone').value,
pemail : document.getElementById('email').value
}
var xhr = new XMLHttpRequest();
xhr.open("POST","insert_details.php", true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.send(JSON.stringify(dataObj));
xhr.onreadystatechange = function() {
if (xhr.readyState>3) {
window.location = 'http://localhost/myproject/test.php?eid=<?php echo $primary_email; ?>';
}
}
alert("test");
}
else
{
window.location = 'http://localhost/myproject/registration_request.php'
}
</script>
code in insert_details.php
$date = "Date:" . date("d/m/Y h:i:s") . "\n"; //to get today's date and time
$logfile = "testing";
$fpath ="myproject/";
$filepath = $fpath .$logfile . '-log-' . date('Y-m-d') . '.csv'; //path of error log file
$fh1 = fopen($filepath, 'a') or die("can't open file"); //opening the error log file
fwrite($fh1, "******************index*******************" . "\n");
fwrite($fh1, $date);
$test=json_decode(file_get_contents('php://input'));
fwrite($fh1, $test[0]);
You are not sending up a named pair. You are just sending up the value of the textbox.
what is looks like as a string.
xhr.send("myEmail#example.com");
Second you have a race condition between the Ajax call and the window.location.href.
You need to wait for the response to come back before doing the redirection.
Basic idea:
var dataObj = {
fname : document.getElementById('fname').value,
phone : document.getElementById('phone').value,
pemail : document.getElementById('email').value
}
xhr.onreadystatechange = function() {
if (xhr.readyState>=3) {
window.location = 'http://localhost/myproject/test.php?eid=<?php echo $primary_email; ?>';
}
}
xhr.send(JSON.stringify(dataObj));
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>
";
}
?>
I have a page that dynamically creates (using jQuery) Input boxes for the user. The user can then enter values in each input box he created. On clicking the save button a call is made to a javascript function that iterates through all the input boxes user created and sends these values using an XMLHttpRequest to the process.php file which inserts these values into the DB.
This code works fine if i send only one Request at a time. But if i loop it and send the value from each box on each iteration (means, send multiple requests using loop), only the last Request finds success. All the other calls except the last call gets aborted (found it using firebug).
Any idea why is this happening?
My code:
<script>
function saveTimeSlots(){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}
catch(e){
alert('Issue with browser.')
}
ajaxRequest.onreadystatechange = function(){
if( ajaxRequest.readyState==4 ){
alert(ajaxRequest.responseText); //This returns empty except for last call
}
}
var timeSlots = document.getElementById('formSlots').childNodes;
var date = $.datepicker.formatDate('dd-mm-yy', new Date($('#datepicker').datepicker("getDate")));
for(j=0; j<timeSlots.length; ++j){
var time = timeSlots[j].getElementsByTagName("input")[0].value;
var status = 1;
var queryString = "?date=" + date + "&time=" + time + "&status=" + status;
ajaxRequest.open("GET", "process.php" + queryString, true);
ajaxRequest.send(null);
}
}
</script>
<input type="button" value="Save time slots" class="custom-button" onclick="saveTimeSlots()"/>
Following is the code of process.php
<?php
mysql_connect( $dbhost,$user,$pwd );
mysql_select_db( $dbase ) or die( mysql_error() );
$date = mysql_real_escape_string( $_GET['date'] );
$time = mysql_real_escape_string( $_GET['time'] );
$status = mysql_real_escape_string( $_GET['status'] );
$query = "INSERT INTO time_slots (`date`,`time`,`status`) VALUES ('" . $date . "','" . $time . "'," . $status . ")";
echo $query;
if( mysql_query( $query ) ){
echo "Success";
}else{
echo mysql_error();
}
mysql_close();
}
?>
This is what Firebug shows:
GET http://localhost/process.php?date=24-06-2012&time=1&status=1 Aborted
GET http://localhost/process.php?date=24-06-2012&time=2&status=1 Aborted
GET http://localhost/process.php?date=24-06-2012&time=3&status=1 200 OK 31ms
You cannot use an instance of XMLHttpRequest for more than one request. Create a new instance for each request.
Since you're already using jQuery, I recommend to use $.ajax (or $.get) to fetch the request.
function saveTimeSlots(){
$('#formSlots').children().each(function() {
var time = $(this).find('input:first').val();
var status = 1;
var queryString = "?date=" + date + "&time=" + time + "&status=" + status;
$.get("process.php" + querystring, function(responseText) {
alert(responseText);
});
});
}
You are using the same XMLHttpRequest object for all the requests, so as soon as you start the request, the next one starts another request on it which aborts the previous one.
Make a new XMLHttpRequest object for each request or just use jQuery's ajax. It's not good to have jQuery and not use it.