Data not getting passed to the ajax function - javascript

The form below is present in every row of an html table.However alert("dfd") pops up only for the first row of the table and not for the forms in the other rows(these forms appear on the webpage).Can anyone tell why is it happening?
HTML:
<form class='form form-horizontal' method='post' role='form' id='formsel' name='formsel'>
<fieldset >
<div>
<span class='control-group' >
<span class='controls'>
<select id='formcont' name='formcont' class='form-control' style='cursor:pointer;'>
<option selected='selected' style='display:none;'>Select</option>
<option value='1'>Option1</option>
<option value='2'>Option2</option>
<option value='3'>Option3</option>
</select> <button id='selbtn' name='selbtn' type='submit'>Sub,it</button>
</span>
</span></div>
</fieldset>
</form>
JS:
$("#formsel").submit(function () {
alert("dfd");
$.ajax({
url:"add.php",
data:$("#formcont").val().serialize(),
type:"POST",
success:function(data){
console.log(data);
if(data=="done"){
alert("success");
}
},
error:function(data){
alert("Network ERROR");
}
})
return false;
});
$("#selbtn").click(function () {
("#formsel").submit();
});
PHP:
<?php
include ('db.php');
session_start();
echo "done";
?>

Yes, because you're not sending any data:
$("#formcont").val().serialize()
Should be:
$(this).serialize()
Since the button you're clicking to trigger the submit is a submit button, you really do not need the following code:
$("#selbtn").click(function () {
("#formsel").submit();
});

Related

How to create or populate a table with data returned by an AJAX call

I have a webpage where I have a user enter in a search and when they enter the search I want data returned by my PHP script to be displayed as a table below the search area. My AJAX call successfully calls my PHP script which retrieves the data successfully. However the HTML elements/data aren't displayed. What is the proper way to generate HTML elements? Is the correct approach to have a PHP script generate them or is it possible to pass the results into some JavaScript function which creates the elements instead?
$sql = "SELECT supplierName, about FROM suppliers";
if ($res = mysqli_query($myConnection, $sql)) {
if (mysqli_num_rows($res) > 0) {
echo "<table>";
while ($row = mysqli_fetch_array($res)) {
//error_log('row');
echo "<tr>";
echo "<td>".$row['supplierName']."</td>";
echo "<td>".$row['about']."</td>";
echo "</tr>";
}
}
echo "</table>";
}
mysqli_close($myConnection);
The commented out error_log outputs the expected amount.
Rough HTML code
<head>
<meta charset="utf-8">
</head>
<body>
<main>
<div id="searchQuery">
<form>
<form action="" method="post" id="form">
<fieldset>
<table>
<tr>
<td>
Food Type*:
<select name = "type" id = "type" style="width:100%">
<option value="Meat">Meat</option>
<option value="Produce">Produce</option>
<option value="Dairy">Dairy</option>
<option value="Grain">Grain</option>
</select>
</td>
<td>
Price: <br>
<select name = "price" id = "price" style="width:100%">
<option value="none">None</option>
<option value="Low to High">Low to High</option>
<option value="High to Low">High to Low</option>
</select>
</td>
</tr>
<tr>
<td>
Food Grade*:
<select name="grade" id="grade" style="width:100%">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="F">F</option>
</select>
</td>
<td>
Organic:
<select name="organic" id="organic" style="width:100%">
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</td>
</tr>
<tr>
<td>
Supplier Name: <br>
<input type="text" name="name" id="name" style="width:95%">
</td>
<td>
<button type="submit" id = "submit" class="button1" form="form" value="Submit" name="submit" style="width:50%">Submit</button>
</td>
</tr>
</table>
</form>
</fieldset>
</form>
</div>
//data displays here <-
</main>
</body>
</html>
Edit: here is the ajax call/form code
'''
$(function() {
$(".button1").click(function() {
var type = $("select#type").val();
var grade = $("select#grade").val();
var organic = $("select#organic").val();
var price = $("select#price").val();
var name = $("input#name").val();
var submit = $("button#submit").val();
$.ajax({
type: "POST",
url: "searchQuery.php",
data: {submit:submit, type: type, grade:grade, organic:organic, price: price, name: name},
success: function() {
console.log('query submitted');
}
});
To anwser your first question: the elements aren't displayed because they occur in an "Asynchronous JavaScript And XML" call (AJAX) which happens outside your page and the only thing you are doing after calling it is:
console.log('query submitted');
you need to somehow send the information back to your page and the way most easy to mantain would be to use PHP to return a JSON (or XML if that's your thing) with something like this:
PHP :
if (mysqli_num_rows($res) > 0) {
$table= array();
while ($row = mysqli_fetch_array($res)) {
array_push($table,array(
'supplierName'=>$row['supplierName'],
'about'=>$row['about']
));
}
echo json_encode($table)
}
And then you can use javascript to generate the table based on the returned json with something like this:
JAVASCRIPT:
success: function(data) {
var myTable = document.getElementById('myTable');
for (i in data) {
var tr = myTable.appendChild(document.createElement('tr'));
for (key in data[i]){
var td = tr.appendChild(document.createElement('td'));
td.title = key;
td.innerHTML = data[i][key];
}
}
}
HTML
//data displays here <-
<table id="myTable"></table>
Some relevant links:
https://www.php.net/manual/en/function.json-encode.php
https://api.jquery.com/jQuery.ajax/
https://www.w3schools.com/jsref/met_document_createelement.asp
Please feel free to add any comment if you would like further clarification.
Yes it is possible
Add success: function(data){} where data is the already defined variable has value is the result you can perform functions using this variable:
$.ajax({
type: "POST",
url: "searchQuery.php",
data: {submit:submit, type: type, grade:grade, organic:organic, price: price, name: name},
success: function(data) {
console.log('query submitted');
document.querySelector("main")[0].append(data);
}
});

how to create selected item and input what item is

i wanna learn how to search something from database, and it's work, here the code
<fieldset>
<form action="" method="POST">
By Round Id : <input id="input-round" type="text" name="name" size="15"/><br/><br/>
By Player Id : <input id="input-player-id" type="text" name="player" size="15"/><br/><br/>
<input id="btn-form-close" type="button" value="Cancel" />
</form>
<script type="text/javascript">
$("#btn-form-close").click(function(){
$('#view-form').html('');
});
$('#input-round').keyup(function(){
var name = $('#input-round').val();
$.ajax({
type:"POST",
url:"<?php echo site_url('account/look_search_history_round');?>",
data:'nama='+name,
success:function(html){
$('#view-list-round-id').html(html);
}
});
});
$('#input-player-id').keyup(function(){
var player = $('#input-player-id').val();
$.ajax({
type:"POST",
url:"<?php echo site_url('account/look_search_history_player');?>",
data:'nama='+player,
success:function(html){
$('#view-list-round-id').html(html);
}
});
});
but i wanna create something like option can be selected, so i can selected search By Round Id or By player Id. but i don't have any idea how to accomplish that. what i get is select that option
<select class="form-control" id="sel1">
<option> By Round Id </option>
<option> By Player Id</option>
</select>
but what about input? can someone give me example, thanks a lot
First you may want to include in the form:
<form action="" method="POST">
Search by
<select class="form-control" id="sel1">
<option id="roundId"> By Round Id </option>
<option id="playerId"> By Player Id</option>
</select>
Id : <input id="input-round" type="text" name="name" size="15"/><br/><br/>
<input id="btn-form-close" type="button" value="Cancel" />
</form>
then send the selected option to backend to process
$('#input-round').keyup(function(){
var name = $('#input-round').val();
var choice = $('#sel1 option:selected').val()
$.ajax({
type:"POST",
url:"<?php echo site_url('account/look_search_history_round');?>",
data:'nama='+name+'&choice='+choice, //process this choice in backend..
success:function(html){
$('#view-list-round-id').html(html);
}
});
});
you have not given value for option
change it like this
<select class="form-control" id="sel1">
<option value="1" data-id="2"> By Round Id </option>
<option value="2" data-id="1"> By Player Id</option>
<option value="3" data-id="2"> By Round Id </option>
</select>
and the jquery function
$('#sel1').change(function(){
var player = $(this).val();
var PR_id = $(this).find(':selected').attr('data-id');
if(PR_id == 1)
{
$.ajax({
type:"POST",
url:"<?php echo site_url('account/look_search_history_player');?>",
data:'nama='+player,
success:function(html){
$('#view-list-round-id').html(html);
}
});
}
else if(PR_id ==2)
{
//next ajax call
}
});
thanks all now i get it, here the code i want it
<form action="" method="POST">
Search by
<select class="form-control" id="select">
<option id="roundId"> Rounds Id</option>
<option id="playerId"> Player Id</option>
</select>
: <input id="input" type="text" name="input" size="15"/><br/><br/>
<input id="submit" type="button" value="Search" />
</form>
jquery function like this
<script type="text/javascript">
$("#btn-form-close").click(function(){
$('#view-form').html('');
});
$("#submit").click(function(){
var data = {
'select' : $("#select").val(),
'input' : $("#input").val(),
};
//alert ($("#input").val());
$.ajax({
type:"POST",
url:"<?php echo site_url('account/look_search_history');?>",
data:data,
success:function(html){
$('#view-list-round-id').html(html);
}
});
});
</script>
and about controller is here
public function look_search_history(){
if($_POST['input']){
$select = $_POST['select'];
$input = $_POST['input'];
if ($select == "Rounds Id"){
$data['tbl_bet_spot'] = $this->login_model->select_by_round($input)->result();
$this->load->view('roulette/view_search_history', $data);
}else if ($select == "Player Id"){
$data['tbl_bet_spot'] = $this->login_model->select_by_player($input)->result();
$this->load->view('roulette/view_search_history', $data);
}
}
}

jQuery, JavaScript - Network Error?

I am working on building a Javascript/jQuery and AJAX website. However, while testing I am encountering the following error:
Timestamp: 6/11/2016 10:13:45 AM
Error: NetworkError: A network error occurred.
To me, the most obvious culprit would be the AJAX call made in my script; however, I tried commenting it out and still received the same error. When the website is first loaded it displays three alert boxes (selection=category&detail=test, and so on), but then the error appears and changing the selection does not trigger the alert.
Here is my main page:
<?php
include('header.php');
?>
<div id='mainContent'>
<?php /* if(!$_SESSION['admin']) {
echo "<p>You do not have permission to view this page!</p>";
} else { */
echo "<form method='post' action='addItem.php'>
<div class='form-group'>
<label>Category</label>
<select id='categorySelection' name='categorySelection'>
<option value=1>Playstation</option>
<option value=2>Wii</option>
<option value=3>Gamecube</option>
<option value=4>N64</option>
<option value=5>Other Console</option>
<option value=6>DS</option>
<option value=7>Game Boy</option>
<option value=8>Other Handheld</option>
<option value=9>DVD</option>
</select>
</div>
<div class='form-group'>
<label>Item</label>
<select id='itemSelection' name='itemSelection'>
</select>
</div>
<div class='form-group'>
<label>Condition:</label>
<select id='conditionSelection' name='conditionSelection'>
<option value=1>Acceptable</option>
<option value=2>Good</option>
<option value=3>Very Good</option>
<option value=4>New</option>
</select>
</div>
<div class='form-group'>
<label>Price: </label>
<input id='itemPrice' type='text' name='itemPrice' />
</div>
<div class='form-group'>
<label>Description: </label>
<textarea id='itemDescription' name='itemDescription'></textarea>
</div>
</form>";
// }
?>
</div>
<script>
function selectionHandler(selectedAction, selectedValue) {
var gameData = "selection=" + selectedAction + "&detail=" + selectedValue;
alert(gameData);
$.ajax({
type: 'POST',
url: 'filter.php',
data: gameData,
success: function(returnData) {
if(selectedAction == 'category') {
$('#itemSelection').html(returnData);
} if(selectedAction == 'game') {
$('#itemPrice').val(returnData)
} else {
$('itemDescription').val(returnData);
}
} // end return
}); // end ajax
} // end handler
$(document).ready(function() {
$("#categorySelection").on("change", selectionHandler('category', "test" ) ) ;
$("#itemSelection").on('change', selectionHandler('game', "test" ) );
$("#conditionSelection").on('change', selectionHandler('condition', "test" ) );
}); // end ready
</script>
<?php
include('footer.php');
?>
and my PHP
<?php
include("header.php");
$db = new pdoAccess("localhost","root","");
$selection = $_POST['selection']; // either game, category, or condition
$detail = $_POST['detail'] // either categoryID or ISBN/Item ID
if($selection == 'category') {
$products = $db->filterByCategory($detail);
$html = "";
foreach($products as $product) {
$html += "<option value={$product->upc)}>$product->title</option>";
}
return $html;
} elseif ($selection = 'game') {
return $db->getProductPrice($detail);
} else {
return $db->getCategoryDescription($detail);
}
?>
Thanks!
EDIT: It should be noted that I also tried other events such as focusout and select. Same issue.
In php string cocatinating is by dot . and use quotes also change here like this
$html .= "<option value='{$product->upc)}'>{$product->title}</option>";
Also use double == to compare here
} else if ($selection == 'game') {
Use echo in ajax instead of return

JavaScript from ajax modified file doesn't work in main page

I have a problems with a form and ajax behavior when I populate my dynamic div using JavaScript.
I have a drop box which contains different time periods and it triggers JavaScript function which modifies the container div based on provided value.
The problem is that the POST behavior of the form and all JavaScript elements doesn't work in the main file.
Here is the code. I simplified it to emphasize the problem.
this is the drop Box:
//jQuery for datePicker comes here
<select id="QSelector" method="post" onchange="populateDiv(this.value)">
<option value="0">All Values</option>
<option value="1">Sets for 1</option>
<option value="2">Sets for 2</option>
<option value="3">Sets for 3</option>
<option value="4">Sets for 4</option>
</select>
<div id="OUtputDiv" ></div>
here is the javascript function:
function populateDiv(id){
var xmlhttp;
if(window.XMLHttpRequest){//safari, chrome, opera, ffox
xmlhttp=new XMLHttpRequest();
}
else{//IE
xmlhttp=ActiveXObject("Microft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("OUtputDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../scripts/supportFile.php?ID=" + id, true);
xmlhttp.send();
}
And here is the content of the support file. don't mind the id variable it does some logic (ant it works), but I removed it because it's irrelevant to a given problem.
<?php
$Id= $_GET['ID'];
echo "<script> alert('it works'); </script>";
echo "<form name='AddForm' class='AddForm' method='post' >";
echo "<span > Date: </span> <input type='textbox' id='datepicker' name='datepicker' > ";
echo "<input type='submit' name='SubBtn' value='Save' >";
echo "</form>";
if(isset($_POST['SubBtn']))
{
echo $_POST["datepicker"];
}
?>
Nether JavaScript or JQuery does not work from the main file. And form does not post anything if I press the save button.
Can anyone suggest how can I make it responsive in the main file where I call ajax function from?
Avoid using IE5/6 support, use jQuery instead:
The problem is that you put all code in the same page, it will not work in that way, you need to make 2 files, 1 for post 1 for result
Good:
test_post.php
<?php
$Id = $_POST['id'];
if(!empty($Id)){
$result = "
<script> alert('it works'); </script>
<form name='AddForm' class='AddForm' method='post' >
<span > Date: </span> <input type='textbox' id='datepicker' name='datepicker' >
<input type='submit' name='SubBtn' value='Save' >
</form>
";
echo json_encode(array('status' => 'success', 'result' => $result));
}
?>
test.php
<select id="QSelector">
<option value="0">All Values</option>
<option value="1">Sets for 1</option>
<option value="2">Sets for 2</option>
<option value="3">Sets for 3</option>
<option value="4">Sets for 4</option>
</select>
<div id="OUtputDiv" ></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
var $ =jQuery.noConflict();
$(document).ready(function(){
$(document).on( "change", '#QSelector',function(e) {
e.preventDefault();
var id = $(this).val();
$.ajax({
type: "POST",
url:"<?php echo './test_post.php'; ?>",
data: {id: id},
dataType: 'json',
success: function(data){
if(data.status == 'success'){
$('#OUtputDiv').html(data.result);
}
}
});
});
});
</script>

ddSlick select on change submit form

I am using ddslick. Is it possible on change to submit form ?
My code:
<form method="post" class="town_form">
<select name="town" id="select_town">
<option value="83">Chicago</option>
<option value="112">New York</option>
</select>
</form>
<script>
$('#select_town').ddslick({
onSelected: function(selectedData){
$('.town_form').submit();
}
});
</script>
But its not working ... any help ?
$('#select_town').dblclick(function() {
onSelected: function(data){
if (data.selectedIndex > 0) {
$('form.town_form').submit();
}
}
});

Categories

Resources