How to add values to a mySQL database with JSON and AJAX? - php

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");

Related

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.

Simple example to populate database using JSON, XMLHttpRequest, and PHP file_get_contents("php://input") not working

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

Error #2007, in AS3, but it traces the correct result, when var textfield is added, it displays Null in dynamic text box

When i tried to use var textField and String(), the result display null.What i posted below, it display Error #2007 Parameter text must be non-null. Trying to pass the echoed results from mysql through php on AS3, through a few dynamic text box.
But when i switch it to Trace(event.target.data), it shows the correct Data.
Here is my AS3 code
var Mend:URLRequest = new URLRequest("http://localhost/Autoresult.php");
Mend.method = URLRequestMethod.POST;
var variablesss:URLVariables = new URLVariables();
variablesss.nobed1 = result.text;
variablesss.LoZip=result2.text;
variabless.rangelow=result3.text;
Mend.data = variablesss;
var BLoader:URLLoader = new URLLoader();
BLoader.dataFormat = URLLoaderDataFormat.TEXT;
BLoader.addEventListener(Event.COMPLETE,Candler);
BLoader.load(Mend);
// handler for the PHP script completion and return of status
function Candler(event:Event){
var seVariables: URLVariables = new URLVariables(event.target.data);
result.text=seVariables.nobed1;
result2.text=seVariables.LoZip1;
result3.text=seVariables.rangelow1;
}
Here is my php code
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
session_start();
include 'connect.php';
$_SESSION['username'];
$username=$_SESSION['username'];
$result=mysqli_query($con,"SELECT * FROM Test WHERE username = '$username'")or die( mysqli_error($con));
$solutions = array();
$check_num_rows=mysqli_num_rows($result);
while ($row = mysqli_fetch_assoc($result))
{
$solutions[0]=$row['nobed1'];
$solutions[1]=$row['LoZip1'];
$solutions[2]=$row['rangelow1'];}
echo "nobed1=.$solutions[0]&LoZip1=.$solutions[1]&rangelow1=.$solutions[2]";
?>
Thanks for your time
without looking into it too deeply, it seems like it might be a type miss-match.
you could try
var seVariables: URLVariables = new URLVariables(event.target.data + "");
that way it is converted to text
I managed to resolve my problem, changing the php, and putting the result in a string, pass it through to AS3, then split up the answer and put them into the dynamic text box.
Here is my code.
function Candler(event:Event){
var fromPhp:String = event.target.data;
var errors:Array = fromPhp.split(",");
trace(errors.length)
result.text= (errors[0].replace(/^\s+|\s+$/mg, ""));
result2.text= (errors[1].replace(/^\s+|\s+$/mg, ""));
result3.text= (errors[2].replace(/^\s+|\s+$/mg, ""));
result4.text= (errors[3].replace(/^\s+|\s+$/mg, ""));
}

Inserting Variables From Jquery Always Fails

i have some problem, i made some local website using php.
I have a file called functions.php which this is the code:
public function saveAll($idmt_salesarea, $thn_bln, $no_pesanan, $tgl_pesan, $idms_langganan, $idms_kodebarang, $quantity, $harga, $jumlah, $disc_cash, $disc_kredit){
$message = "Waiting input...";
try{
$con = new db();
$conn = $con->connect();
$query = "INSERT INTO mt_pesanan(idmt_salesarea,thn_bln,no_pesanan,tgl_pesan,idms_langganan, idms_kodebarang,quantity,harga,jumlah,disc_cash,disc_kredit) VALUES ($idmt_salesarea, '$thn_bln', '$no_pesanan', '$tgl_pesan', $idms_langganan, $idms_kodebarang, '$quantity', $harga, $jumlah, '$disc_cash', '$disc_kredit')";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn) . " " . mysqli_errno());
if($result == 1){
$message = "Success";
} else if($result == 0){
$message = "Failed";
}
}catch(Exception $exc){
echo $exc->getCode();
}
$con->disconnect();
return $message;
}
i Take the input parameter from file called: index.php and pass the parameter using AJAX Jquery. The parameter itself is sent and pointing to file called insert.php
here's the insert.php file:
<?php
include_once 'functions.php';
$idmt_salesarea = isset($_GET['salesarea']);
$thn_bln = isset($_GET['thn_bln']);
$no_pesanan = isset($_GET['nopes']);
$tgl_pesan = isset($_GET['tglpes']);
$idms_langganan = isset($_GET['idlangganan']);
$idms_kodebarang = isset($_GET['idbarang']);
$quantity = isset($_GET['quantity']);
$harga = isset($_GET['harga']);
$jumlah = isset($_GET['jumlah']);
$disc_cash = isset($_GET['disc_cash']);
$disc_kredit = isset($_GET['disc_kredit']);
if (($disc_cash == null) || ($disc_kredit == null)) {
$disc_cash = 0;
$disc_kredit = 0;
}
$insert = new functions();
$insert->saveAll($idmt_salesarea, $thn_bln, $no_pesanan, $tgl_pesan, $idms_langganan, $idms_kodebarang, $quantity, $harga, $jumlah, $disc_cash, $disc_kredit);
?>
but when i check the error, that is the variable that cannot get from insert.php file (using $_GET statement).
How proper way to gain the variable? because all the parameter is set.
I know this is combining object oriented style and old fashion php coding. Any ideas?
thanks in advance.
UPDATE
here's the index.php file using jquery ajax to sent the data
function sendAll(){
var tgl_pesan = $('#dpc').val();
var sales_area = $('#sales_area').val();
var nopes = $('#no_pesanan').val();
var thnbln = getTahunBulan();
var id_langganan = $('#kode_langganan').val();
var id_barang = $('#kode_barang').val();
var quantity = getQuantity();
var harga = $('#harga').val();
var jumlah = $('#jumlah').val();
var disc_cash = $('#cash').val();
var disc_kredit = $('#kredit').val();
var max = $('#max').val();
$.ajax({
type:"POST",
**url:"insert.php",**
data:{
salesarea:sales_area,
thn_bln:thnbln,
nopes:nopes,
tglpes:tgl_pesan,
idlangganan:id_langganan,
idbarang:id_barang,
quantity:quantity,
harga:harga,
jumlah:jumlah,
disc_cash:disc_cash,
disc_kredit:disc_kredit,
max:max
},
success:function(msg){
alert("Data Inserted");
},
error:function(msg){
alert("Data Failed to save" + msg);
}
});
the ajax itself is pointing to file insert.php which the insert.php is executing function from another file called functions.php
The problem is with this code:
$idmt_salesarea = isset($_GET['salesarea']);
$thn_bln = isset($_GET['thn_bln']);
$no_pesanan = isset($_GET['nopes']);
$tgl_pesan = isset($_GET['tglpes']);
$idms_langganan = isset($_GET['idlangganan']);
$idms_kodebarang = isset($_GET['idbarang']);
$quantity = isset($_GET['quantity']);
$harga = isset($_GET['harga']);
$jumlah = isset($_GET['jumlah']);
$disc_cash = isset($_GET['disc_cash']);
$disc_kredit = isset($_GET['disc_kredit']);
For each of those variables, you are assigning the result of isset(), which will evaluate to either TRUE or FALSE. If you want to bind the actual value of your $_GET input, change each line from this syntax:
$idmt_salesarea = isset($_GET['salesarea']);
To
$idmt_salesarea = isset($_GET['salesarea']) ? $_GET['salesarea'] : '';
However this code isn't really maintainable, and I would also recommend using arrays instead of passing that many arguments to your saveAll() method.
In response to your update
If you are sending an AJAX request with type: "POST", you cannot access your input data via the PHP $_GET super global, you have to use $_POST. However, what I said before is still valid, as you aren't binding values to your variables properly.
Although I do not get what you are saying completely, still based on your description the problem can be you sending the variable using ajax call. If the ajax call is async you might not get the value by the time you use it.
So you can either set async:false in the ajax call (which is not a good way) or trigger any thing that uses that variable from within the success callback handler of the ajax call.
It would be really helpful if you can share the piece of code which explains the following statement of yours.... "i Take the input parameter from file called: index.php and pass the parameter using AJAX Jquery. The parameter itself is sent and pointing to file called insert.php"

Capture form response in Javascript?

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);
}

Categories