How do I send data to my PHP script using AJAX? - php

I'm new to PHP and Javascript/Ajax so please bear with me.
All I need to do is get a variable from Ajax and set it as a variable in php. I'm trying to do this with a super global GET but something is not right. I don't want to this by submitting the form.
Here's my JS:
function myFunction(){
var hora= document.getElementById("hora").value;
$.ajax({
type : 'GET',
url : 'reservation.php',
data : {hora: hora},
success : function(data) {
console.log(hora);//This is because I was curious as to
// what the console would say. I found
// that this sets the super global if I
// change the url to something else that
// doesn't exist. Console would say
// -GET http://localhost/bus/(somepage).php?hora=4
// 404 (Not Found)-
alert(hora);
}
})
}
Here's my PHP:
Hora:
<select name="hora" id="hora" onchange="myFunction()">
<?php
$query = "SELECT * FROM vans";
$horas_result = mysql_query($query);
while ($horas = mysql_fetch_array($horas_result)) {
echo "<option value=\"{$horas["van_id"]}\">{$horas["time"]}</option>";
}
?>
</select>
Asientos Disponibles:
<?php echo $_GET["hora"]; ?>
//Right now I only want to echo this variable..
As you can see, right now I only want to echo this variable, later on I'll be using this to write a query.

Look at the code i post, ajax is used to post/get data without need to refresh the page but if you just want to post the data and give the result in other page use a form instead.
<?php
if (isset($_GET["hora"]))
{
echo $_GET["hora"];
exit;
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Page title</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function()
{
$("#hora").change(function ()
{
$.ajax(
{
type : 'GET',
url : '',
data : $('select[name=\'hora\']'),
success : function(data)
{
$('#ajax_result').html('Asientos Disponibles: ' + data);
},
error: function(xhr, ajaxOptions, thrownError)
{
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
}
)
}
)
}
)
</script>
<select name="hora" id="hora">
<?php
$query = "SELECT * FROM vans";
$horas_result = mysql_query($query);
while ($horas = mysql_fetch_array($horas_result)) {
echo "<option value=\"{$horas["van_id"]}\">{$horas["time"]}</option>";
}
?>
</select>
<div id="ajax_result">
</div>
</body>
</html>

For example, the following script
$.ajax({
type: "POST",
url: "test.php",
data: {value:1}
}).done(function(msg) {
// msg contains whatever value test.php echoes. Whether it is code, or just raw data.
if(msg=="Success") {
alert("hello world");
} else {
alert("Hello Hell")
}
});
Will set the variable $_POST['value'] to 1
and my test.php looks like:
<?php
if($_POST['value'] == "1") {
echo "Success";
} else {
echo "Failure";
}
?>
If you run that example, the webpage will show you an alert box with the text "Hello World"
If you change the value to any other number, it will show you an alert with the text "Hello Hell"
Hope that answers your question.

Related

How to send values of Select button from Mysqli database and send to second pages?

I tried to coding it. I am still getting stuck over it. The main goal was if user select value from mysqli database selected it and send the values to other pages. I know people recommend it use by AJAX. I tried to use it. still not working. I'll put details code below.
Main pages Code(main.php)-
<?php
session_start();
$conn=mysqli_connect('localhost','root','','user');
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$resultset=$conn->query("SELECT name from newtable"); ?>
<!DOCTYPE html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
</head>
<body>
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
click
</center>
<script type="text/javascript">
$(document).ready(function(){
var search='';
$("#tables option:selected").each(function() {
if ($(this).attr('value') !== '') {
search=$(this).attr('value');
}
});
$("a").click(function() {
$.ajax({
method: 'post',
url: 'database1.php',
data: {key:search},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
</body>
</html>
as alert box i am getting value of it but second pages get error that key value doesn't exist. here the second one pages (database1.php) -
<?php
$conn=mysqli_connect('localhost','root','','user');
session_start();
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$database=$_POST['key'];
echo'You Selected'.$database.'from table';
$sql = "SELECT * FROM $database";
$result=mysqli_query($conn,$sql);
if($result){
echo'Worked';
}else{
echo'ERROR!';
}
?>
so what the problem occurred?
UPDATED ANSWER
Thanks to #swati which she mentioned that use form tag instead of AJAX (i know its simple answer) still by the way thanks for answer. :)
UPDATED CODE FULL -
<body>
<form action="database1.php" method="GET">
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option
value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
<input type="submit">
</center>
</form>
</body>
SECOND PAGE(database1.php) CHANGES LITTLE -
$database=$_GET['tables'];
You are calling each loop on page load that will give you the already selected value not the value which is selected by user.Also , this loop is not need as you have to pass only one value .
Your script should look like below :
<script type="text/javascript">
$(document).ready(function() {
//no need to add loop here
var search = '';
$("a").click(function() {
search = $("#tables option:selected").val(); //getting selected value of select-box
$.ajax({
method: 'post',
url: 'database1.php',
data: {
key: search
},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
Also , as you are using ajax no need to give href="database1.php" to a tag because you are calling this page using ajax .i.e: Your a tag should be like below :
<a>click</a>
And whatever you will echo in php side will be return as response to your ajax .So , your alert inside success function will show you that value.

How do I get response data from php with ajax (one file)?

I'am trying to get php response data with ajax. I want to check if there is a specific string in testing.txt from my input and if the string is found, php should echo "1" but no matter what I try AJAX always says the output isn't 1
This is my code:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
if (in_array($_POST['table'], $file)) {
echo "1";
} else {
echo "0";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text);
};
function post(vally) {
var table = vally;
$.post('test.php', {table:table}, function(data) {
})
.done(function (data) {
if (data == 1) {
console.log("the output is 1")
} else {
console.log("the output isn't 1")
}
});
console.log('posted');
}
</script>
</body>
</html>
testing.txt:
abc
def
ghi
The response I get if i console.log(data):
0<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text);
};
function post(vally) {
var table = vally;
$.post('test.php', {table:table}, function(data) {
})
.done(function (data) {
if (data == 1) {
console.log("the output is 1")
} else {
console.log(data)
}
});
console.log('posted');
}
</script>
</body>
</html>
I have tried using .done(), .fail() and .always() but I always get the output isn't 1(I am using JQuery 3.2.1).
Can someone tell me what I'm doing wrong?
EDIT: I would like to point out something I haven't before. I'm looking for a one page solution. I know that it can easily be done with two pages but I was wondering if there was a one page solution.
The problem is the Ajax request is sent to the home page, so it receives everything after '0' or '1'. Split that.
Move your PHP code in anoter file, say 'ajax.php'
And change your $.post() settings to call ajax.php instead of test.php.
So the Ajax request will only receive the '0' or '1' string.
Notice how your AJAX response is the entire page, prepended with the single digit that you're looking for. You don't need to send the whole page to the browser twice. Move your PHP logic into its own file with nothing but that logic. Let's call it checkTable.php for the sake of demonstration:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
if (in_array($_POST['table'], $file)) {
echo "1";
} else {
echo "0";
}
}
?>
Then make your AJAX call to that page:
$.post('checkTable.php', {table:table})
Then the response will contain only what that PHP code returns, not the whole page. (It's worth noting that this PHP code will return an empty response if table isn't in the POST data.)
Aside from that, your code is currently returning a 0 for whatever input you're providing, so it's still going to be true that "the output isn't 1". For that you'll need to double-check your input and data to confirm your assumptions.
Because I wanted everything in one file I decided to use data.slice(0, 1); to trim off everything except the first character which will be a 0 or 1, and thanks to David for reminding me that there may be a whitespace issue, which there was. Now I added text.trim() to remove all of the whitespace from the input and array_filter(array_map('trim', $file)); to remove all of the whitespace from the strings written in the file.
This is the finished code:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
$file = array_filter(array_map('trim', $file));
if (in_array($_POST['table'], $file) == true) {
echo "1";
} else {
echo "0";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text.trim());
};
function post(vally) {
var table = vally;
console.log(vally);
$.post('test.php', {table:table}, function(data) {
var cut = data.slice(0, 1);
if (cut == 1) {
console.log("the output is 1")
} else {
console.log(cut);
}
});
console.log('posted');
}
</script>
</body>
</html>
I would like to thank everyone who helped me resolve my issue, which has been bugging me for the last 2 days.

How to filter a JSON page feeding data to Select2?

I'm trying to populate a Select2 box with data from a t-sql query. The query is run on a PHP page which translates the output to JSON and is called in the javascript of the main page.
The main page looks like this:
<?php
header('Content-type: text/html; charset=UTF-8');
require('db.php'); // Bring in the database connection
include("auth.php"); // Make sure the user is logged in to an account
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" http-equiv="Content Type" charset="utf-8"/>
<!-- JQuery -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- SELECT 2 -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
</head>
<body style="background-color: #F5F5F5;">
<select class="js-data-example-ajax">
</select>
<script>
$('.js-data-example-ajax').select2({
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json'
// Additional AJAX parameters go here
}
});
</script>
</body>
</html>
My JSON page looks like this:
<?php
require('db.php'); // Bring in the database connection
include("auth.php"); // Make sure the user is logged in to an account
$search = $_GET['search'];
//JSON Table Stuff
$sql = "SELECT DISTINCT [IN] AS id, Nom as text
FROM dbo.[TFM_NumérosIN2012]
;";
$stmt = sqlsrv_query($con,$sql);
$result = array();
do {
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($stmt));
sqlsrv_free_stmt($stmt);
$data2 = json_encode($result);
echo '{ "results":' . $data2 . '}';
?>
The data output by the JSON page looks like this:
{ "results":[{"id":2,"text":"SMITH Sean"},{"id":3,"text":"CHARLES charley"},{"id":4,"text":"TFC Madrid"},{"id":5,"text":"VAN DAMME jean claude"}]}
The data is loading into the select list without any problems. However, I've tried to filter the data multiple ways and nothing has worked. I've tried adding a data parameter and passing a search variable to the php/JSON page and referencing in the $sql variable as a where clause, but this doesn't return anything
To try and filter the data I changed the javascript to this:
$('.js-data-example-ajax').select2({
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json',
data: function (params) {
var query = {
search: params.term
}
// Query parameters will be ?search=[term]&type=public
return query;
}
}
});
But this breaks my select and and it displays a message 'The results could not be loaded.'
Does anyone know what I'm doing wrong here?
Cheers,
At the end of your php file just echo the following line :
echo json_encode($result);
In your html/js file :
<link href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js'></script>
<select name='js-data-example-ajax' class='js-data-example-ajax'></select>
$(document).ready(function()
{
$('.js-data-example-ajax').select2({
placeholder: "Search for product",
minimumInputLength: 1,
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json',
data: function (params) {
var query = {
search: params.term,
type: 'public'
}
console.log("query : "+query.search);
return query;
},
processResults: function (response) {
console.log("response : "+response);
return {
results: $.map(response, function(obj) {
console.log("response obj.id: "+obj.id);
console.log("response obj.text: "+obj.text);
return { id: obj.id, text: obj.text };
})
};
},
cache: false
}
});
});

ajax new record count notification in php

iam doing a page in php that if any new record is entered it will notify the users screen with the new record count. Following is the code i did for the same, but its not working fine. Can u pls suggest me as of what iam doing wrong...
alert.php
<?php
require("config.php");
$result = mysql_query("SELECT * FROM marketing_tend_corr");
$res = mysql_num_rows($result);
echo $res;
?>
index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php
define('BASEPATH', true);
require("config.php");
?>
<script>
var count_cases = -1;
setInterval(function(){
$.ajax({
type : "POST",
url : "alert.php",
success : function(response){
if (count_cases != -1 && count_cases != response) echo $count_cases);
count_cases = response;
}
});
},1000);
</script>
The following line of code is not going to work in Javascript:
if (count_cases != -1 && count_cases != response) echo $count_cases);
This line of code contains php code (echo $count_cases) which is server side code.
I've changed the code a bit and replaced the number of records by returning a random value.
// alert.php
<?php
echo rand(1, 1000000);
//index.php
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
setInterval(function(){
$.ajax({
type : "POST",
url : "alert.php",
success : function(response){
$("body").html(response);
}
});
},1000);
</script>
</head>
<body>
</body>
</html>
You can check the index.php file in your browser to see the random numbers being returned. This random number should in your case become the result of your 'mysql_num_rows' function.

Ajax display msg on submit without refresh

I am submitting form data via Ajax and would like to display a message above the form on successful submit.
Currently the form does send the data successfully. It should render the feedback message on form submit <?php $this->renderFeedbackMessages(); ?> as defined in my config.php
Where am I going wrong? Possibly doing things in the wrong order due to first time working with mvc?
my config.php file I have the following defined;
define("FEEDBACK_BOOK_ADD_SUCCESSFUL", "Book add successful.");
my model;
public function addIsbn($isbn)
{
// insert query here
$count = $query->rowCount();
if ($count == 1) {
$_SESSION["feedback_positive"][] = FEEDBACK_BOOK_ADD_SUCCESSFUL;
return true;
} else {
$_SESSION["feedback_negative"][] = FEEDBACK_NOTE_CREATION_FAILED;
}
// default return
return false;
}
my controller;
function addIsbn()
{
// $_POST info here
header('location: ' . URL . 'admin/searchIsbn');
}
my searchIsbn.php;
<?php $this->renderFeedbackMessages(); ?>
<div>
//my html form here
</div>
<div id="result"></div>
<script>
$('#form').submit(function() {
event.preventDefault();
var isbn = $('#isbn_search').val();
var url='https://www.googleapis.com/books/v1/volumes?q=isbn:'+isbn;
$.getJSON(url,function(data){
$.each(data.items, function(entryIndex, entry){
$('#result').html('');
var html = '<div class="result">';
html += '<h3>' + entry.volumeInfo.isbn + '</h3>';
html += '<hr><button type="button" id="add" name="add">add to library</button></div>';
$(html).hide().appendTo('#result').fadeIn(1000);
$('#add').click(function(ev) {
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>admin/addIsbn',
data: {
'isbn' : isbn
}
});
});
});
});
});
</script>
No console error messages.
You are redirecting here:
header('location: ' . URL . 'admin/addIsbn');
remove it.
echo the success message here and add it to an HTML element's .html() API.
Your page will not be refreshed.
Your page is making the call to admin/addIsbn which is redirected to admin/searchIsbn. So you already have the output of renderFeedbackMessages() being sent to your function.
Use the success callback to output the results to the page:
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>admin/addIsbn',
data: {
'isbn' : isbn
},
success: function(data) {
$('#result').html(data);
}
});
The only way I could get this to work was to add an auto-refresh to my Ajax success function as follows;
window.location.reload(true);
Working however open to suggestions.

Categories