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.
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 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
Currently blank rows are being entered into my mySQL database. Undefined index is what I'm getting for Name and Address in the PHP. I'm using the javaScript code as part of a function. The user will activate this function and this adding to the database will happen seemless behind the scenes.
How can I get the values to enter the mySQL.
PHP Code,
<?php
$connection = mysqli_connect("localhost", "user", "pass", "db");
$name = $_POST['Name'];
$address = $_POST['Address'];
mysqli_query($connection,"INSERT INTO offerSelected (Id, Url) VALUES ('".$name."','".$address."')");
?>
JavaScript
var name = "John";
var address = "UK";
var sendInfo = {
Name: name,
Address: address
};
var params = JSON.stringify(sendInfo);
alert(params);
var httpSend = new XMLHttpRequest();
var php = "http://server/~name/folder/insertOffer.php";
httpSend.open("POST", php, true);
httpSend.onreadystatechange = function()
{
if(httpSend.readyState == 4 && httpSend.status == 200) {
alert("sent");
}
}
httpSend.send(params);
UPDATED
var params = 'Name=' + name + '&Address=' + address;
alert(params);
var httpSend = new XMLHttpRequest();
var php = "http://server/~name/folder/insertOffer.php";
httpSend.open("POST", php, true);
httpSend.onreadystatechange = function()
{
if(httpSend.readyState == 4 && httpSend.status == 200) {
alert("h");
}
}
httpSend.send(params);
Apart from the SQL injection problems people mentioned in the comments, the problem with your code is JSON.stringify. The POST parameters use a key-value format just like GET requests, which means your params should look like this:
Name=name&Address=address
And not a JSON object. You also have to add this line of code after httpSend.open to tell the server that you are sending key/values:
httpSend.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
I'm currently trying to make a email verification sender in case an individual didn't receive the email to verify their account. Where my issue comes in is that I have to echo the individuals email into javascript (along with their name and other things). I don't want individuals to open the source code and see that their email is there within javascript, is there a way that I can encrypt this json encode? Here is my script for
Verification.php
<script type="text/javascript">
$(document).ready(function() {
$("#cliq").click(function() {
//get input field values
var ndxr = <?php $to_Email = $_SESSION['SESS_CONTROL_EMAIL']; echo json_encode($to_Email); ?>;
var fvje = <?php $vcode = $_SESSION['SESS_CONTROL_VCODE']; echo json_encode($vcode); ?>;
var name = <?php $name = $_SESSION['SESS_CONTROL_FIRST']; echo json_encode($name); ?>;
var proceed = true;
if(proceed)
{
post_data = {'ndxr':ndxr, 'fvje':fvje, 'name':name};
$.post('verifye.php', post_data, function(response){
if(response.type == 'error')
{
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
});
});
</script>
And here is the verification page Verifye.php
$name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["ndxr"], FILTER_SANITIZE_EMAIL);
$vcode = filter_var($_POST["fvje"], FILTER_SANITIZE_STRING);
Any way of preventing the user's email from displaying?
Don't display it at all! If all this data is present in your session, there's no need to pass it to the user in the first place — the script that you're POSTing to from AJAX can pull that data out of the session itself.
the way I would do this is by using base64_encode function and the base64_decode function on the other end.
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);
}