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));
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'm working with the coordinates. I don't want to use a GeoIP database. So I tried first to get the coordinates, then send them with a post to a php file which write them in an html file.
This is the index.html code:
<p> Hello. </p>
<script type="text/javascript">
$.get("http://ipinfo.io", function (response) {
var ip = response.ip;
var city = response.city;
var region = response.region;
var details = JSON.stringify(response, null, 4);
$.ajax({
type: "POST",
url: 'write.php',
data: '&ip='+ ip + '&city=' + city + '®ion=' + region + '&details=' + details,
success: function (data) {
alert("Sent!");
},
error: function(jqXHR, text, error){
alert("Error: not sent.");
}
});
}, "jsonp");
this is the write.php code:
<?php
$ip = $_POST['ip'];
$city = $_POST['city'];
$region = $_POST['region'];
$details = $_POST['details'];
$fh = fopen('lol.html', 'a') or die("can't open file");
fwrite($fh,'IP: $ip ;');
fwrite($fh,'Details: $details');
fclose($fh);
echo "Created";
?>
If I host and open index.html it alert "Sent!". But then, when I open lol.html I see the string: IP: $ip ;Details: $details
Why? What am I doing wrong?
This is because you are trying to use variables inside single quotes ' when writing data; so the variables aren't getting evaluated but instead being treated as literals.
So, try this instead:
<?php
// Parse input
$ip = isset($_POST['ip']) ? $_POST['ip'] : '';
$city = isset($_POST['city']) ? $_POST['city'] : '';
$region = isset($_POST['region']) ? $_POST['region'] : '';
$details = isset($_POST['details']) ? $_POST['details'] : '';
// Open file for writing
$fh = #fopen('lol.html', 'a');
if (!$fh) exit('Failed to open file for writing')
// Write data
fwrite($fh, "IP: $ip\r\n");
fwrite($fh, "Details: $details");
// Finished
fclose($fh);
echo "Created";
?>
Update
Based on your comment, I have optimised this script into the following, try this out:
index.html (or what ever .html file)
<p> Hello. </p>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$.getJSON('http://ipinfo.io', function(response) {
$.post('write.php', { response: JSON.stringify(response) })
.done(function(result) {
alert(result);
});
});
</script>
write.php
<?php
// Parse input
$response = isset($_POST['response']) ? $_POST['response'] : '';
// Decode input
$response = #json_decode($response, true);
if (!$response) {
exit('Invalid input.');
}
// Open file for writing
$fh = #fopen('lol.html', 'a');
if (!$fh) {
exit('Failed to open file for writing.');
}
// Write data
$result = '<pre>';
foreach ($response as $key => $value) {
$result .= "$key = $value\r\n";
}
$result .= '</pre>';
fwrite($fh, $result);
// Finished
fclose($fh);
echo "Created";
?>
The resulting lol.html file will now look like this (when index.html is executed):
<pre>ip = 90.152.2.38
hostname = host90-152-2-38.ipv4.regusnet.com
city = St Albans
region = England
country = GB
loc = 51.8379,-0.4399
org = AS8220 COLT Technology Services Group Limited
postal = AL3
</pre>
And if you were to open this lol.html file in browser, it will render like this:
Is this what you are after?
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);
}
How does xhr.upload.addEventListener("error", failed, false) differ from me having $success = move_uploaded_file($tmp_name, $name); if $(success) { echo "0" } else { echo "1" }? Is this unnecessary redundancy?
function uploadPHP() {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", updateProgress, false);
xhr.upload.addEventListener("load", complete, false);
xhr.upload.addEventListener("error", failed, false);
xhr.upload.addEventListener("abort", cancelled, false);
var foo = document.getElementById("uploadScreen");
var form = document.getElementById("uploadForm");
var percentComplete;
var index;
xhr.onreadystatechange = function () {
if (xhr.readyState == 1){
}
--
function cancelled() {
//cancel
}
}
localhost file_server # cat php/upload.php
<?php
//
//require_once('PhpConsole.php');
//PhpConsole::start();
$tmp_name = $_FILES['file1']['tmp_name'];
$path = "/trunk";
$name = $path . DIRECTORY_SEPARATOR . $_FILES['file1']['name'];
$success = move_uploaded_file($tmp_name, $name);
if ($success) {
echo "0";
} else {
echo "1";
}
?>
"error" occurs if your request doesn't get through, for example if it times out.
Say you need to validate some data. If it is invalid, the "error" event won't occur unless you throw an uncaught exception in your PHP. Instead, it will simply return some data that indicates the values were invalid, for example the string "0".
In your given example, it is entirely possible for the move_uploaded_file to fail, yet the error handler won't trigger because technically the request completed without untoward incident. The only indication you will have of the action you wanted to take having failed will be the "0" response.
I'm trying to make my xml file URL dynamic so multiple people can be using my site and querying data at once. I order to do so I'm inserting a random number php variable in front of my xmlfile. For some reason I'm having issues creating and writing xml files when trying to use this variable. When I use a static URL like 'wine.xml' it works fine.
$fp = fopen($randnumb.'wine.xml', 'w');
fwrite($fp, $string);
fclose($fp);
I might be wrong (so any one let's correct me) if you have an xml and want to allow many people to read it why do you have to make multiple copies of it?!
Isn't the server supposed to do this job serving a file to many peple? If I am wrong and there is something else you try to then this php only works okay. This way you don't have to look for errors in php.
<?php
$fileName = rand().'file.xml';
$fp = fopen($fileName, 'w');
fwrite($fp, 'Hello!');
fclose($fp);
?>
<?php
$handle = fopen($fileName, "rb");
$contents = fread($handle, filesize($fileName));
print_r($contents);
fclose($handle);
?>
var winexml=loadXMLDoc("<?=$randnumb?>wine.xml");
Does <? work for you? cause wamp asks <?PHP (must be the php.ini)
Why do you have a second = in the loadxmldoc parameters?!
Does this work:
<?PHP
$dbq="\"";
echo 'var winexml=loadXMLDoc(',$dbq,$randnumb,'wine.xml',$dbq,');';
?>
Okay I see. I don't know what is you preference of final xml file display, however this scripts has stuff that might let you have your job done, just adjust it to your needs.
index.html and getXml.php
<html>
<head>
<script type="text/javascript">
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
</script>
<script type="text/javascript">
var fileOption;
var fileName;
function runPhp(makeFile)
{
var url = "getXml.php";
fileOption = makeFile;
var params = "makeFile=" +makeFile+"";
request.open("POST", url, true);
//Some http headers must be set along with any POST request.
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = updatePage;
request.send(params);
}////////////////////
function getXml( )
{
if(fileName==null){alert('please click create file first');return;}
var url = fileName;
var params = null;
request.open("POST", url, true);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = displayFile;
request.send(params);
}////////////////////
//You're looking for a status code of 200 which simply means okay.
function updatePage() {
if (request.readyState == 4) {
if (request.status == 200)
{
if(fileOption==1)
{fileName=request.responseText; return;}
document.getElementById('divResults').innerHTML=request.responseText;
document.getElementById('textareaResults').innerHTML=request.responseText;
}
else{
//alert("status is " + request.status);
}
}
}
function displayFile() {
if (request.readyState == 4) {
if (request.status == 200)
{
document.getElementById('textareaResults').innerHTML=request.responseText;
document.getElementById('divResults').innerHTML='File loaded in text area above.';
}
else{
//alert("status is " + request.status);
}
}
}
</script>
</head>
<body >
<span style="background-color:blue;color:yellow;"
onClick="runPhp(0)"/>
Click for Xml Results.<br>
(<font color=pink>I prefer this one!!!</font>)
</span><br><br>
<span style="background-color:blue;color:yellow;"
onClick="runPhp(1)"/>
Click to create an xml file.<br>
</span>
<span style="background-color:blue;color:yellow;"
onClick="getXml(1)"/>
Click to read the xml file.<br>
</span>
<textarea rows="10" cols="88" id="textareaResults">
</textarea>
<br><br>
<pre><div id="divResults"></div></pre>
<br><br>
</body>
</html>
<?PHP
mysql_connect('localhost', 'root','');
mysql_select_db("mysql");
$query="select * from help_category;";
$resultID = mysql_query($query ) or die("Data not found.");
$xml_output = "<?xml version=\"1.0\"?>\n";
$xml_output .= "<records>\n";
for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){
$row = mysql_fetch_assoc($resultID);
$xml_output .= "\t<record>\n";
$xml_output .= "\t\t<help_category_id>" . $row['help_category_id'] . "</help_category_id>\n";
$xml_output .= "\t\t<name>" . $row['name'] . "</name>\n";
$xml_output .= "\t\t<parent_category_id>" . $row['parent_category_id'] . "</parent_category_id>\n";
$xml_output .= "\t</record>\n";
}
$xml_output .= "</records>";
if($_POST['makeFile']==0)
echo $xml_output;
else
{
$fileName = rand().'file.xml';
$fp = fopen($fileName, 'w');
fwrite($fp, $xml_output);
fclose($fp);
$dbq="\"";
echo $fileName;
}
?>