How to pass data from HTML, to PHP file by Ajax? - php

I would like to know, how can I pass <select> element from html to PHP file by ajax.
Here is my index.php:
<p>
<form action = "display.php" method="post" enctype="multipart/form-data">
Select:
<select name="chosenOption" id="chosenOption" style="width:100px"">
<?php
include 'dbConnection.php';
$query = $db->query("SELECT id,name FROM products");
while($row = $query->fetch_assoc())
{
echo'
<option value="'.$row['id'].'">'.$row['name'].'
</option>';
}
?>
</select>
Display : <input type="submit" name="display" value="Display">
</form>
</p>
My display.php, where i have ajax method:
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
function refresh_div() {
var chosenOption= $('#chosenOption').val();
jQuery.ajax({
url: 'products.php',
type:'POST',
data:{chosenOption:chosenOption},
success:function(results) {
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,1000);
</script>
<div class="result"></div>
And products.php, where i want to pass selected < select > element:
<?php
include 'dbConnection.php';
$chosenOption = $_POST["chosenOption"];
// Display section
$query = $db->query("SELECT cost,description FROM products_info WHERE products_id=$chosenOption);
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
echo "Actual cost and description: ".$row["cost"]. " ".$row["description"]. ;
}
} else {
echo "No data";
}
?>
I expect that selected option from index.php will be pass to products.php by ajax and display the appropriate message. The current code does not work. Any idea?

You can't refer to $("#chosenOption") in display.php, because the page has been reloaded. You need to use $_POST['chosenOption'], since that was submitted by the form.
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
function refresh_div() {
var chosenOption= $('#chosenOption').val();
jQuery.ajax({
url: 'products.php',
type:'POST',
data:{chosenOption: <?php echo $_POST['chosenOption']; ?>},
success:function(results) {
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,1000);
</script>
<div class="result"></div>

Related

send selected dropdown value to another PHP page

I do not use submit button
I want the selected value from the user sent to the test1.php page, but when the user selects an option nothing happen in the page, and the value is not sent to the test1.php page
Is there any mistake in my code, or did I miss something ?
test2.php
<?php include_once 'database.php';
?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function() {
$('.category').change(function() {
var category = $('.category option:selected').val();
alert('category changed to ' + category);
$.ajax({
method: "POST",
url: "test1.php",
data: {
category1: $(this).val()
},
success: function(data) {
console.log(data);
}
});
});
});
</script>
</head>
<p> Filter By Category</p>
<select id="category" class="category">
<?php
$query = mysqli_query($conn,"select * from category ");
while($category = mysqli_fetch_array($query)) {
echo "<option value='" . $category['cat_name'] . "'>" . $category['cat_name'] . "</option> ";
}
?>
</select>
test1.php
<?php
include_once 'database.php';
if (isset($_POST['category1'])) {
$category = $_POST['category1'];
echo $category;
}
?>
is that all your file ? did you forget to include jquery ?
I just did the same script as yours but in html, and console said $ not found, after add jquery that's working
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function() {
$('.category').change(function() {
$.ajax({
method: "POST",
url: "https://webhook.site/2d574d22-5570-46f2-b5bd-343d715adff4",
data: {
category1: $(this).val()
},
success: function(data){
console.log(data);
}
});
});
});
</script>
</head>
<body>
<p> Filter By Category</p>
<select id="category" class="category">
<option value='1'>One</option>
<option value='2'>two</option>
</select>
</body>
</html>
here is the webhook to check your request, it is like test1.php but just for debugging purpose https://webhook.site/#!/2d574d22-5570-46f2-b5bd-343d715adff4/e3406220-f58e-45be-a4ef-13d8d3e0b0d3/1
here are some advices:
inspect your page using developer tools, maybe there are some errors
check with console.log .val()
hope this help

Submit form using Ajax/Jquery and check result?

I am wanting to submit a form using ajax to go to my page 'do_signup_check.php'.
There it will check the email address the user entered against the database to see if there is a match.
If there is a match I want my ajax form to redirect the user to the login.php page.
If there isn't a match I want it to load my page 'do_signup.php'
for some reason the code seems to be doing nothing. Please can someone show me where I am going wrong?
My Ajax form:
<html lang="en">
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
<?php include 'assets/config.php'; ?>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'do_signup_check.php',
data:{"name":name,"email":email},
success: function () {
if(result == 0){
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('do_signup.php',function(){}).hide().fadeIn(500);
});
}else{
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('login.php',function(){}).hide().fadeIn(500);
}
});
});
});
</script>
</head>
<body>
<div class="sign_up_contain">
<div class="container">
<div class="signup_side">
<h3>Get Onboard.</h3>
<h6>Join the directory.</h6>
<form id="signup" action="" method="POST" autocomplete="off" autocomplete="false">
<div class="signup_row action">
<input type="text" placeholder="What's your Name?" name="name" id="name" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<input type="text" placeholder="Got an Email?" name="email" id="email" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<div class="g-recaptcha" style="margin-top:30px;" data-sitekey="6LeCkZkUAAAAAOeokX86JWQxuS6E7jWHEC61tS9T"></div>
<input type="submit" class="signup_bt" name="submit" id="submt" value="Create My Account">
</div>
</form>
</div>
</div>
</div>
</body>
</html>
My Do_Signup_Check.php page:
<?php
session_start();
require 'assets/connect.php';
$myName = $_POST["name"];
$myEmail = $_POST["email"];
$check = mysqli_query($conn, "SELECT * FROM user_verification WHERE email='".$myEmail."'");
if (!$check) {
die('Error: ' . mysqli_error($conn));
}
if (mysqli_num_rows($check) > 0) {
echo '1';
} else {
echo '0';
}
?>
Try to use input id 'submt' to trigger the form as such :
$("#submt").click(function(){
e.preventDefault();
//your logic
You have not included the jquery in your page, the function is also missing the closing parentheses.
Include the jquery at the top
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Replace your function with the following code:-
<script>
$(function () {
$('form').on('submit', function (e) {alert(123);
e.preventDefault();
$.ajax({
type: 'post',
url: 'receive-callback.php',
data:{"name":name,"email":email},
success: function () {
if(result == 0){
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('do_signup.php',function(){}).hide().fadeIn(500);
});
}else{
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('login.php',function(){}).hide().fadeIn(500);
});
}
}
});
});
});
</script>
After receiving success in Ajax and doing all necessary logic (fadeOut etc) just relocate user to login.php:
window.location.href = 'path/to/login.php';
Otherwise, in error function (it is goes just after success function) do the next:
window.location.href = 'path/to/do_signup.php';
Upd:
In case you want to have some piece of code from another file, you can use jQuery method load.
$('#some-selector').load('path/to/course/login.php');
It's a very basic example of using 'load', go google around it to explore more.
Please Try this code.
$.ajax({
type: 'post',
url: 'do_signup_check.php',
data:{"name":name,"email":email},
success: function (result) {
if(result == 0){
window.location.href = 'do_signup.php';
}else{
window.location.href = 'login.php';
}
});
My Do_Signup_Check.php page:
<?php
session_start();
require 'assets/connect.php';
$myName=$_POST["name"];
$myEmail=$_POST["email"];
$check = mysqli_query($conn, "SELECT * FROM user_verification WHERE email='".$myEmail."'");
if (!$check) {
die('Error: ' . mysqli_error($conn));
}
if(mysqli_num_rows($check) > 0){
echo json_encode(array('result'=>'1'));
exit;
}else{
echo json_encode(array('result'=>'0'));
exit;
}
?>
I hope this will work for you.

Why form is fetching all data when i dont give any input?

This is index.php . when i give a input, it fetch the specific name and year. that's OK . but when i submit the form ,without any input it gives all the name of the movie and years but i don't want that ,the user can not show all the data saved in the database. i gave priventdefault() method but it's not working. how can i solve this problem ?
<!DOCTYPE html>
<html>
<head>
<title>ajax</title>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(function() // this function excited if the jquery is ready i mean after jquery successfully loaded
{
function loaddata()
{
var moviename= $("#moviename").val(); // read moviename value and assign;
$.ajax({
type: "GET",
url: "query.php",
data: {
name:moviename // there is no variable name so you have to assign the moveiname to name vairable ;
},
success: function (data) {
$("#result").html(data);
}
});
}
$("#submit").click(function(event) // Click Event Listener.
{
event.preventDefault();
loaddata()
});
});
</script>
</head>
<body>
<p>Enter movie name </p>
<form action="" method="POST">
<input type="text" name="moviename" id="moviename" placeholder="Enter Movie Name" required autocomplete="off">
<input type="submit" name="submit" id="submit" value="Search"/>
<!-- if you want ot use jquery you have to use event listener. like $("#submit").click(function(event){}); code from line 31 to 35 -->
</form>
<br>
<div id="result">
</div>
</body>
</html
///this is query.php
<?php
include 'dbcon.php';
$name =isset($_GET['name'])?$_GET['name']:'';
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
?>
Execute the query only if $name is not null.
if(!empty($name)) {
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query)){
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
}
$name =isset($_GET['name'])?$_GET['name']:'';
if(!empty($name)){
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
}
in javascript
var moviename= $("#moviename").val(); // read moviename value and assign;
if(moviename){
$.ajax({
type: "GET",
url: "query.php",
data: {
name:moviename // there is no variable name so you have to assign the moveiname to name vairable ;
},
success: function (data) {
$("#result").html(data);
}
});
}
In query.php, you always assign empty string to $name in the line if empty 'name' value passed into query.php
$name =isset($_GET['name'])?$_GET['name']:'';.
So query will return you all the results in db as $name is an empty string and matches with all the data in db.
You can validate if $name is empty, not to run the query.

Fill in data from database in multiple divs via ajax request

I have 2 divs on my html page. When I press my button I want to fill the div #question1 with the question1 data from my database and the #question2 div with the question2 data from my database. Now the 2 divs are filled with the same data.
This is my html and js code
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function () {
"use strict";
$('#button').click(function() {
$.ajax({
url: 'getquestions.php',
success: function(data) {
$('#question1').html(data);
$('#question2').html(data);
}
});
});
});
</script>
<input type="button" id="button" value="Load" />
<div id="question1"></div>
<div id="question2"></div>
</body>
</html>
The php file
<?php
$connection = mysqli_connect("localhost", "root", "" , "mobiledatabase");
$query = "SELECT question1, question2 FROM adult_questions WHERE id=3";
$query_run = mysqli_query($connection,$query);
$query_row = mysqli_num_rows($query_run);
if ($query_row==1) {
foreach ($query_run as $row ) {
echo $question1 = $row['question1'];
echo $question2 = $row['question2'];
}
}
?>
Update your php file.
Create an array like $retArr = array("question1" =>$question1,"question2" =>$question2); in your php file Then convert it in to json using json_encode($retArr) & echo json_encode($retArr) In your ajax response show $('#question1').html(data.question1);
Hope this will help
Try this,
In PHP pass it like,
$question1='';$question2='';
if ($query_row==1) {
foreach ($query_run as $row ) {
$question1 = $row['question1'];
$question2 = $row['question2'];
}
}
echo json_encode(array('question1'=>$question1,'question2'=>$question2));
In Jquery,
$.ajax({
url: 'getquestions.php',dataType:'json',
success: function(data) {
$('#question1').html(data.question1);
$('#question2').html(data.question2);
}
});

how to submit the form without refreshing the page

this is my html code when i click on submit button it displays alert and then when i open the retrieveform.php it does not show me the value please solve this mystery
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'retrieveform.php',
data: $('form').serialize(),
success: function () {
alert('helllo');
}
});
});
});
</script>
</head>
<body>
<form>
<input type="text"name="t1">
<input type="submit"name="s1"value="submit">
</form>
</body>
</html>
and my retrieveform.php is
<?php
if($_POST['t1'])
{
echo $_POST['t1'];
}
else
{
echo "hekllojjio";
}
?>
Is it possible that the element "t1" is present since it's part of your form, but empty or just empty characters .. perhaps check if this is the case?
<?php
if($_POST['t1'] && !empty($_POST['t1'])) {
echo "You submitted t1 of: ".$_POST['t1'];
} else {
echo "t1 is empty";
}
?>
Also of note is you may want to use something like firebug to view the ajax page loaded and its results. The echo statement on the ajax loaded page will not display on the parent page unless you set the contents of the response into the page:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$('.form').on('submit', function (e) {
tValue = $(this).find(input[type=text]:first).val();
e.preventDefault();
$.ajax({
type: 'post',
url: 'retrieveform.php',
data: $('form').serialize(),
success: function (response) {
alert('helllo');
$('#placeholder').html(response);
$('#placeholder2').html(tValue);
}
});
});
});
</script>
</head>
<body>
<?PHP for ($i = 1; $i <= 10; $i++) { ?>
<form class="form" name="form_<?PHP echo $i; ?>" id="form_<?PHP echo $i;?>">
<input type="text" id="t<?PHP echo $i; ?>" name="t<?PHP echo $i; ?>">
<input type="submit" name="s<?PHP echo $i; ?>" value="submit">
</form>
<?PHP } ?>
<div id="placeholder"></div>
<div id="placeholder2"></div>
</body>
</html>
with this your ajax loaded page's echo will be put on the page in the "placeholder" div.

Categories