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);
}
Related
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);
I have cut this down to be a simple as possible. I create a typeahead variable that works perfectly.
but I need to pass two other variables $php_var1 and $php_var2 that are unrelated to the typeahead. The PHP variables are defined in
start.php. The typeahead script calls search_script.php then calls cart.php. cart.php is were I will need the two PHP variables to
be passed to. Thanks in advance for any help
start.php
<?php
$php_var1 = "my php variable 1";
$php_var2 = "my php variable 2";
?>
<script>
$(document).ready(function() {
var php_var1 = <?php echo $php_var1; ?>;
var php_var2 = <?php echo $php_var2; ?>;
$('#my_input').typeahead({
source: function(query, result) {
$.ajax({
url: "search_script.php",
method: "POST",
data: {
query: query
},
dataType: "json",
success: function(data) {
result($.map(data, function(item) {
return item;
}));
}
})
},
updater: function(item) {
location.href = 'cart.php?shop_name=' + item
return item
}
});
});
</script>
<form action="cart.php" action="post">
<input type="text" id="my_input" placeholder="Typeahead Search" />
</form>
search_script.php
<?php
$php_var1 = isset($_REQUEST['php_var1']) ? $_REQUEST['php_var1'] : "empty";
$php_var2 = isset($_REQUEST['php_var2']) ? $_REQUEST['php_var2'] : "empty";
$connect = mysqli_connect($servername, $username, $password, $dbname);
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query = " SELECT * FROM all_shops WHERE p_shop_name LIKE '%".$request."%'";
$result = mysqli_query($connect, $query);
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row["p_shop_name"];
}
echo json_encode($data);
}
?>
cart.php
$php_var1 = isset($_REQUEST['php_var1']) ? $_REQUEST['php_var1'] : "empty";
$php_var2 = isset($_REQUEST['php_var2']) ? $_REQUEST['php_var2'] : "empty";
echo $php_var1;
echo $php_var2;
?>
You need quotes around the php output in order to generate javascript strings
var php_var1 = "<?php echo $php_var1; ?>";
var php_var2 = "<?php echo $php_var2; ?>";
Stackoverflow is an excellent resource, but sometimes you don't get the answer, so you need to persevere and keep trying. I worked on this all day yesterday and just couldn't figure it out. Woke up this AM and it came to me. The answer is as follows. In the typeahead script change the following line
location.href = 'cart.php?shop_name=' + item
to
location.href = 'cart.php?shop_name=' + item + '&php_var1=<?php echo $php_var1 ?>' + '&php_var2=<?php echo $php_var2 ?>'
I have 2 functions in 1 php file, one for upvote and 1 for downvote. How to tell ajax to post to the function with name upvoteImage()? I'm literally starting out with ajax so I'm having some troubles figuring things out.
Javascript file
$('.arrowUp').click(function(){
var id = $("input[name='id']").val();
var userId = $("input[name='userId']").val();
$.post('../includes/voting.inc.php', {id: id, userId: userId}, function(data){
alert(data);
});
});
PHP file
function upvoteImage($conn) {
if (isset($_POST['upvoteImage'])){
$imageId = $_POST['id'];
$userId = $_POST['userId'];
$sql3 = "SELECT * FROM votingconnection WHERE userId='".$userId."' and imageId='".$imageId."'";
$result3 = mysqli_query($conn, $sql3);
$getResult3 = mysqli_fetch_assoc($result3);
if ($getResult3['vote'] == 'downvote') {
$sql4 = "UPDATE votingconnection SET vote='upvote' WHERE userId='".$userId."' and imageId='".$imageId."'";
$result4 = mysqli_query($conn, $sql4);
$sql5 = "UPDATE image SET upvotes = upvotes + 1 WHERE id='$imageId'";
$result5 = mysqli_query($conn, $sql5);
$sql6 = "UPDATE image SET downvotes = downvotes - 1 WHERE id='$imageId'";
$result6 = mysqli_query($conn, $sql6);
header("Location: ../index.php");
} else {
$sql = "INSERT INTO votingconnection (userId, imageId, vote) VALUES ('".$userId."','".$imageId."', 'upvote')";
$result = mysqli_query($conn, $sql);
$sql2 = "UPDATE image SET upvotes = upvotes + 1 WHERE id='$imageId'";
$result2 = mysqli_query($conn, $sql2);
header("Location: ../index.php");
}
}
}
I just can't understand how to connect the index page, the page with the logic for upvote/downvote and the javascript page. This is part of my index page.
<?php
if (isset($_POST['action']) && in_array($_POST['action'], ['upvote', 'downvote'])) {
if ($_POST['action'] == 'upvote' ) {
upvoteImage($conn);
} else {
downvoteImage($conn);
}
}
$currentUser = $_SESSION['id'];
$sql = "SELECT * FROM image";
$result = mysqli_query($conn, $sql);
$getResult = mysqli_fetch_assoc($result);
$numberOfResults = mysqli_num_rows($result);
$resultsPerPage = 5;
$numberOfPages = ceil($numberOfResults/$resultsPerPage);
if (!isset($_GET['page'])) {
$page = 1;
} else {
$page = $_GET['page'];
}
$currentPageResults = ($page-1)*$resultsPerPage;
$sql2 = "SELECT * FROM image ORDER BY id DESC LIMIT ".$currentPageResults.','.$resultsPerPage;
$result2 = mysqli_query($conn, $sql2);
while($row = $result2->fetch_assoc()) {
$sql3 = "SELECT * FROM votingconnection WHERE userId='".$currentUser."' and imageId='".$row['id']."'";
$result3 = mysqli_query($conn, $sql3);
$getResult3 = mysqli_fetch_assoc($result3);
$hasVoted = mysqli_num_rows($result3);
$vote = $getResult3['vote'];
echo "<div class='imageContainer'>"
."<h1>".$row["name"].'</h1>'
.'<div class="stickyImageContainer"><img class="uploadedImg" src="uploads/'.$row["path"] .'" alt="Random image" /> ';
if (isset($_SESSION['id'])) {
if ($hasVoted < 1) {
echo "<div class='upvoteDownvoteRatingContainer'><form class='upvoteImage' method='POST' action=''>
<input type='hidden' name='action' value='upvote'>
<input type='hidden' name='id' value='".$row['id']."'>
<input type='hidden' name='userId' value='".$currentUser."'>
<button class='upvoteImageButton' type='submit' name='upvoteImage'><img class='arrowUp' src='../images/Social Media/arrowUp.png' alt='submit'></button>
</form>";
echo "<div class='ratingNumber'>";
if ($row['upvotes'] - $row['downvotes'] <= 0) {
echo "<p>0</p>";
} else {
echo $row['upvotes'] - $row['downvotes'];
}
echo "</div>";
echo "<form class='downvoteImage' method='POST' action=''>
<input type='hidden' name='action' value='downvote'>
<input type='hidden' name='id' value='".$row['id']."'>
<input type='hidden' name='userId' value='".$currentUser."'>
<button class='downvoteImageButton' type='submit' name='downvoteImage'><img class='arrowDown' src='../images/Social Media/arrowDown.png' alt='submit'></button>
</form></div>";
}
Ajax is not "posting to a function", it's only a way to request a page from the server.
The code in your page is the one that should decide what to do, so basically you can just call the function in your page:
function upvoteImage() {
....
}
upvoteImage()
Of check the data you got from the client, and based on that data - run the relevant function:
function upvoteImage() {
....
}
if ($_POST['do_upvote']) {
upvoteImage()
}
You could call functions by sending post data with some tag like "type:"upvote" or "type:"downvote" and in php, call the function upvoteImage or doenVoteImage according to the tag.
You don't tell ajax to post to a function specifically. Instead tell ajax to post to a file specifically.
$('.arrowUp').click(function(){
var id = $("input[name='id']").val();
var userId = $("input[name='userId']").val();
$.post('../includes/upvote.inc.php', {id: id, userId: userId}, function(data){
alert(data);
});
});
$('.arrowDown').click(function(){
var id = $("input[name='id']").val();
var userId = $("input[name='userId']").val();
$.post('../includes/downvote.inc.php', {id: id, userId: userId}, function(data){
alert(data);
});
});
One for handling the upvote, and the other the downvote.
Either send the preferred action(upvote or downvote) along with the query part of the URL, or send a separate action data(upvote or downvote) along with id and userId.
Method(1):
// for downvote, URL would be ../includes/voting.inc.php?action=downvote
$.post('../includes/voting.inc.php?action=upvote', {id: id, userId: userId}, function(data){
alert(data);
});
And process the request in voting.inc.php page the following way,
if($_GET['action'] == "upvote"){
// call upvoteImage function
}else if($_GET['action'] == "downvote"){
// call downvoteImage function
}
Method(2):
// for downvote, {id: id, userId: userId, action: 'downvote'}
$.post('../includes/voting.inc.php', {id: id, userId: userId, action: 'upvote'}, function(data){
alert(data);
});
And process the request in voting.inc.php page the following way,
if($_POST['action'] == "upvote"){
// call upvoteImage function
}else if($_POST['action'] == "downvote"){
// call downvoteImage function
}
You can simply do this via data-* attribute and make your voting buttons like this
<button class="vote" data-type="up" data-id="1" data-user-id="2">Up</button>
<button class="vote" data-type="down" data-id="1" data-user-id="2">Down</button>
then you can simply send the ajax request like this
$('.vote').click(function() {
var data = {
id: $(this).data('id'),
userId: $(this).data('user-id'),
type: $(this).data('type')
};
$.post('../includes/voting.inc.php', data, function(data){
alert(data);
});
});
Finally, in your server side you can check the type and call functions
if (isset($_POST['type']) && $_POST['type'] == "up"){
// Call upvote function here
}
else if (isset($_POST['type']) && $_POST['type'] == "down"){
// Call downvote function here
}
else {
// Abort if invalid
}
Please help, I am trying to get the value of input field after ajax success, I don't know why is it always undefined?
ajax.js
$(document).on('click','.modify',function(){
var modId = $(this).attr('id');
var event_id = $(this).attr('class').split(' ')[1];
$.ajax({
cache: false,
url: '../ajax/paraphernalia/ajax_get_edit.php',
type: 'post',
data: { modId: modId, event_id: event_id},
success:function(data){
var mod_name = $(data).find('input#hidden_headerName').val();
alert(mod_name);
$('#display_modal_edit').html(data);
$('#judge_name_header').html(mod_name);
}
});
});
ajax_get_edit.php
session_start();
require ("../../global.php");
if (isset($_POST['modId']) && isset($_POST['event_id'])) {
$modId = $_POST['modId'];
$event_id = $_POST['event_id'];
$output = '';
$sql = mysql_query("SELECT * FROM tbl_judges WHERE judge_id = ".$modId." AND event_id = ".$event_id."");
$soc_sql = mysql_fetch_assoc($sql);
$output .= '<input type="text" value="GetThisvalue" id="hidden_headerName">';
$output .= '.....';//bunch of codes here
$output .= '</div>';
echo $output;
}
You can Return a JSON from PHP and Create the Divs you need/dont Need on the Client, further its also simpler if you just Need some values
I am trying to send a post to a php script which will collect all the account information from the database using this...
var e = document.getElementById("lstAccounts");
var accountID = e.options[e.selectedIndex].value;
alert("Account ID:"+accountID);
$.post("php/getAccount.php", {ID: accountID}, function(data)
{
var accountInfo = data;
});
This posts into this...
<?php
$id = $_POST['ID'];
include('database_api.php');
$db = new DatabaseControl;
$db->open_connection();
$result = $db->db_query("SELECT * FROM tblAccount WHERE ID=$id");
$account_info = array();
//Get Basic Information
while($row = mysqli_fetch_array($result))
{
$account_info['Name'] = $row['Name'];
$account_info['CRN'] = $row['CRN'];
$account_info['ID'] = $row['ID'];
$account_info['Type'] = $row['Type'];
$account_info['Revenue'] = $row['Revenue'];
$account_info['Industry'] = $row['Industry'];
$account_info['Description'] = $row['Description'];
$account_info['Employees'] = $row['NoOfEmployees'];
$account_info['Billing'] = $row['BillingAddress'];
$account_info['Shipping'] = $row['ShippingAddress'];
}
//Get Details
$result = $db->db_query("SELECT tblDetails.ID, tblDetails.Label, tblDetails.Value FROM tblAccountDetails
INNER JOIN tblDetails ON tblDetails.ID = tblAccountDetails.DetailID
WHERE AccountID=$id");
//Get Basic Information
while($row = mysqli_fetch_array($result))
{
$account_info['Detail'.$row['ID']]['Label'] = $row['Label'];
$account_info['Detail'.$row['ID']]['Value'] = $row['Value'];
}
//Get Contact Information
//Get Invoices
//Get Payments
//Get Notes
//Get To-Do
//Events
//Send back to javascript
echo json_encode($account_info);
?>
I need the echoed json_encode to enter a javascript on the return data. How do I get that data into an array?
$.post("php/getAccount.php", {ID: accountID}, function(data)
{
//In here how do I decode data into a javascript array
});
The data is set at "{"Name":"A business name","CRN":null,"ID":"17","Type":"User","Revenue":null,"Industry":"Software & Internet","Description":null,"Employees":null,"Billing":"An Address","Shipping":"An Address","Detail75":{"Label":"Phone","Value":"a phone number"},"Detail76":{"Label":"Email","Value":"an email address"}}" on return
pass in json_encode()'ed data from your php, like:
...
while($row = mysqli_fetch_array($result))
{
$account_info['Detail'.$row['ID']]['Label'] = $row['Label'];
$account_info['Detail'.$row['ID']]['Value'] = $row['Value'];
}
echo json_encode($account_info);
in js part:
$.post("php/getAccount.php", {ID: accountID}, function(data) {
//parse the json response
var response = jQuery.parseJSON(data);
console.log(response); //you can use $.each to iterate the data
});
First Set the datatype as JSON
$.post("php/getAccount.php", {ID: accountID}, function(data)
{
// Confirm Response
console.log(data);
$.each(data, function(i, e){
console.log(e);
});
}, 'json');