Passing of JSON array to PHP file using javascript AJAX function - javascript

I am now about to give up for ajax in javascript to pass JSON array to PHP. I have first PHP file in which I have form which contains a text area and checkboxes. The snippet is below:
<form name="drugForm" onsubmit="return validateForm()" method="post">
Drug name: <input type="text" name="dname"></pre>
<pre>
<input type="checkbox" name="drug" value="one">1 <input type="checkbox" name="drug" value="two">2</br>
<input type="checkbox" name="drug" value="three">3 <input type="checkbox" name="drug" value="four">4</br></br>
<input type="submit" value="Submit">
</pre>
Here, with validateForm() call I am calling javascript to check whether text area is filled and at least a checkbox is checked. Also, it is creating array, in javascript, to get checked values. Here with this js I want to send this array to PHP file by converting it JSON using ajax. COde snippet is below:
function validateForm()
{
var x=document.forms["drugForm"]["dname"].value;
var y=document.drugForm.drug;
var y_array = new Array();
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else if (Boolean(x))
{
for(k=0;k<y.length;k++)
{
if(y[k].checked)
{
var arr_val = y[k].value;
y_array.push(arr_val);
//alert(arr_val);
}
}
$.ajax({
type: "POST",
url: "drug_form3.php",
dataType: 'json',
data: {json: JSON.stringify(y_array)},
});
alert("Check one checkbox at least");
return false;
}
}
Here, with js array is getting created and whenever I am printing values with alert, it is giving proper result. But, when I am trying to send it to next PHP file even after using json_decode in php file, it is not able to get array printed with PHP. Below is code snippet for second PHP:
<body>
<?php
$json = $_POST['json'];
$array=json_decode($_POST[$json]);
// here i would like use foreach:
print_r ($array);
echo "Its in form2 and working fine";
?>
</body>
Please guide me in this issue, how to pass json array to PHP file using javascript.

You have the following lines confused:
$json = $_POST['json'];
$array=json_decode($_POST[$json]);
Change to:
$array=json_decode($_POST['json']);

Can you try this and check whether you getting the post values here,
$json = $_POST['json'];
echo "<pre>"; print_r($json);echo "</pre>";

Try this and see if it works for you
$array = json_decode($_POST['json'], true);

Related

cannot receive js array posted with ajax

I am trying to send form data and js array to mysql database. I am having problem with receiving js array into my php. I receive data from form but not the array. I can't find the problem.
index.php
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"><!--bootstrap-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script><!--jquery-->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script><!--angular js-->
<script type="text/javascript" src="assets/js/main.js"></script>
</head>
<body>
<form method="post" action="upload.php">
<!--dynamic form created from javascript-->
<input id="submit" type="submit" value="Upload" name="submit" onclick="upload()"/>
</form>
</body>
</html>
javascript -- main.js
var objArray = []; //Array of questions
function upload(){
var jsonArray = JSON.stringify(objArray);
$.ajax({
type:'post',
url: 'upload.php',
data: { jsonData : jsonArray},
success: function(data){
console.log("success!");
}
});
} else {
console.log("no data javascript!");
}
}
upload.php
<?php
if(($_SERVER['REQUEST_METHOD'] == "POST") && (isset($_POST['submit']))){
$servername = "......";
$username = "......";
$password = "......";
$dbname = ".....";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(!empty($_POST['jsonData'])){
$json = $_POST['jsonData'];
var_dump(json_decode($json, true));
echo "<script type=\"text/javascript\">
console.log('received data');
</script>";
} else {
echo "data not received";
}
$conn->close();
}else {echo "unsecure connection";}
?>
objArray looks like this:
[{"questionId":1,"questionTypeObj":"single","options":3},{"questionId":2,"questionTypeObj":"single","options":3}]
upload.php outputs "data not received"
Your output indicates what the problem is: You get to the part where you echo data not received but you are not sending a submit key: $_POST['submit'] is not set when called through ajax.
So you are submitting your form the "normal" way and not through ajax.
This is caused by the fact that you are not cancelling the default submit action of your button.
The best way to solve that (in my opinion...), is to remove the inline javascript - the click handler - and replace your function with:
$("form").on('submit', function(e) {
// Cancel the default form submit
e.preventDefault();
// The rest of your function
var jsonArray = JSON.stringify(objArray);
...
});
Note that I am catching the form submit event. You could also replace that with the button click event but that might not work correctly when a visitor uses the enter key in a form field.
You shouldn't be doing it this way. There's no way to guarantee that the javascript will execute before you redirect. In fact, it won't run fast enough, and will just redirect to the next page. Try
<form method="post" action="upload();">
This will get the data to the page, but it won't display it. If you want it displayed you should have forms submitting it. If you post with ajax you can also try to catch the response with jquery.
when you click the button your code are going to send 2 requests to the server
First request-the ajax
this ajax request has the parameter you need jsonData : jsonArray
and right after that you are going to send another request
Second request-submitting the form
and the form has no jsonData : jsonArray paramter sent with it
you don't need this ajax at all!
all you need to do to receive the jsonData : jsonArray paramter is to send it along with the form
for example:
change your form to be like this
<form method="post" action="upload.php">
<input id="jsonData" type="hidden" name="jsonData" value="">
<input id="submit" type="submit" value="Upload" name="submit" onclick="upload()"/>
</form>
and change your button function to be like this
function upload(){
var jsonArray = JSON.stringify(objArray);
$('input#jsonData')[0].value=jsonArray ;
}
EDIT :
Or if you want upload.php to process the ajax request, and not to response with a whole document then you don't need the form, remove the form from your HTML , and just add submit:Upload to the ajax request
data: { jsonData : jsonArray, submit:"Upload" }

Correct method of sending a variable from a html form to a php function via ajax

I'm coding a voting system for multiple uploads; each uploaded image is in a foreach statement with a form attached to each, with three buttons to vote up, down or none, each associated with an INT in my mysql database.
I got it to work by submitting the form data straight to the PHP function that 'UPDATE's the database. To avoid a page refresh, I attach ajax. I got the ajax to send the two variables needed for the PHP function to update the correct "image" row and INT in the db.
Question: The ajax function works, but the PHP function doesn't seem to update.
SUSPECTED PROBLEM: I'm pretty sure it's the way I'm defining the variables in ajax that I want to pass, I was trying to grab the ID of the "image" it's handling, but I don't know how to translate this data to the PHP function so that it UPDATE's correctly.
Here's the form, javascript, and php:
// IMAGE, and rest of foreach above this, and ending after form
// This form only shows one button, there are three, each
// I'll treat the same once I get one to work
<form action="feed.php" method="post" id="vote_form_1">
// If js isn't turned on in broswer, I keep this
// hidden input, to send unique ID
<input type="hidden" name ="input_id"
class="input_id" value="<?php echo $row['id']; ?>"/>
<input type="submit" name="post_answer1" onclick="sayHi(event);"
class="answer_L" id="<?php echo $row['id']; ?>"
value="<?php echo $row['post_answerL']; ?>"/>
</form>
// end of foreach
//AJAX
<script type="text/javascript">
function sayHi(e) {
var input_id = $(e.currentTarget).attr('id');
var post_answer1 = $("input[name='post_answer1']");
jQuery.ajax({
type: 'POST',
url: 'feed.php', //name of this file
data:input_id,post_answer1,
cache: false,
success: function(result)
{
alert ('It worked congrats');
}
});
e.preventDefault();
</script>
// PHP VOTE UPDATE FUNCTION
<?php>
if(isset($_POST['post_answer1'],$_POST['input_id'])){
$current_id = $_POST['input_id'];
$vote_1 = "UPDATE decision_post set " .
"post_answer1=post_answer1+1 WHERE id = '".$current_id."' ";
$run_vote1 = mysqli_query($conn2, $vote_1);
if($run_vote1){ echo 'Success'; }
}
?>
Here a simple answer, just serialize all your form data!
$('form').submit(function(){
$.post('feed.php', $(this).serialize(), function(data){
console.log(data);
}, 'json');
return false;
});
var post_answer1 = $("input[name='post_answer1']").val();

jQuery serialize and insert in mysql

I have this code to insert some data that comes from a while, in a db. I'm trying to use jQuery serializearray and jQuery post together. But it seems I do some errors
$query= "SELECT * FROM barcode_prodotti";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo'
<input type="text" name="prodotto[]" class="prodotto" value="'.$row["prodotto"].'"></div>
<input type="text" name="prezzo[]" class="price" value="'.$row["prezzo"].'">
<input type="text" name="quantita[]" class="price" value="'.$row["quantita"].'">';
}
?>
<script src="js/mine.js"></script>
<button>Serialize form values</button>
</form>
<div id="results"></div>
This is my jQuery code I put in mine.js
$(document).ready(function(){
$('form').submit(function(msg) {
var mia =$(this).serialize();
$('#results').text(mia)
alert($(this).serialize()); // check to show that all form data is being submitted
$.post("testtest.php",$(this).serializeArray(),function(data){
alert(data);
});
return false; });
});
This is my php file (testtest.php)
mysql_connect("localhost","root","");
mysql_select_db("db");
$arr = $_POST;
$sql="INSERT INTO table VALUES(
'".$arr['prodotto']."',
'".$arr['quantita']."',
'".$arr['prezzo']."'
)";
$rssql = mysql_query($sql);
?>
So I the serialize is ok (i tried to assign in a div a value to see if it was ok), but I can't insert values in my db
Your INSERT query ends up looking like this after variable substitution.
INSERT INTO table VALUES( 'product', '123', '321')
If your table has exactly three columns this will work fine. Otherwise it will fail. You may wish to use this query instead.
INSERT INTO table (prodotto, prezzo, quantita ) VALUES( 'product', '123', '321')
which enumerates the columns where you want your data.
After doing an insert (and after any query) you should check for errors. This can be done with code like this.
$res = mysql_query($q);
if ($res === false) {
echo $mysql_error ();
}
Note well: The mysql_xxx() interface is being removed from PHP for a good reason: it is vulnerable to cybercriminals. Please adopt mysqli_xxx() or PDO as soon as possible.
The simplest way to do this:
<form id="myform" method="post">
<input type="text" name="prodotto" id="prodotto">
<input type="text" name="prezzo" id="prezzo">
<input type="text" name="quantita" id="quantita">
</form>
Jquery is pretty simple too:
var datastring = $("#myform").serialize();
$.ajax({
type: 'POST',
url: 'url/to/yourfile.php',
data: datastring
}).done(function(res){
var res = $.trim(res); //the ajax response. you can alert it or whatever...
});
You can parse the fields in the ajax file like that:
yourfile.php
<?php
$product = mysql_real_escape_string($_POST["prodotto"]);
$prezzo = mysql_real_escape_string($_POST["prezzo"]);
$quantity = mysql_real_escape_string($_POST["quantita"]);
//here you have the variables ready to add them as values to database
$ins = "INSERT INTO table (prodotto, prezzo, quantita ) VALUES( 'product', '123', '321')";
mysql_query($ins);
?>

How to post data without a form

Good day sir/ma'am I am a new programmer, I would like to ask how to post data like the functionality of form that when submitting the form the URL in action will display using javascript.
"WITHOUT USING A FORM" or using xmlHTTP that not return to main page
sample is
HTML
<input type="button" value="revise" onclick="revisetask(<?php echo $id; ?>)">
JS
function revisetask(idtask)
{
//In this function sir i would like to post here
}
Im very sorry if my english is too bad.. thanks in advance :D
You can use javascript for submitting the values of input boxes,
to do so,
write a javascript function which will read all your input boxes values into javascript variables,
Prepare a URL, and call that URL using window.location.href
function SubmitMyForm
{
var Firstname = document.getElementbyId('FirstName').value;
var Lastname = document.getElementbyId('LastName').value;
var URL="myDBoperations.php?firstname="+Firstname+"&lastname="+Lastname;
window.location.href= URL;
}
On the operations form you will receive these value in GET.
Hope this will help you.
U can use ajax for this. U don't need a form for ajax post, and it won't refresh the page too.
Below is an example code
<input type="text" id="test_name" />
<input type="button" value="Submit" obclick="save_this()" />
<script type="text/javascript">
function save_this(){
var text = $('#test_name');//stores te value in text field
$.ajax({
url: 'http://example.com/test.php',//your URL
type: 'POST',
data: { text: text },
success: function(data){
alert(data);
}
});
}
</script>
test.php
<?php
echo $_POST['text'];
As I've seen in this code:
<input type="button" value="revise" onclick="revisetask(<?php echo $id; ?>)">
I assume and believe that the reason why you don't want to use form because you want your $id to be submitted through javascript/jquery. But alternatively, you could just do it this way:
HTML:
<form method = "POST" action = "updatetask.php">
<input type = "hidden" value = "<?php echo $id; ?>" name = "taskid" id = "taskid"/>
<input type = "submit" value = "UPDATE" name = "updatebutton">
</form>
PHP:
<?php
$taskid = $_POST['taskid'];
?>
In the above code I just set the type hidden and which contains the value of your $id in which would be post in your Php file.
UPDATE:
If it still doesn't fit to what you want then you could just have this other alternative which will be using the GET method: <a href = "updatetask.php?id='<?php echo $id; ?>' REVISE </a>"
That's the only option you have. and if you don't want to show the id in your url then you could just use URL Rewriting (refer to this link: https://www.addedbytes.com/articles/for-beginners/url-rewriting-for-beginners/)
Hope this helps.

getting form value from the same php page

I have a database and I get info from it and put it into php page. BUT the thing is, I cant put data from that php file to database. I use form to put there the value of variable, but it says [html span element]. and I get errors:
Notice: Undefined index: souls in xxx/the_cave.php on line 20
Notice: Undefined index: bones in xxx/the_cave.php on line 21
Here is the code:
JS:
document.getElementById("souls_form").value=<?php echo $souls_value; ?>;
document.getElementById("bones_form").value=<?php echo $bones_value; ?>;
function upload(){
<?php upload(); ?>}
PHP part:
$current_souls=$_POST['souls'];
$current_bones=$_POST['bones'];
function upload(){
mysqli_query($db,"UPDATE Data SET Souls=$current_souls, Bones=$current_bones WHERE Username='$username'");
HTML form
<form style="visibility:hidden" action="" method="post">
<input name="souls" id="souls_form">
<input name="bones" id="bones_form">
</form>
UPDATED CODE
<script>
var souls1=<?php echo $souls_value;?>
var bones1=<?php echo $bones_value;?>
//do your process
//after the values changes for variables souls1,bones1
//YOU HAVE TO CALL AJAX CALL TO SAVE YOUR UPDATED VARIABLES DATA INTO DB
$.ajax({
url:'updatedata.php',
type:"POST",
data:{souls:souls1,bones:bones1},
success:function(result)
{
if(result)
{
alert('updated succesfully');
}
}
});
updatedata.php
<?php
if(isset($_POST['souls'])&&isset($_POST['bones']))
{
$current_souls=$_POST['souls'];
$current_bones=$_POST['bones'];
if(mysqli_query($db,"UPDATE Data SET Souls='$current_souls', Bones='$current_bones' WHERE Username='$username'"))
{
echo 'TRUE';
}
}
?>
As the Php code executes first than all other codes, the $current_souls=$_POST['souls']; is executing first so you have to check form submission using isset() other wise no error will be printed

Categories

Resources