Getting json data back from php without reloading - javascript

I need to send a value from a form to php, get data from a database based on the posted value, store all the data in json and then change an input value to the value of the json. All that without reloading the page because I can't lose the stuff that user has input already in the form.
Here is the select where I get the value from:
<select name="groupName" id="groupName" class="form-control message" onchange="group_select()">
<?php
$user_id = $_SESSION["id"];
$sql = mysqli_query($link, "SELECT group_name FROM SMAILY_groups WHERE user_id = '".$user_id."'");
while ($row = $sql->fetch_assoc()){
echo "<option value='".$row['group_name']."'>" . $row['group_name'] . "</option>";
}
?>
</select>
The changing of the value is handled by this function:
function group_select(){
$.ajax({
url:'send.php',
type:'post',
data:$('#smsForm').serialize(),
success:function(data){
}
});
}
And php that handles it is this:
$groupName = $_POST["groupName"];
$user_id = $_SESSION["id"];
$stack = array();
$sql = "SELECT phone FROM SMAILY_groups_numbers t1 INNER JOIN SMAILY_groups
t2 ON t1.group_id = t2.group_id WHERE t2.user_id = '".$user_id."' AND
t2.group_name = '".$group_name."'";
$result = mysqli_query($link, $sql);
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
array_push($stack, $row["phone"]);
}
$stack = json_encode($stack);
$result->free();
Now I need to get the phone numbers that I got from the database, and assign them as a value to one of my input fields. I need to do this without refreshing the page. I'm pretty sure it's somehow done in the ajax success function but I just don't know how.

You are correct, it is done in the success callback. Actually it's pretty simple: Create a <input type="hidden" name="phonenumbers" id="phonenumbers"> element in your HTML.
<select name="groupName" id="groupName" class="form-control message" onchange="group_select()">
<?php
...
?>
</select>
<input type="hidden" name="phonenumbers" id="phonenumbers" value="">
Then, on each request, append the returned value(s) to the value of that <input> element. Don't forget to add a separator though! I use comma.
For example:
function ajaxSuccessHandler (data) {
var hiddenInput = document.querySelector('#phonenumbers');
if (hiddenInput.value.length >= 1) {
// if there are already one (or more) numbers in the hidden input
hiddenInput.value += ',' + data.join(',');
} else {
hiddenInput.value = data.join(',');
}
}
You can either call that function inside the success callback or as your success callback. So this:
function group_select(){
$.ajax({
url:'send.php',
type:'post',
data:$('#smsForm').serialize(),
success: ajaxSuccessHandler
});
}
or this:
function group_select(){
$.ajax({
url:'send.php',
type:'post',
data:$('#smsForm').serialize(),
success: function (data) {
ajaxSuccessHandler(data);
}
});
}
should produce the same result.

You Can try this
<select name="groupName" id="groupName" class="form-control message" onchange="group_select()">
<?php
$user_id = $_SESSION["id"];
$sql = mysqli_query($link, "SELECT group_name FROM SMAILY_groups WHERE user_id = '".$user_id."'");
while ($row = $sql->fetch_assoc()){
echo "<option value='".$row['group_name']."'>" . $row['group_name'] . "</option>";
}
?>
</select>
Javascript Code Dont Forget to Include jquery in your page head
<script>
function group_select(){
let groupName = document.getElementById('groupName').value;
$.ajax({
url:'send.php?groupName='+groupName,
type:'GET',
success:function(data){
var obj = jQuery.parseJSON(data);
//Field to which you want to sent value
document.getElementById('fieldName').value = obj.variableName;
}
});
}
</script>
send.php will look some what like this
$groupName = $_GET["groupName"];
$user_id = $_SESSION["id"];
$stack = array();
$result = mysql_query("SELECT phone FROM SMAILY_groups_numbers t1 INNER JOIN SMAILY_groups
t2 ON t1.group_id = t2.group_id WHERE t2.user_id = '".$user_id."' AND
t2.group_name = '".$group_name."'");
$row = mysql_fetch_assoc($result);
echo json_encode($row);

Related

Fire back two success in ajax

I want to separate the result after requesting in ajax
<input type="text" class="form-control" name="userno" id='stud_id' readonly >
<input type="text"name="studentname" id='studentname' readonly >
<input type='submit' name='stud' onclick='showstudent_info()'>
function showstudent_info(){
var studid = $('#studid').val();
console.log(studid);
if(studid){
$.ajax({
type:'POST',
url:'parentinfo.php',
data: 'studid='+studid,
success:function(html){
var infoid = html
$('#stud_id').val(info);
var studname = html
$('#studentname').val(studname);
}
});
}
}
this is my parentinfo.php page
parentinfo.php
$stud_id = $_POST['studid'];
$qry = "Select studtbl.stud_id,concat(studtbl.fname,' ',
substring(studtbl.mname, 1,1),'. ',studtbl.lname) as Name from studtbl where
stud_id = $stud_id";
$result = mysqli_query($conn, $qry);
while($row = mysqli_fetch_array($result))
{
extract($row);
$info = $row['stud_id'];
$studname = $row['Name'];
}
echo $info;
echo $studname;
my problem is the value of infoid and studname is joined e.g(1Albert Einstein)
Send it as JSON so you can break it up server side to make it readable as a javascript object client side instead of parsing a string sent from server
In php would be something like:
$outputArray = array(
'id'=> $idVariable,
'name'=> $nameVariable
);
echo json_encode($outputArray);
Then in js add dataType:'json' to the ajax options and success callback would be something like:
success:function(responseObject){
var infoid = responseObject.id;
$('#stud_id').val(infoid );
var studname = responseObject.name;
$('#studentname').val(studname);
}

Onchange populate different dropdown based on value

I'm trying to populate the second dropdown after I select the first option, nothing appears in the second dropdown.
My first select:
<select name="inst" class="form-control" required="" id="inst">
<option value=0 selected=1>Select...</option>
<?php
$sql="SELECT * FROM sapinst";
$myData=mysqli_query($GLOBALS['con'],$sql);
if (mysqli_num_rows($myData) > 0){
while ($row = mysqli_fetch_array($myData))
{
echo '<option value="' .$row["nbd"]. '">' .$row["nome"]. '</option>';
}
}
else{echo "No categories were found!";}
?>
</select>
My second select:
<select id= "sub" name="sub" class="form-control"></select>
My Script:
<script type="text/javascript">
$("#inst").change(function () {
//get category value
var cat_val = $("#inst").val();
// put your ajax url here to fetch subcategory
var url = '/ajax.php';
// call subcategory ajax here
$.ajax({
type: "POST",
url: url,
data: {
cat_val: cat_val
},
success: function (data)
{
$("#sub").html(data);
}
});
});
</script>
My Ajax.php file:
<?php
require_once 'edp/configdbedp.php';
$prod_cat = $_POST['cat_val'];
$sql = "SELECT * FROM " . $dbname . ".sappainel WHERE nbd = '$prod_cat'";
$result = mysqli_query($conn, $sql);
$msg = '';
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$msg =. '<option value="' . $row["nome"] . '">' . $row["nome"] . '</option>';
}
} else {
$msg .= "No categories were found!";
}
echo $msg;
mysqli_close($conn);
?>
if I try to print some thing in the Ajax php I can't...seems ajax.php won't run.
Am I calling it correctly?
Is your second ajax being called properly?
Check the console messages(in developer options, F12) for errors in ajax call.
you might want to do this as both cat_val are same. It might be giving an error. -
data: {
cat_val: cat_val_local //different variable names here.
},
Also "Select * from $TABLE_NAME(not #dbname)"
and next remove extra .[dot] here -> ".sappainel WHERE"
you can also try put console.log() in success callback and see if the success is returning any elements.
success: function (data)
{
console.log(data);
$("#sub").html(data);
}
If nothing is shown then your php might be wrong. Add an eror callback too! like this -
error: function (e)
{
console.log(e);
}
Hope this helps.
I already solved
Diferences on scrip:
<script type="text/javascript">
$("#inst").change(function(){
//get category value
var cat_val = $("#inst").val();
// put your ajax url here to fetch subcategory
var url = 'ajax.php';
// call subcategory ajax here
$.ajax({
type:"POST",
url:url,
data:{
cat_val : cat_val
},
success:function(data)
{
$("#sub").html(data);
}
});
});
</script>
On ajax.php
<?php
require_once 'edp/configdbedp.php';
$prod_cat = $_POST["cat_val"];
$sql = "SELECT * FROM ".$dbname.".sappainel WHERE nbd = '$prod_cat'";
$result = mysqli_query($GLOBALS['con'], $sql);
$msg ='';
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
$msg .='<option value="'. $row["nome"] .'">'. $row["nome"] .'</option>';
}
}
else{$msg .="No categories were found!";}
echo ($msg);
mysqli_close($GLOBALS['con']);
?>

HTML, AJAX, PHP - Send a html input array through ajax to a php page

I have seen many similar questions however I have tried them and none of them worked.
I have a form in which the user can enter an unspecified amount of inputs. These inputs are selects and the user can add them when required. I am using ajax to add in more selects as required.
I am then trying to post this array to a php page using ajax, eventually to insert into a database
This is my html:
<strong>Allergens:</strong><br><div id="allergens">
<select name="allId[]" id="allId">
<option value="">No allergens</option>
<?php
$sql = ("SELECT AllergenId, LookupValue From ALLERGENS");
$result = $conn->query($sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<option value=".$row["AllergenId"].">".$row["LookupValue"]."</option>";
}
}
?>
</select><button type="button" class="addRemove" onClick="addAllergen()">+</button><br></div><br>
Here is what I insert to add in more selects:
<div id="newSelect">
<select name="allId[]" id="allId">
<?php
$sql = ("SELECT AllergenId, LookupValue From ALLERGENS");
$result = $conn->query($sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<option value=".$row["AllergenId"].">".$row["LookupValue"]."</option>";
}
}
?>
</select><button type="button" class="addRemove" onClick="removeNew()">-</button><br></div>
This is my ajax:
function addIng() {
if (confirm("Are you sure you want to submit?")) {
var toPost ={};
$form = $("#ingForm");
toPost.allId = [];
var allId = document.querySelectorAll("#ingForm input[name='allId[]']");
for (i = 0; i < allId.length; i++) {
toPost.allId.push(allId[i].value);
}
$.ajax({
type: "POST",
url: "../PHP/addIngredient.php",
data: toPost,
success: function(data) {
$("#addIngResult").html(data);
}
});
}
}
And then how can I set up my php so I can just call $_POST["allId"] and put it into an array?
On addIngredient.php page you will get the post value in $_POST['toPost'] variable as this is what writing in ajax

ajax -- add comments asynchronously

I have two php files that handle a commenting system I have created for my website. On the index.php I have my form and an echo statement that prints out the user input from my database. I have another file called insert.php that actually takes in the user input and inserts that into my database before it is printed out.
My index.php basically looks like this
<form id="comment_form" action="insertCSAir.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="field1_name"/>
<input type="submit" name="submit" value="submit"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<!--connects to database and queries to print out on site-->
<?php
$link = mysqli_connect('localhost', 'name', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
I want users to be able to write comments and have it updated without reloading the page (which is why I will be using AJAX). This is the code I have added to the head tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
// this is the id of the form
$("#comment_form").submit(function(e) {
var url = "insert.php"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: url,
data: $("#comment_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
However, nothing is happening. The alert() doesn't actually do anything and I'm not exactly sure how to make it so that when the user comments, it gets added to my comments in order (it should be appending down the page). I think that the code I added is the basic of what needs to happen, but not even the alert is working. Any suggestions would be appreciated.
This is basically insert.php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
header("Location:index.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
it also filters out bad words which is why there's an if statement check for that.
<?php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element)
{
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0)
{
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
if ($result)
{
http_response_code(200); //OK
//you may want to send it in json-format. its up to you
$json = [
'commment' => $newComment
];
print_r( json_encode($json) );
exit();
}
//header("Location:chess.php"); don't know why you would do that in an ajax-accessed file
//die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
?>
<script>
// this is the id of the form
$("#comment_form").submit(function(e) {
var url = "insert.php"; // the script where you handle the form input.
$.ajax({
type: "GET", //Id recommend "post"
url: url,
dataType: json,
data: $("#comment_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
$('#myElement').append( data.comment );
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
To get a response from "insert.php" you actually need to print/echo the content you want to handle in the "success()" from the ajax-request.
Also you want to set the response-code to 200 to make sure "success: function(data)" will be called. Otherwise you might end up in "error: function(data)".

how to get multiple data from a php and store it in select options using ajax

I have a select option from which I can select a hotel name which I get from a php script.
And then I have another select option which shows room types based on the hotel selected from 1st select option.
And when I select a hotel with the help of ajax I only get one room type in my 2nd select option, while in my table I have multiple room types for a single hotel.
My php code for getting room types.
<?php
include('mysql.php');
$h_id = $_POST['hotel_id'];
$result = mysql_query("SELECT * FROM room_type WHERE hotel_id = '$h_id'");
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$type_name = $row['type_name'];
$type_id = $row['roomtype_id'];
echo $type_name.",".$type_id;
}
exit();
?>
javascript:
jQuery(document).ready(function($){
$('#hotel_list').change(function(){
$.ajax({
type:'post',
url:'roomtype_fetch.php',
data: 'hotel_id='+ $(this).val(),
success: function(value){
var data = value.split(",");
var type_name =data[0];
var type_id =data[1];
$("#roomtype_list").html("<option value="+type_id+">"+type_name+"</option>");
}
});
});
});
html for 1st select option with its php to get hotel name.
<select class="form-control" name="hotel_list" id="hotel_list" onchange="cal()">
<option>--Select--</option>
<?php
$query2 = mysql_query("SELECT * FROM hotel") or die("the query cannot be completed at this moment");
if(mysql_num_rows($query2) <1) {
?>
<option>No Hotel Found!</option>
<?php
}
while($row = mysql_fetch_array($query2, MYSQL_ASSOC)){
$hotel_name = $row['hotel_name'];
$hotel_id_1 = $row['hotel_id'];
?>
<option value="<?php echo $hotel_id_1; ?>"><?php echo $hotel_name; ?></option>
<?php
}
?>
</select>
2nd select html code:
<select class="form-control" name="roomtype_list" id="roomtype_list">
<option>--Select--</option>
</select>
Any type of help would be appreciated.
You cant directly do value.split(",") because your php output looks like:
name1,id1name2,id2name3,id3
echo does not add a new line at the end, if you change the line to:
echo $type_name.",".$type_id,"\n";
That would give you an output like:
name1,id1
name2,id2
name3,id3
Which then you can split by "\n" to get an array of lines then by "," to separate name and id:
var data = value.split(",");
data.forEach(function(line){
var type_values = line.split(",");
var type_name = type_values[0];
var type_id = type_values[1];
$("#roomtype_list").html("<option value="+type_id+">"+type_name+"</option>");
}
But anyway, I think your best option is to change your php to return JSON:
$result = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$result[] = $row;
}
echo json_encode($result);
Then just do something like:
var data = JSON.parse(value);
$("#roomtype_list").empty();
data.forEach(function(type){
$("#roomtype_list").append("<option value="+type.roomtype_id+">"+type.type_name+"</option>");
});
The first thing is, your php loop that generates the types gives a wrong output:
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$type_name = $row['type_name'];
$type_id = $row['roomtype_id'];
echo $type_name.",".$type_id;
}
That gives you something like that:
name1,type1name2,type2name3,type3...
You should add a ; or an other separator like that between, so change the echo line to:
echo $type_name.",".$type_id.",";
That will give you an output like that:
name1,type1;name2,type2;name3,type3...
The second thing is, that you have to loop with jquery through your received types. You split the received string in an array:
var data = value.split(",");
..and so you should do the following in your javascript success function:
...
success: function(value){
var data = value.split(";");
//split all types first with ";"
$.each(data, function() {
var type = $(this).split(",");
//then split the type in name and id
var type_name = type[0];
var type_id = type[1];
//add every type to roomtype_list
$("#roomtype_list").html("<option value="+type_id+">"+type_name+"</option>");
});
}
...
Explanation: Split first all types with the separator ";" and split then the type in name and id with ",". I hope this helps.

Categories

Resources