sucess function not working in ajax - javascript

I was getting alert value after change function but after success function, I not getting any values
my ajax page
$(document).ready(function(){
$("#customer").change(function() {
var customer_type = $(this).find(":selected").val();
var dataString = 'customer_type='+ customer_type;
$.ajax({
url: 'http://localhost/capms_v3/ajax/getcust_type.php',
dataType: "json",
data: dataString,
cache: false,
success: function(customerData) {
alert(data);
alert("test");
if(customerData) {
var customer = [customerData];
customerData.forEach(function(item) {
var data = '<tr>';
data+= '<td colspan="4"> </td>';
data+= '<td align="right">'+item.company_id+'</td>';
data+= '<td align="right">'+item.company_name+'</td>';
data+='</tr>';
$('.appendData').append(data);
});
} else {
$("#heading").hide();
$("#records").hide();
$("#no_records").show();
}
}
});
});
});
my array values are not coming after the success function but in getcusttype page values was coming in an array
getcusttype.php
<?php
//header("Content-type:application/json");
include 'db.php';
$db=DbConnect();
if($_REQUEST['customer_type']) {
$sql = "SELECT company_id,company_name FROM ca_customer WHERE customer_type ='".$_REQUEST['customer_type']."'";
$result = mysql_query($sql) or die(mysql_error());
$data = array();
while( $rows = mysql_fetch_array($result) ) {
$data[] = $rows;
}
echo json_encode($data);
} else {
echo 0;
}?>
//var customer =[{"0":"1","company_id":"1","1":"Win Win
web","company_name":"Win Win web"},{"0":"7","company_id":"7","1":"New
Company","company_name":"New Company"},
{"0":"10","company_id":"10","1":"Murugan Super
Store","company_name":"Murugan Super Store"}];
after the success: function(customerdata) if I alert(data) values was getting alert I don't know what error I have made.
view
<select id="customer" name="customer_type" class="form-control">
<option value="">Select Customer Type</option>
<?php
foreach($all_ca_customer_type as $ca_customer_type)
{
$selected = ($ca_customer_type['customer_type_id'] == $this->input->post('customer_type')) ? ' selected="selected"' : "";
echo '<option value="'.$ca_customer_type['customer_type_id'].'" '.$selected.'>'.$ca_customer_type['customer_type_name'].'</option>';
}
?>
</select>
<tbody class="appendData">
</tbody>
not getting values after success function.if anybody face this problem help me.thanks in advance

Uncomment header("Content-type:application/json"); in getcusttype.php

It looks like your alert() function is referencing data Where does data come from? Try alert(customerData) in place of alert(data).
success: function(customerData) {
alert(data);
alert("test");
if(customerData) {
var customer = [customerData];
customerData.forEach(function(item) {
var data = '<tr>';
data+= '<td colspan="4"> </td>';
data+= '<td align="right">'+item.company_id+'</td>';
data+= '<td align="right">'+item.company_name+'</td>';
data+='</tr>';
$('.appendData').append(data);
});
} else {
$("#heading").hide();
$("#records").hide();
$("#no_records").show();
}
}
If you're looking to alert the row that your appending you should move the alert(data) call, as is, down into your forEach() block after you declare your data variable.
Ex:
customerData.forEach(function(item) {
var data = '<tr>';
data+= '<td colspan="4"> </td>';
data+= '<td align="right">'+item.company_id+'</td>';
data+= '<td align="right">'+item.company_name+'</td>';
data+='</tr>';
alert(data);
$('.appendData').append(data);
});

Related

How to pass PHP variable to AJAX URL

Hello guys I am new to javascript
I am trying to send php variable to AJAX url file but i was unable to do it. I don't know where the problem actually arise. your help will be highly appreciated
Here i want to send the below PHP Variable "$cheque" to the AJAX URL Page cheque_select.php
<php? $cheque = '78964Y' ?>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"cheque_select.php",
method:"POST",
dataType:"json",
success:function(data)
{
var html = '';
for(var count = 0; count < data.length; count++)
{
html += '<tr>';
html += '<td><input type="checkbox" id="'+data[count].id+'" data-cheque_no="'+data[count].cheque_no+'" data-id="'+data[count].id+'" data-name="'+data[count].name+'" data-sum="'+data[count].sum+'" data-account="'+data[count].account+'" class="check_box" /></td>';
html += '<td>'+data[count].cheque_no+'</td>';
html += '<td>'+data[count].id+'</td>';
html += '<td>'+data[count].name+'</td>';
html += '<td>'+data[count].sum+'</td>';
html += '<td>'+data[count].account+'</td></tr>';
}
$('tbody').html(html);
}
});
}
fetch_data();
This is my cheque_select.php i want to fetch data from mysql by the above variable
<?php
include('connection.php');
$query = "select * FROM entry where entry.bank= $cheque";
$statement = $connect->prepare($query);
if($statement->execute())
{
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$data[] = $row;
}
echo json_encode($data);
}
?>
Simply add a "data" value in the ajax/jquery request you are firing. This will send data in the form of a POST value to the page that is receiving your ajax request. This is the revised "fetch_data" function after adding the data you wish to send:
function fetch_data()
{
$.ajax({
url:"cheque_select.php",
method:"POST",
dataType:"json",
data:{"cheque":"<?= $cheque ?>"},
success:function(data)
{
var html = '';
for(var count = 0; count < data.length; count++)
{
html += '<tr>';
html += '<td><input type="checkbox" id="'+data[count].id+'" data-cheque_no="'+data[count].cheque_no+'" data-id="'+data[count].id+'" data-name="'+data[count].name+'" data-sum="'+data[count].sum+'" data-account="'+data[count].account+'" class="check_box" /></td>';
html += '<td>'+data[count].cheque_no+'</td>';
html += '<td>'+data[count].id+'</td>';
html += '<td>'+data[count].name+'</td>';
html += '<td>'+data[count].sum+'</td>';
html += '<td>'+data[count].account+'</td></tr>';
}
$('tbody').html(html);
}
});
}
Then on the page that is receiving the request, you would get the cheque value by saying php $_POST['cheque'] . Also one mistake I noticed is you have mistyped your opening PHP tag. You have wrote <php? . The correct way is <?php .
One more thing - you haven't prepared your statement correctly in the PHP page. This is how you should prepare it:
$pre_stmt = "SELECT * FROM entry WHERE entry.bank=?";
$stmt = $conn->prepare($pre_stmt);
$stmt->bind_param(
"i", # if cheque is a numerical value keep it "i" otherwise change it to "s" if it is a string
$cheque
);
$stmt->execute();
#do whatever success condition
Preparing statements like this prevents SQL injection
Add data in your AJAX request like -
<?php $cheque = '78964Y' ?>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"cheque_select.php",
method:"POST",
dataType:"json",
data:{'cheque': "<?php echo $cheque; ?>"},
success:function(data)
{
var html = '';
for(var count = 0; count < data.length; count++)
{
html += '<tr>';
html += '<td><input type="checkbox" id="'+data[count].id+'" data-cheque_no="'+data[count].cheque_no+'" data-id="'+data[count].id+'" data-name="'+data[count].name+'" data-sum="'+data[count].sum+'" data-account="'+data[count].account+'" class="check_box" /></td>';
html += '<td>'+data[count].cheque_no+'</td>';
html += '<td>'+data[count].id+'</td>';
html += '<td>'+data[count].name+'</td>';
html += '<td>'+data[count].sum+'</td>';
html += '<td>'+data[count].account+'</td></tr>';
}
$('tbody').html(html);
}
});
}
fetch_data();
It will send the cheque value to the server end.
And get it at the PHP end just before the query by adding -
<?php
include 'connection.php';
$cheque = $_POST['cheque'];
$query = "SELECT * FROM entry WHERE entry.bank = ?";
$statement = $connect->prepare($query);
$statement->execute([$cheque]);
$data = $statement->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($data);

Populating data from an html table row

The given snippet has a javascript function and a table in which I want to show content of each row using a modal.
But the problem is when I am using alert in middle for debugging for any number of row when I click in view button it always shows the first value of m_id but it must show the corresponding values. $v object is returning expected data only no problem in that.
I need help since I am just a beginner in ajax.
<script type="text/javascript">
function view_message(){
//alert("aa gyaksjhfjxvhk");
var m_id = document.getElementById('m_id').value;
var c_name = document.getElementById('c_name').value;
var message = document.getElementById('message').value;
alert(m_id);
//alert(loc);
$.ajax({
type: "POST",
url: "view_message.php",
data:
{ 'm_id' :m_id,
'c_name' : c_name,
'message' : message
},
success: function(data){
// alert("success");
$(".message_container").html(data);
}
});
}
</script>
foreach($v_message as $v)
{
echo '<tr>';
echo '<td>'.$v->time.'</td>';
echo '<td>'.$v->c_name.'</td>';
echo '<input id="m_id" name="m_id" value="'.$v->id.'" hidden />';
echo '<input id="c_name" name="c_name" value="'.$v->c_name.'" hidden />';
echo '<input id="message" name="message" value="'.$v->message.'" hidden />';
echo '<td data-toggle="modal" data-target="#myModal">';
echo ' <input type="button" id="view" onclick="view_message()" value="view"></input>';
echo '</td>';
echo '<td data-toggle="modal" data-target="#myModal1">
<span>Delete</span>';
echo '</td>';
echo '</tr>'; ?>
<div id="message_container">
</div>
change your selector $(.message_container) to $(#message_container)
modified code is below.
<script type="text/javascript">
function view_message(){
//alert("aa gyaksjhfjxvhk");
var m_id = document.getElementById('m_id').value;
var c_name = document.getElementById('c_name').value;
var message = document.getElementById('message').value;
alert(m_id);
//alert(loc);
$.ajax({
type: "POST",
url: "view_message.php",
data:
{ 'm_id' :m_id,
'c_name' : c_name,
'message' : message
},
success: function(data){
// alert("success");
$("#message_container").html(data);
}
});
}
</script>
because your selector is document, its find first element with target id, so always first row element return in result.in php code replace onclick="view_message()" with class="view-btn" and use my answer javascript,
<script type="text/javascript">
$(document).ready(function() {
var view_message = function(){
var row = $(this).closest('tr');
var m_id = $(row).find('#m_id').val();
var c_name = $(row).find('#c_name').val();
var message = $(row).find('#message').val();
alert(m_id);
}
$(".view-btn").on('click', view_message);
});
</script>
foreach($v_message as $v)
{
echo '<tr>';
echo '<td>'.$v->time.'</td>';
echo '<td>'.$v->c_name.'</td>';
echo '<input id="m_id" name="m_id" value="'.$v->id.'" hidden />';
echo '<input id="c_name" name="c_name" value="'.$v->c_name.'" hidden />';
echo '<input id="message" name="message" value="'.$v->message.'" hidden />';
echo '<td data-toggle="modal" data-target="#myModal">';
echo ' <input type="button" id="view" class="view-btn" value="view"></input>';
echo '</td>';
echo '<td data-toggle="modal" data-target="#myModal1">
<span>Delete</span>';
echo '</td>';
echo '</tr>'; ?>
<div id="message_container">
</div>
IDs must be unique in the document. See: stackoverflow.com/a/9454716/2181514.
Your for loop generates multiple items with the same id, so when you do $(#id you get the first one.
You can fix this by using classes and passing a reference to the current row:
Change
onclick="view_message()"
<input id="m_id" name="m_id"
to
onclick="view_message(this)"
<input class='m_id' id="m_id" name="m_id"
then:
function view_message(el){
var row = $(el).closest("tr");
var m_id = $(".m_id", row).val();
Update: typo - should have been $(el).closest, not $(this)
Example fiddle: https://jsfiddle.net/37tkgsnm/
html:
<tr>
<td><input class='m_id' value='123' /></td>
<td><button type="button" onclick="view_message(this);">click</button></td>
</tr>
js:
function view_message(el) {
var row = $(el).closest("tr");
alert($(".m_id", row).val())
}

List with elements from database in cloned jquery <tr>

I have a js script that inserts html elements into the page everytime a button is clicked. In one of those inputs(Select) i want to show a list of options retrieved from a database. I have the correct code for this but I have no idea how to combine them because i can not place PHP into JS.
My code:
var rowCount = 0;
function add_product()
{
var $table = $('table');
var generateRow = function(indx){
$table.append('<tr>\n\
<td></td>\
<td>\
<b>Aantal: </b><input style="width: 60px;" id="aantal" name="aantal_'+indx+'" type="number" min="0" required>\
</td>\
<td>\
<b>Product: </b><select name="products_'+indx+'" type="text" required>\n\
</select>\
</td>\
</tr>');
}
generateRow(++rowCount);
}
<?php
$productQuery = mysql_query("SELECT * FROM voorraad")
while ($productInfo = mysql_fetch_array($productQuery))
{
$productID = $productInfo[0];
$product = $productInfo[1];
echo "<option value='$productID'>$product</option>";
}
?>
This is not the best method of doing what you're trying to achieve, but using the method you have started then it can be accomplished like this.
First you need to put the options string into a PHP variable
Then put that options string into a javascript variable.
This also assumes that your PHP and Javascript are all in the same document and that your PHP code is above your Javascript in the document.
<?php
$options = '';
$productQuery = mysql_query("SELECT * FROM voorraad")
while ($productInfo = mysql_fetch_array($productQuery))
{
$productID = $productInfo[0];
$product = $productInfo[1];
$options .= "<option value='$productID'>$product</option>";
}
?>
var options = "<?php echo $options; ?>";
var rowCount = 0;
function add_product()
{
var $table = $('table');
var generateRow = function(indx){
$table.append('<tr>\n\
<td></td>\
<td>\
<b>Aantal: </b><input style="width: 60px;" id="aantal" name="aantal_'+indx+'" type="number" min="0" required>\
</td>\
<td>\
<b>Product: </b><select name="products_'+indx+'" type="text" required>\n\
' + options + ' </select>\
</td>\
</tr>');
}
generateRow(++rowCount);
}
You can do it like this:
jQuery.ajax({
type: "POST",
url: 'your_functions_address.php',
dataType: 'json',
data: {functionname: 'add', arguments: [1, 2]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
From:
How can I call PHP functions by JavaScript?

AJAX On Keyup Search Function

I wrote a AJAX search function which grabs the keyword values on key up and fires off the script. My goal is to have it populate the content area every key reordering the results to be in ABC order.
Instead what's happening is the first key fires off and the top result is always this
*ENGRAVING
then the rest of the values under it are in no specific order that I can tell.
I think this has to do with escaping characters?
Any help would be appreciated. Please help me get this to function so as a user searches the content area reorders itself being in order based on the keyword being searched up to the value that has been entered at that time.
On page load 5 results are added to the page then on page scroll more results are added to the page like this,
var assetPath = "<?php echo $assetPath ?>";
var searchPath = "<?php echo $searchPath ?>";
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
async: false,
url: assetPath,
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#productResults").append(html);
$('#loader_image').hide();
if (html === "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show();
} else {
$("#loader_message").html('Loading... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
Then when a user wants to search they use this form,
<div class="form-group pull-right">
<input type="text" name="itemID" id="itemID" class="search form-control" placeholder="Search product number">
</div>
Then this ajax function fires off on keyup
$("#itemID").keyup(function (){
var itemID = $(this).val();
var url = searchPath;
$.ajax({
type : "GET",
async : false,
url : url,
data : "itemID=" + encodeURIComponent(itemID),
cache : false,
success: function(html) {
$('#loader_image').hide();
$( "#productResults" ).replaceWith( html );
if (html === "") {
$("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
} else {
$("#loader_message").html('Searching... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
});
which runs this script at searchPath as the path variable
require_once ('Dbconfig.php');
$sql=" SELECT * FROM wuno_inventory WHERE wuno_product like '%".$itemID."%' OR wuno_alternates like '%".$itemID."%' ORDER BY wuno_product ";
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<tr class="invent">';
echo '<td>' . $res['wuno_product'] . '</td>';
echo '<td>' . $res['wuno_alternates'] . '</td>';
echo '<td>' . $res['wuno_description'] . '</td>';
echo '<td>' . $res['wuno_onhand'] . '</td>';
echo '<td>' . $res['wuno_condition'] . '</td>';
echo '</tr>';
}
}
The initial data populates perfectly in order from what is in the database. So I do not see why there would be problems for this function if it is a escaping situation.
Also the initial data is paginated. Would this cause a problem with the second query? I was thinking maybe since there is so much data it's all being appended to the content instead of replacing it. Maybe the jquery is conflicting?
Try introducing the timeout for your AJAX call. Move your AJAX JS into a separate function first:
function get_search_results(event) {
var itemID = $(event.target).val();
var url = searchPath;
$.ajax({
type : "GET",
async : false,
url : url,
data : "itemID=" + encodeURIComponent(itemID),
cache : false,
success: function(html) {
$('#loader_image').hide();
$( "#productResults" ).replaceWith( html );
if (html === "") {
$("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
} else {
$("#loader_message").html('Searching... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
Then add it to your keyup handler:
$("#itemID").keyup(function (){
setTimeout(get_search_results, 200);
});

AJAX Search Function Not Updating Answer

I have an AJAX function that calls a php function to search a mysql database. The script fires off on keyup and the problem is on the first key press the html content is updated but it will not update after the initial keyup event
How do I make the page continuously update the html content with the new data that is coming in after every keyup.
My AJAX function,
var searchPath = "<?php echo $searchPath ?>";
$("#itemID").keyup(function (){
var itemID = $(this).val();
var url = searchPath;
$.ajax({
type : "GET",
async : false,
url : url,
data : "itemID=" + encodeURIComponent(itemID),
cache : false,
success: function(html) {
$('#loader_image').hide();
$( "#productResults" ).replaceWith( html );
if (html === "") {
$("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
} else {
$("#loader_message").html('Searching... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
});
And this is the php behind it all,
<?php
require_once ('Dbconfig.php');
$sql=" SELECT * FROM wuno_inventory WHERE wuno_product like '%".$itemID."%' OR wuno_alternates like '%".$itemID."%' ORDER BY wuno_product ";
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<tr class="invent">';
echo '<td>' . $res['wuno_product'] . '</td>';
echo '<td>' . $res['wuno_alternates'] . '</td>';
echo '<td>' . $res['wuno_description'] . '</td>';
echo '<td>' . $res['wuno_onhand'] . '</td>';
echo '<td>' . $res['wuno_condition'] . '</td>';
echo '</tr>';
}
}
?>

Categories