How to pass many ajax results to different input values? - javascript

My ajax return results are four values.I want assign these values to four input value.Here my ajax code:
$.ajax({
type:"POST",
url:"modify_cbndtb.php",
data: {cabinetNum:id},
success:function (res)
{
}
});
modify_cbndtb.php code:
if(isset($_POST['cabinetNum']))
{
$q=$_POST["cabinetNum"];
$sql="select num1,num2,num3,num4 from hpc WHERE sysid= '".$q."';";
$sel = $conn->query($sql);
}
My html code:
<div id="content" class="content">
1U:<input type="text" id="1U" value="">11U:<input type="text" id="11U" value=""><br />
2U:<input type="text" id="2U" value="">12U:<input type="text" id="12U" value=""><br />
</div>
1U.value should be num1. 2U.value should be num2. 3U.value should be num3. 4U.value should be num4. But I don't know how to realize. Who can help me?

I think you can try this
modify_cbndtb.php
if(isset($_POST['cabinetNum']))
{
$q=$_POST["cabinetNum"];
$sql="select num1,num2,num3,num4 from hpc WHERE sysid= '".$q."';";
$sel = $conn->query($sql);
$arr = $sel->fetch(PDO::FETCH_ASSOC);
$data = json_encode($arr);
echo $data;
}
and AJAX
client file
$.ajax({
type:"POST",
url:"modify_cbndtb.php",
data: {cabinetNum:id},
success:function (data) {
$('#1U').val(data[0].num1);
$('#11U').val(data[0].num2);
$('#2U').val(data[0].num3);
$('#12U').val(data[0].num4);
}
});
I hope it help you

Try this
modify_cbndtb.php
<?php
if(isset($_POST['action']))
{
$q=$_POST["cabinetNum"];
$sql="select num1,num2,num3,num4 from hpc WHERE sysid= '".$q."';";
$sel = $conn->query($sql);
while($row = $sel->fetch_assoc()){
echo $row['num1'].",".$row['num2'].",".$row['num3'].",".$row['num4'];
}
}
?>
your form
<script type="text/javascript" src="testing/jquery-3.2.1.js"></script>
<form id="form">
<input type="submit" name="submit" id="submit">
<input type="hidden" id="cabinetNum" name="cabinetNum" value="1">
</form>
<div id="content" class="content">
1U:<input type="text" id="1U" value="">3U:<input type="text" id="3U" value=""><br />
2U:<input type="text" id="2U" value="">4U:<input type="text" id="4U" value=""><br />
</div>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','#submit',function(e){
e.preventDefault();
var dataen = $("#form").serialize() + "&action";
$.ajax({
type:"POST",
url:"modify_cbndtb.php",
data: dataen,
success:function (data) {
$(function(){
var valData = data;
var valNew=valData.split(',');
for (i = 0; i < valNew.length; i++) {
valNew[i] = valNew[i];
$('#'+(i + 1)+'U').val(valNew[i]);
}
});
}
});
});
});
</script>

Related

Javascript autocomplete function not work with spaces

im have an autocomplete function searching in database field (name).
If my field = john, and i typing "joh" autocomplete works fine.
But
If my field = john marshall, and i typing "joh" or anything, autocomplete doesn't work.
Any ideas? Thanks so much.
my code:
index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
<link href="css/jqueryui.css" type="text/css" rel="stylesheet"/>
<script>
$(document).ready(function(){
$( "#matricula" ).autocomplete({
source: "searchalumno.php",
minLength: 2
});
$("#matricula").focusout(function(){
$.ajax({
url:'alumno.php',
type:'POST',
dataType:'json',
data:{ matricula:$('#matricula')}
}).done(function(respuesta){
$("#nombre").val(respuesta.nombre);
$("#paterno").val(respuesta.paterno);
$("#materno").val(respuesta.materno);
});
});
});
</script>
</head>
<body>
<form>
<label for="matricula">Matricula:</label>
<input type="text" id="matricula" name="matricula" value=""/>
<label for="nombre">Nombre:</label>
<input type="text" id="nombre" name="nombre" value=""/>
<label for="paterno">Paterno:</label>
<input type="text" id="paterno" name="paterno" value=""/>
<label for="materno">Materno:</label>
<input type="text" id="materno" name="materno" value=""/>
</form>
</body>
alumno.php:
<?php
$conexion = new mysqli('servidor','usuario','password','basedatos',3306);
$matricula = $_POST['matricula'];
$consulta = "select nombre, paterno, materno FROM tblalumno WHERE matricula = '$matricula'";
$result = $conexion->query($consulta);
$respuesta = new stdClass();
if($result->num_rows > 0){
$fila = $result->fetch_array();
$respuesta->nombre = $fila['nombre'];
$respuesta->paterno = $fila['paterno'];
$respuesta->materno = $fila['materno'];
}
echo json_encode($respuesta);
?>
searchalumno:
<?php
$conexion = new mysqli('servidor','usuario','password','basedatos',3306);
$matricula = $_GET['term'];
$consulta = "select matricula FROM tblalumno WHERE matricula LIKE '%$matricula%'";
$result = $conexion->query($consulta);
if($result->num_rows > 0){
while($fila = $result->fetch_array()){
$matriculas[] = $fila['matricula'];
}
echo json_encode($matriculas);
}
?>
In your ajax request, use input value instead of input object:
$.ajax({ ... data:{ matricula: $('#matricula').val() } })

Get $_POST from PHP to Javascript and pass it to another php

I build a search feature with infinite scroll. How do i get search string from search page to my scroll page for query database.
PHP :
search.php
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style/css/scroll.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<link href="css/search.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="search">
<form action="search" method="post">
<input type="text" name="search" id="search" autocomplete="off">
<button type="submit" class="btn btn-primary">Search</button>
</form>
</div>
<img id='loading' src='img/loading.gif'>
<div id="demoajax" cellspacing="0">
</div>
</body>
<script type="text/javascript" src="js/infinitescroll/search.js"></script>
scroll.php
<?php
include('db.php');
$searchstring = $_POST['search'];
if(isset($_REQUEST['actionfunction']) && $_REQUEST['actionfunction']!=''){
$actionfunction = $_REQUEST['actionfunction'];
call_user_func($actionfunction,$_REQUEST,$con,$limit);
}
function showData($data,$con,$limit){
$page = $data['page'];
if($page==1){
$start = 0;
}
else{
$start = ($page-1)*$limit;
}
$sql = "SELECT fm_product.p_name, fm_product.p_descp, fm_product.p_id, fm_product.p_price, fm_product.p_discount, fm_product.p_img, fm_member.member_display_name, fm_product.p_member_id, fm_package.package_name, fm_package.package_id FROM fm_member LEFT JOIN fm_product ON fm_member.member_id = fm_product.p_member_id LEFT JOIN fm_package ON fm_member.package_id = fm_package.package_id order by p_created_date desc limit $start,$limit";
$str='';
$data = $con->query($sql);
if($data!=null && $data->num_rows>0) {
while( $row = $data->fetch_array(MYSQLI_ASSOC)){
if($row['package_id']=='1'){
$package = "No Package";
} else {
$package = "<form class='form-item'><input name='product_code' type='hidden' value='".$row['p_id']."'><button type='submit'>Add to Cart</button></input></form>";
}
$id = $row['p_id'];
$str.="<div style=align: center class='data-container'><a href=item?id = $id><img src=upload/".$row['p_img']." width=300px style=max-width:100%; height: auto; vertical-align: middle></a><p>By ".$row['member_display_name']."</p><p>Product Name : ".$row['p_name']."</p><p>Price : ".$row['p_price']."</p><p>Discount : ".$row['p_discount']."</p><p>Description : ".$row['p_descp']."</p><p>Package ".$_POST['search']." : ".$row['package_name']."</p><p>".$package."</p></div>";
}
$str.="<input type='hidden' class='nextpage' value='".($page+1)."'><input type='hidden' class='isload' value='true'>";
} else {
$str .= "<input type='hidden' class='isload' value='false'><p>Finished</p>";
}
echo $str;
}
?>
Javascript :
search.js
var ajax_arry=[];
var ajax_index =0;
var sctp = 100;
$(function(){
$('#loading').show();
$.ajax({
url:"scroll.php",
type:"POST",
data:"actionfunction=showData&page=1",
cache: false,
success: function(response){
$('#loading').hide();
$('#demoajax').html(response);
}
});
$(window).scroll(function(){
var height = $('#demoajax').height();
var scroll_top = $(this).scrollTop();
if(ajax_arry.length>0){
$('#loading').hide();
for(var i=0;i<ajax_arry.length;i++){
ajax_arry[i].abort();
}
}
var page = $('#demoajax').find('.nextpage').val();
var isload = $('#demoajax').find('.isload').val();
if ((($(window).scrollTop()+document.body.clientHeight)==$(window).height()) && isload=='true'){
$('#loading').show();
var ajaxreq = $.ajax({
url:"scroll.php",
type:"POST",
data:"actionfunction=showData&page="+page,
cache: false,
success: function(response){
$('#demoajax').find('.nextpage').remove();
$('#demoajax').find('.isload').remove();
$('#loading').hide();
$('#demoajax').append(response);
}
});
ajax_arry[ajax_index++]= ajaxreq;
}
return false;
if($(window).scrollTop() == $(window).height()) {
alert("bottom!");
}
});
});
I want to get $_POST['search'] from search.php to scroll.php for replace it into WHERE on this query like.
$sql = "SELECT ... FROM ... LEFT JOIN ... ON ... LEFT JOIN ... ON ... WHERE p_name LIKE '%$_POST['search']' ORDER BY ... LIMIT ..."
Appreciated.
<form action="search" method="post">
This redirects to /search page, which you don't have. You have /search.php and /scroll.php. I think you should just put scroll.php as the action, and you'd get your result.
<form action="scroll.php" method="post">
EDIT:
I seem to have misunderstood the code. scroll.php is an API endpoint in this. Then the action remains search.php, BUT, in order to have the submitted values, you can kill 2 birds with 1 stone.
Update the form HTML (you don't need action, you don't need the form either, but let's keep it):
<form action="" method="post">
<input type="text" name="search" id="search" autocomplete="off">
<button type="button" id="do_search" class="btn btn-primary">Search</button>
</form>
In your JS, make the function get triggered by the search:
jQuery(document).ready(function($) {
$("#do_search").on("click", function() {
var searchTerm = $("#search").val();
//this is where you do the AJAX stuff. You can use searchTerm variable.
});
});

Adding Comment in textarea and displaying text with Edit and delete buttons

I have textarea with save and cancel buttons for updating textarea text in mysql DB.
Initially my MYSQL db
ID text
1 NULL
If i enter some text in textarea i'm updating my mysql db text with entered value currently i'm able to achieve it but my requirment is once i entered text in textarea it should update my db and that text value should display with EDIT and DELETE buttons.
on clicking EDIT button it should open up textarea with save and cancel buttons. can somebody aid me out how to achieve it Thanks!
http://jsfiddle.net/a32yjx0k/
HTML
<div id="b_news">
<form method="post" action="">
</div>
<div class="breaking_news_content">
<div>
<form method="post" action="">
<div>
<div>
<textarea id="breaking_news_text" class="breaking_news_text" rows="6" cols="50" placeholder="Add text here..." required></textarea>
</div>
</div>
<div>
<input type="submit" class=" save_breaking_news" value="Save Changes"/>
<input type="submit" value="Cancel" class=" breaking_news_cancel">
</div>
</form>
</div>
</div>
</form>
</div>
JQUERY
$(function(){
$(".save_breaking_news").click(function(){
var textcontent = $('.breaking_news_text').val();
if(textcontent == '')
{
alert("Enter Some Text...");
$('.breaking_news_text').focus();
}
else
{
$.ajax({
type: "POST",
url: "index.php",
data:{
textcontent:textcontent
},
success:function(response){
alert('breaking news successfully updated');
}
});
}
return false;
});
});
PHP
<?php
if(isset($_POST['textcontent']))
{
$breaking_news = mysqli_real_escape_string($con, $_POST['textcontent']);
$sql = "update breakingnews set text='".$breaking_news."'";
$result = mysqli_query($con, $sql);
}
?>
$(function(){
$(".save_breaking_news").click(function(){
var textcontent = $('.breaking_news_text').text();
if(textcontent == '')
{
alert("Enter Some Text...");
$('.breaking_news_text').focus();
}
else
{
$.ajax({
type: "POST",
url: "index.php",
data:{
textcontent:textcontent
},
success:function(response){
alert('breaking news successfully updated');
}
});
}
return false;
});
});
To get textbox use (class/id).text();
Your DIV
<div id="b_news">
<form method="post" action="">
</div>
<div class="breaking_news_content">
<div>
<form method="post" action="">
<div>
<div>
<textarea id="breaking_news_text" class="breaking_news_text" rows="6" cols="50" placeholder="Add text here..." required></textarea>
</div>
</div>
<div>
<input type="hidden" id="post_ID" value="2"/>
<input type="button" class=" save_breaking_news" value="Save Changes"/>
<input type="button" value="Cancel" class=" breaking_news_cancel">
</div>
</form>
</div>
</div>
</form>
</div>
YOUR SCRIPT SHOULD BE LIKE THIS
$(function(){
$(".save_breaking_news").click(function(){
var textcontent = $('.breaking_news_text').text();
if(textcontent == '')
{
alert("Enter Some Text...");
$('.breaking_news_text').focus();
}
else
{
var postID=$("#post_ID").val();
$.ajax({
url: 'index.php',
type: 'post',
data: 'textcontent=' + drvNo+"id="+postID,
success:function(response){
alert('breaking news successfully updated');
}
});
}
return false;
});
});
YOUR PHP CODE FOR UPDATE
<?php
if(isset($_POST['textcontent']))
{
$breaking_news = mysqli_real_escape_string($con, $_POST['textcontent']);
$sql = "update breakingnews set text='".$breaking_news."' Where id='".$_POST['id']."'";
$result = mysqli_query($con, $sql);
}
?>
AND IF YOU WANT TO INSERT POST YOUR CODE SHOULD BE LIKE THIS:
<?php
if(isset($_POST['textcontent']) && !isset($_POST['id']))
{
$breaking_news = mysqli_real_escape_string($con, $_POST['textcontent']);
$sql = "insert into <TBL NAME> `text` values ('".$_POST['textcontent']."')";
$result = mysqli_query($con, $sql);
}
?>
Your code everything is fine. Instead of calling function use .keyup() function in Jquery.
$("#breaking_news_text").keyup(function(){
var textcontent = $('.breaking_news_text').val();
if(textcontent == '')
{
alert("Enter Some Text...");
$('.breaking_news_text').focus();
}
else
{
alert(textcontent);
$.ajax({
type: "POST",
url: "index.php",
data:
{
textcontent:textcontent
},
success:function(response)
{
alert('breaking news successfully updated');
}
});
}
return false;
});
and when you going to cancel please use input type="reset"
<input type="reset" value="Cancel" class=" breaking_news_cancel">

How to Insert and display record without refreshing web page in codeigniter version?

I have a code here of inserting and displaying record without refreshing web page using ajax and plain php but I don't know how to set this up using codeigniter. Please help. Here are the codes
inserting.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
if(test=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" align="absmiddle">
<span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "demo_insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
document.getElementById('content').value='';
document.getElementById('content').focus();
$("#flash").hide();
}
});
} return false;
});
});
</script>
// HTML code
<div>
<form method="post" name="form" action="">
<h3>What are you doing?</h3>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Update" name="submit" class="comment_button"/>
</form>
</div>
<div id="flash"></div>
<div id="display"></div>
demo_insert.php
PHP Code display recently inserted record from the database.
<?php
include('db.php');
if(isSet($_POST['content']))
{
$content=$_POST['content'];
mysql_query("insert into messages(msg) values ('$content')");
$sql_in= mysql_query("SELECT msg,msg_id FROM messages order by msg_id desc");
$r=mysql_fetch_array($sql_in);
}
?>
<b><?php echo $r['msg']; ?></b>
In your wellcome controller you can add the following:
public function inserting()
{
$this->load->view('inserting');
}
public function process()
{
$content=$this->input->post('content');
if($this->db->insert('mytable', array('msg' => $content))){
echo "<b>{$content}</b>";
}
You should then use inserting.php as your view, in application/views, and the ajax url would be /process.
Didn't test it, but this should do the trick. Also, you should check this example http://runnable.com/UXczcazDrMMiAAGl/how-to-do-ajax-in-codeigniter-for-php

add and retrieve record from mysql using ajax

As shown from the diagram, I have two tables in my mysql and I would like the system to add and retrieve comment without refreshing the page.
I have three php pages involved in this function and they are 'DB.php', 'comment.php' and 'action.php'
The codes are as shown:
DB.php
<?php
$conn = mysql_connect('localhost','Practical4','1234') or die (mysql_error);
$db=mysql_select_db('Practical4', $conn) or die (mysql_error);
?>
comment.php
<----------------ajax script-------------------->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var dataString = 'content='+ textcontent;
if(textcontent=='')
{
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: true,
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<-----retrieve hotel id from hotel table-------->
<?php
$conn=mysqli_connect('localhost','Practical4','1234') or die('Not connected');
$database=mysqli_select_db($conn,'Practical4') or die('Database Not connected');
$id=$_GET['id'];
$query = "select * from hotel where name='$id'";
$data=mysqli_query($conn,$query);
while($rows=mysqli_fetch_array($data)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<---------------post form------------------->
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Post" name="submit" class="submit_button"/>
</form>
</div>
<div class="space"></div>
<div id="flash"></div>
<div id="show"></div>
action.php
<?php
include('DB.php');
$check = mysql_query("SELECT * FROM comment order by commentID desc");
if(isset($_POST['content']))
{
$content=mysql_real_escape_string(trim($_POST['content']));
$name=mysql_real_escape_string(trim($_POST['name']));
mysql_query("insert into comment(content,name) values ('$content','$name')");
$fetch= mysql_query("SELECT content FROM comment order by commentID desc where name = '$name'");
$row=mysql_fetch_array($fetch);
}
?>
<div class="showbox"> <?php echo $row['content']; ?> </div>
when I run this, the page display nothing when I insert the comment, can anyone help me to solve this? Thanks a lot!!
Some changes have been made as follows:
comment.php
<!-- ajax script -->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var name = $("#name").val();
var dataString = 'content='+ textcontent + '&name='+name;
if(textcontent=='')
{
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: true,
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<!-- retrieve hotel id from hotel table -->
<?php
include('DB.php');
$id=$_GET['id'];
$query = mysql_query("select * from hotel where name='$id'");
while($rows=mysql_fetch_array($query)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<!-- post form -->
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Post" name="submit" class="submit_button"/>
</form>
</div>
<div class="space"></div>
<div id="flash"></div>
<div id="show"></div>
action.php
<?php
include('DB.php');
$check = mysql_query("SELECT * FROM comment order by commentID desc");
if(isset($_POST['content']))
{
$content=$_POST['content'];
$name=$_POST['name'];
mysql_query("insert into comment (content,name) values ('$content','$name')");
echo '<div class="showbox">'.$content.'</div>';
}
?>
Reasons why your code failed:
name not added in dataString causing name not sent in post
some mysql errors

Categories