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.
Related
Sorry for disturbing again with my very basic question. First of all, sorry if my English is a little bit hard to understand. My current situation is I want to do a popup modal in my drag and drop boxes. In my popup modal, I can view and edit the details of the user based on what we click in the button in the box. The problem is, I cannot SELECT the data by id. But, when I SELECT all the data, the data appear in the modal boxes. But, it appears all the data. I just want the selected id. Back to my question for past few days, I've redo again to get more understanding on this popup modal part. I've done ajax and a little bit JavaScript, also, I tried to debug my code just what I've been told but I got an error saying "Parameter is missing" . What is causing by that ? I've done some reading about parameter but I still don't get the actual understanding about it. Can someone give an idea what is actually parameter is missing . And what I suppose to do by it?
Here what I've tried so far.
This is the button
<button data-id="<?php echo $row['userid'];?>" data-target="doubleClick-1" class='jobinfo' type='button' id='btnInfo' ondblclick="document.getElementById('doubleClick-1').style.display='block'">Info</button>
This is the modal popup
<div id="doubleClick-1" class="modal">
<label class="tabHeading">User Info</label>
<div class="contentTechJobInfo">
<div class="tech-details">
<div class="techClose" onclick="document.getElementById('doubleClick-1').style.display='none'" >×</div>
</div>
</div>
</div>
</div>
<script type='text/javascript'>
$(document).ready(function() {
$('.jobinfo').click(function() {
var userid = $(this).data('userid');
// AJAX request
$.ajax({
url: 'ajaxhome.php',
type: 'post',
data: {userid: userid},
success: function(response) {
// Add response in Modal body
$('.tech-details').html(response);
// Display Modal
$('#doubleClick-1').modal('show');
}
});
});
});
</script>
This my ajaxhome.php
<?php
$connection = mysqli_connect("", "", "");
$db = mysqli_select_db($connection, '');
if (!isset($_GET['userid'])) {
die("Parameter is missing!");
}
$userid = intval($_GET['userid']);
$query = "SELECT * FROM user WHERE userid ='$userid'";
$query_run = mysqli_query($connection, $query);
if ($query_run) {
while ($row = mysqli_fetch_array($query_run)) {
?>
<div class="input-box">
<label for="">Name</label>
<input type="text" id="username" name="username" value="<?php echo $row['username']?>">
</div>
<div class="input-box">
<label for="">Number</label>
<input type="text" id="usernumber" name="usernumber" value="<?php echo $row['usernumber']?>">
</div>
<div class="input-box">
<label for="">Class</label>
<input type="text" id="userclass" name="userclass" value="<?php echo $row['userclass']?>">
</div>
<button type="submit" id="submit" name="update" class="btn btn-primary"> Update Data </button>
<?php
if (isset($_POST['update'])) {
$username = $_POST['username'];
$usernumber = $_POST['usernumber'];
$userclass = $_POST['userclass'];
$query = "UPDATE user SET username='$username', usernumber='$usernumber', userclass='$userclass' WHERE userid='$userid'";
$query_run = mysqli_query($connection, $query);
if ($query_run) {
echo '<script> alert("Data Updated"); </script>';
header("location:homepage.php");
} else {
echo '<script> alert("Data Not Updated"); </script>';
}
}
} ?>
<?php
}
?>
In short, I think the problem comes from these lines of code in your modal:
var userid = $(this).data('userid');
you should replace it with
var userid = $(this).data('id'); // you should pass 'id' to .data() function instead of 'userid'
With your current code userid variable in your modal will always be undefined. It means it wont exist in $_GET when you send ajax request to PHP. And it causes your ajaxhome.php moves to die("Parameter is missing!");.
To get data-xxx attribute with jQuery, you should use pass 'xxx' to .data() function.
var xxx = $(this).data('xxx');
In your button, you are storing userid in data-id attribute
<button data-id="<?php echo $row['userid'];?>"
so if you need to get that userid you should pass 'id' into .data() function
Update:
In your ajax, you are using type: 'post', so in your php code you should check $_POST instead of $_GET
I don't think the value of user has been obtained
var userid = $(this).data('userid');
you can try
var userid = $(this).data('id');
I'm having an issue. When I hit submit, my form values are sent to the database. However, I would like the form to both send the value to the database and execute my script, as said in the title.
When I hit submit button, the form is sent to the database and the script remains ignored. However, if I input empty values into the input areas, the javascript is executed, and does what I want (which is to show a hidden < div >), but it's useless since the < div > is empty, as there is no output from the server.
What I want is:
submit button -> submit form -> javascript is executed > div shows up > inside div database SELECT FROM values (which are the ones added through the submitting of the form) appear.
Is this possible? I mean, to mix both PHP and JavaScript like this?
Thanks in advance.
By two ways, You can fix it easily.
By ajax--Submit your form and get response
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //action
data: form.serialize(), //your data that is summited
success: function (html) {
// show the div by script show response form html
}
});
});
First submit your from at action. at this page you can execute your script code .. At action file,
<?php
if(isset($_POST['name']))
{
// save data form and get response as you want.
?>
<script type='text/javascript'>
//div show script code here
</script>
<?php
}
?>
hers is the sample as I Comment above.
In javascript function you can do like this
$.post( '<?php echo get_site_url(); ?>/ajax-script/', {pickup:pickup,dropoff:dropoff,km:km}, function (data) {
$('#fare').html(data.fare);
//alert(data.fare);
fares = data.fare;
cityy = data.city;
actual_distances = data.actual_distance;
}, "json");
in this ajax call I am sending some parameters to the ajaxscript page, and on ajaxscript page, I called a web service and gets the response like this
$jsonData = file_get_contents("https://some_URL&pickup_area=$pickup_area&drop_area=$drop_area&distance=$km");
echo $jsonData;
this echo $jsonData send back the data to previous page.
and on previous page, You can see I Use data. to get the resposne.
Hope this helps !!
You need ajax! Something like this.
HTML
<form method='POST' action='foobar.php' id='myform'>
<input type='text' name='fname'>
<input type='text' name='lname'>
<input type='submit' name='btnSubmit'>
</form>
<div id='append'>
</div>
jQuery
var $myform = $('#myform'),
$thisDiv = $('#append');
$myform.on('submit', function(e){
e.preventDefault(); // prevent form from submitting
var $DATA = new FormData(this);
$.ajax({
type: 'POST',
url: this.attr('action'),
data: $DATA,
cache: false,
success: function(data){
$thisDiv.empty();
$thisDiv.append(data);
}
});
});
And in your foobar.php
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$query = "SELECT * FROM people WHERE fname='$fname' AND lname = '$lname' ";
$exec = $con->query($query);
...
while($row = mysqli_fetch_array($query){
echo $row['fname'] . " " . $row['lname'];
}
?>
That's it! Hope it helps
You can use jQuery ajax to accomplish it.
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //url where the form is to be submitted
data: data, //your data that is summited
success: function () {
// show the div
}
});
});
Yes, you can mix both PHP and JavaScript. I am giving you a rough solution here.
<?php
if(try to catch submit button's post value here, to see form is submitted)
{
?>
<script>
//do javascript tasks here
</script>
<?php
//do php tasks here
}
?>
Yes, This is probably the biggest use of ajax. I would use jquery $.post
$("#myForm").submit(function(e){
e.preventDefault();
var val_1 = $("#val_1").val();
var val_2 = $("#val_2").val();
var val_3 = $("#val_3").val();
var val_4 = $("#val_4").val();
$.post("mydbInsertCode.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// Form values are now available in php $_POST array in mydbInsertCode.php - put echo 'success'; after your php sql insert function in mydbInsertCode.php';
if(response=='success'){
myCheckdbFunction(val_1,val_2,val_3,val_4);
}
});
});
function myCheckdbFunction(val_1,val_2,val_3,val_4){
$.post("mydbCheckUpdated.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// put echo $val; from db SELECT in mydbSelectCode.php at end of file ';
if(response==true){
$('#myDiv').append(response);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
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();
I have a simple form with 2 input:
<form name="contact" id="contact">
<input type="text" id="firstName" name="firstName"/>
<input type="text" id="lastName" name="lastName"/>
<input type="submit" value="Send"/>
</form>
On submit I want using jQuery ajax method to send data to print.php. Code looks next:
var contact=$("#contact");
contact.on("submit",function(event){
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
$.ajax({
type:"POST",
url:"print.php",
dataType:"json",
data:{
fname:firstName,
lname:lastName
}
});
});
I want that Print.php script simply prints sent data, but nothing is happening. Script looks next:
<?php
$fname = $_POST['fname'];
$lname=$_POST['lname'];
echo $fname;
?>
Problem is obviusly in print.php.
you need to use following.
$("form").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "print.php",
dataType: "json",
data: {
fname: firstName,
lname: lastName
},
success: functon(dt) {
alert(dt);
}
});
});
There is no $subject variable anywhere.
You set the first name and last name variables properly.
To check your script's response (which will be an error), go to your console and check network, and then repsonse data.
Change $subject to $fname and it should "work"
Also add on .on() submit event handler to your jQuery AJAX call like so:
$('form').on('submit', function() {
//ajax call
});
Edit:
You made an edit and changed $subject to $name. There is no $name variable either.
You do not need the JSON type on the ajax form. And include the preventDefault to avoid natural action(page refreshes when submitting)
contact.on("submit",function(event){
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
event.preventDefault();
$.ajax({
type:"POST",
url:"print.php",
data:{
fname:firstName,
lname:lastName
}
});
});
It looks like your problem is that your HTML form doesn't know where to go ounce the submit happens and that is why nothing is happening. You need to tell your HTML form to run javascript.
You could link your HTML form to your javascript by using JQuery's .submit() method document here http://api.jquery.com/submit/
This will trigger your javascript to run once it is submitted if you wrap all your javascript around it.
$("form").submit(function( event ) {
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
$.ajax({
type:"POST",
url:"print.php",
dataType:"json",
data:{
fname:firstName,
lname:lastName
}
});
});
Also you could give your HTML form an action so it knows what to do when the form is submitted.
Below we are saying run myFunction() when this form is submitted, we will then need to wrap all your javascript in myFunction().
<form name="contact" action=“javascript:myFunction();”>
<input type="text" id="firstName" name="firstName"/>
<input type="text" id="lastName" name="lastName"/>
<input type="submit" value="Send"/>
</form>
Your javascript will look like this
function myFunction(){
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
$.ajax({
type:"POST",
url:"print.php",
dataType:"json",
data:{
fname:firstName,
lname:lastName
}
});
}
Once you get that far you will want to fix your php. The way you have it now $name is empty and won't print anything. You will want to fill the variable in before you echo it out. I am assuming you want $name to contain a concatenated version of $fname and $lname.
<?php
$fname = $_POST['fname'];
$lname=$_POST['lname'];
$name = $fname . ' ' . $lname;
echo $name;
?>
That should work for you.
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);