getting the rest of the row in a database using JQuery - php

Ok, so I have this search box in which people typein a food item. When they press the button I need that input to be send to a .php file. That php file will look op the calories of that food item (thats in my database) and output the food item name and calories. All this need to be done without reloading the page so I started figuring out how JQuery works.
However I am stuck, I don't know what to put in the data field of the jquery function and how I can 'catch' that data in the .php file. Can someone give me an idea? thanks a lot! (see the ??????'s for things i don't understand). Also, the data that comes back needs not to be in an alert box in the end, but update some table on my page, how can i do this? which JSON (?) Jquery function do I need?
what I have up until now:
in head:
<script type="text/javascript">
function contentDisp()
{
$.ajax({
type: 'POST',
url: 'getFood.php',
data: '????????',
success: function(data){
alert("Data Loaded: " + data);
}
});
}
</script>
and in body:
<form autocomplete="off">
<p>
Product:
<input type="text" name="food" id="food" class="food_name_textbox" onmouseover="javascript: this.className='food_name_textbox_mouseover';" onmouseout="javascript: this.className='food_name_textbox';" / >
</p>
<button id="zoek" type="button" onClick="contentDisp();">Zoek</button>
</form>
and in getFood.php:
<?php
require_once "config.php";
$id = "??????"
$result = mysql_query("SELECT * FROM voedingswaarden WHERE voedsel='$id'");
$row = mysql_fetch_array($result);
echo json_encode($row);
?>

$.ajax({
type: 'POST',
url: 'getFood.php',
data: {'foodnametextbox' : $('#food').val() },
datatype: "json",
success: function(data){
$('#table').html(data);
}
});
<?php
require_once "config.php";
$id = $_POST['foodnametextbox']; //escape and validate this input before using it in a query
$result = mysql_query("SELECT * FROM voedingswaarden WHERE voedsel='$id'");
$row = mysql_fetch_array($result);
echo json_encode($row);
?>

<script type="text/javascript">
function contentDisp()
{
var textSearch = $("#myText").text();
$.ajax({
type: 'POST',
url: 'getFood.php',
data: textSearch,
success: function(data){
alert("Data Loaded: " + data);
}
});
}
</script>
PHP:
$id = $_POST['textSearch'];

Related

Update div in html using Ajax function failed

I'm trying to display the search result of my page under the the search area. So I used AJAX to display the result in a div. but I could'nt get it work.
I have three main pieces, the div, the searchResult page and the ajax function
<input type="text" name="studentName">
<button type="submit" name="searchByName" onclick='get_info();'>بحث</button>
<div id="searchResult"><b></b></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function get_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "NameSearchResult.php", // Name of the php files
data: {name: <?php echo $_POST['studentName']; ?>},
success: function(html)
{
$("#searchResult").html(html);
}
});
}
and my search Page:
<?php
include_once 'dbConfigBDO.php';
$studentName = $_POST["name"];
$counter=0;
$emptyString = "لايوجد";
$sql = "SELECT * FROM Student";
$result = $conn->query($sql);
$row_count = $result->rowCount();
if ($row_count > 0){
.......... }
Now when I search nothing appears, although it works when I put all the code in one page (which would be messy in term of the appearance of the result!).
From function return the output as per below:
return json_encode($result);
In ajax call use dataType:"json" and show your html
Example ajax call:
$.ajax({
type: "POST",
dataType:"json",
url: "NameSearchResult.php", // Name of the php files
data: {name: $("#studentName").val()},
success: function(html)
change code like this
<input type="text" name="studentName" id="studentName">
<button type="submit" name="searchByName" onclick='get_info();'>بحث</button>
<div id="searchResult"><b></b></div>
<script>
$.ajax({
type: "POST",
url: "NameSearchResult.php", // Name of the php files
data: {name: $("#studentName").val()},
success: function(html)
{
$("#searchResult").html(html);
}
});
}
</script>
inside ajax success method try catch what you are getting
success: function(html)
{
console.log(html);
}
if you getting something then your code must be work.

AJAX seems to be sending entire web page script rather than data

I am having real trouble with my AJAX request and I am not sure why. The following code seems to send to the entire web page script (as seen in both my alert box and in the console) rather than my checkbox values. Can anyone explain to me what I am doing wrong?
Here is my PHP checkbox, which has values generated by SQL, and has no submit button so the code is set up to run on change from the user:
<form id="numberOrderForm" action="testdatabase.php" method="post">
<div class="wrappers" id="multi-select1Wrapper">
<h2>Area Code</h2>
<select class="dropDownMenus" id="multi-select1" name="multi_select1[]" multiple="multiple">
<?php
//The query asking from our database
$areaCodeSQL = "SELECT ac.Number AS `AreaCode`, ac.Name AS `AreaName`
FROM `AreaCodes` ac"; //SQL query: From the table 'AreaCodes' select 'Number' and put into 'AreaCode', select Name and put into 'AreaName'
$areaCodeResults = $conn->query($areaCodeSQL); // put results of SQL query into this variable
if ($areaCodeResults->num_rows > 0) { // if num_rows(from $results) is greater than 0, then do this:
// output data of each row
foreach($areaCodeResults as $areaCodeResult) //for each item in $areCodeResults do this:
{
$areaNameAndCode = $areaCodeResult['AreaCode'] ." ". $areaCodeResult['AreaName']; //get AreaCode and AreaName from query result and concat them
$areaName = $areaCodeResult['AreaName']; // get AreaName
$areaCode = $areaCodeResult['AreaCode']; //get AreaCode
?><option class="menuoption1" name="menuAreaCode" value="<?php echo $areaCode ?>" ><?php echo $areaNameAndCode; ?></option><?php //Create this option element populated with query result variables
}
}
?>
</select>
</div>
</form>
And here is my jQuery AJAX code:
<script>
$('#multi-select1').on("change", function(){
var areaCode = $(this).val();
$.ajax({
type:"POST",
url: "testdatabase.php", //my PHP database
data: "areacode=" + areaCode,
success: function(response){
//do stuff after the AJAX calls successfully completes
alert (response);
console.log(response);
},
error : function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
</script>
your data is incorrect for one.
replace:
data: "areacode=" + areaCode,
with:
data: {"areacode": areaCode},
you should also add: enctype='multipart/form-data' to your form element
Please add following line on jquery ajax call
dataType: 'json'
contentType: "application/json",
After add above code your code is like below
<script>
$('#multi-select1').on("change", function(){
var areaCode = $(this).val();
$.ajax({
type:"POST",
url: "testdatabase.php", //my PHP database
data: "areacode=" + areaCode,
dataType: 'json',
contentType: "application/json",
success: function(response){
//do stuff after the AJAX calls successfully completes
alert (response);
console.log(response);
},
error : function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
</script>

Form not saving data to MySQL database

I am having trouble recording a single data (deckName) from this form to my MySQL database. I read and tried all the solutions I found over the web, but I cannot get it to work. Doing the MySQL command from the PHPMyAdmin work fine.
I need to save in the deck table of the db (id, name, cards) the values.
Jquery/Ajax script:
<script>
$(document).ready(function(){
$(document).on('submit','.save',function(){
var deckName = $('.deck').val();
console.log(deckName);
$.ajax({
type: "POST",
url: "submit.php",
data: { "name": deckName},
success: console.log('worked')
});
});
});
</script>
Form:
<div class="decklist">
<form method="post" id="decklist">
<input class="deck" id="deckN" type="text" value="Deck name"/>
<input class="save" type="submit" value="Save Deck"/>
</form>
<div class="list">
<ul class="d_list">
<li class='added_card' id='list_0'></li>
</ul>
</div>
</div>
submit.php:
<?php
if(isset($_POST["name"])&& strlen($_POST["name"])>0){
$deckName = $_POST["name"];
$cards = 0;
echo $deckName;
$conn = new mysqli("localhost:8080","root","","ken");
if($conn -> connect_errno){
die("Failed to connect: (". $conn->connect_errno. ")".$conn->connect_error);
}
$insert = $conn->query ("INSERT INTO `deck` (deck, cards) VALUES ($deckName, $cards)");
if ($insert){
echo 'Successfully saved '. $deckName;
$conn -> close();
}
}
?>
Also once I hit Save Deck for submit, the div get refreshed while I assume it shouldn't with ajax.
I tried using click instead of submit, and the console.log returned everything correctly from the ajax function and the div wasn't refreshing every time, but with submit logs don't show up anymore in console.
I don't get anything from the echo in submit.php, never.
Try using preventDefault; like so
$(document).on('submit','.save',function(e){
e.preventDefault;
Hope it solves your problem !
You have to put quotes around string values:
"INSERT INTO `deck` (deck, cards) VALUES ('$deckName', $cards)"
how about change js like this:
$(".decklist").on("click", ".save", function(){
$.post("submit.php", { name: deckName }).success(function(){
console.log('worked');
});
});
You need to bind on the form submit event :
$(document).ready(function(){
$("#decklist").on('submit',function(e){
e.preventDefault();
var deckName = $('.deck').val();
console.log(deckName);
$.ajax({
type: "POST",
url: "submit.php",
data: { "name": deckName},
success: function(response) {
console.log('worked')
}
});
});
});
$(document).ready(function(){
$("#decklist").on('submit',function(e){
e.preventDefault();
var deckName = $('#deck').val();
console.log(deckName);
$.ajax({
type: "POST",
url: "submit.php",
data: { "name": deckName},
success: function(response) {
console.log('worked')
}
});
});
});
it works form me, change $('#deck').val();

Update Mysql records using Ajax/Json isn't working

What I'm trying to do is to edit mysql records using php. I've used Ajax/Json to edit a single record, but the problem is my codes isn't working. I tried to alert the value of input element after I clicked the save button and the alert output is verified. And also I don't get any message in console.
Here's what I got right now. Any help will appreciate.
Index.php
<div class="entry-form1">
<form action="" method="post">
<input type="text" name="id_edit" id="id_edit" class="inputs_edit">
<input type="text" name="approved_edit" id="approved_edit" class="inputs_edit">
<input type="submit" name="save_edit" id="save_edit" value="Save"/>
</form>
</div>
Search.php
$query1 = $mysqli->query(""); // not to include
while($r = $query1->fetch_assoc()){
<td><a href='#' name='".$r['id']."' id='".$r['pr_id']."' class='edits'>Edit</a></td>
}
<script>
$(document).ready(function(){
$(".edits").click(function(){
$(".entry-form1").fadeIn("fast");
//not to include some parts of codes
$.ajax({
type: "POST",
url: "auto-complete.php",
data :edit_post_value,
dataType:'json',
success:function(data){
var requested=data.requested;
var id=data.id;
//send to element ID
$('#id_edit').val(id);
$('#requested_edit').val(requested);
}
});
$("#save_edit").click(function () {
var two = $('#id_edit').val();
var five = $('#requested_edit').val();
alert(five);
$.ajax({
type: "POST",
url: "item_edit.php",
data: "id_edit="+two+"&requested_edit="+five,
dataType:'json',
success: function(data){
console.log(JSON.stringify(data))
if(data.success == "1"){
$(".entry-form1").fadeOut("fast");
//setTimeout(function(){ window.location.reload(); }, 1000);
}
}
});
});
});
</script>
Item_edit.php
<?php
$mysqli = new mysqli("localhost", "root", "", "app");
if(isset($_POST['id_edit'])) {
$id_edit= $_POST['id_edit'];
$requested_edit= $_POST['requested_edit'];
$sql = $mysqli->query("UPDATE pr_list SET requested='$requested_edit' WHERE id='$id_edit'");
if($sql){
echo json_encode(array( "success" => "1"));
}else{
echo json_encode(array("success" => "0"));
}
}
?>
1) First, you're not capturing the click event, because $("# save_edit") is within a function that is not being called. So, you're not even sending the form to the server.
2) Second, the way a form works by default send the data and then reload the page, you must call the preventDefault() function from the event object captured to prevent it, before making the ajax call.
try this:
$(document).ready(function(){
$("#save_edit").click(function (e) {
e.preventDefault(); //prevent a page reload
var two = $('#id_edit').val();
var five = $('#requested_edit').val();
alert(five);
$.ajax({
type: "POST",
url: "/item_edit.php",
data: "id_edit="+two+"&requested_edit="+five,
dataType:'json',
success: function(data){
console.log(JSON.stringify(data));
if(data.success == "1"){
$(".entry-form1").fadeOut("fast");
//setTimeout(function(){ window.location.reload(); }, 1000);
}
}
});
});
});

Typeahead input field and query passed to PHP with AJAX

I am using Twitter Bootstrap Typeahead for an autocomplete field.
End state goal: The user first enters details into field 1. When they enter details in field 2, ajax passes the query as it is written to a PHP file which queries a database based on what was also entered into field 1.
How do I pass both the query from field 2 and the contents of field 1 to the PHP file and access them.
Here is what I have so far:
HTML FILE:
<div class="field1">
<input type="text" id="field1" data-provide="typeahead" name="field1">
</div>
<div class="field2">
<input type="text" id="field2" data-provide="typeahead">
</div>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/bootstrap.js"></script>
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
PHP FILE:
if (isset($_POST['query'])) {
$db_server = mysql_connect("localhost", "root", "root");
mysql_select_db("db_test");
$query = $_POST['query'];
$other = '**This needs to be field 1**';
$sql = mysql_query("SELECT * FROM table WHERE row1 LIKE '%{$query}%' AND row2 = '$other'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['row1'];
}
echo json_encode($array);}
At the moment, the query part works perfectly and the results are returned (the console also displays the value from 'Field1'. Just need to get that value into the php file at the same time!
Any help would be great
If I understood this correctly, you want to parse both the values of field 1 and 2 to the same AJAX call. This is how you do it.
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query + '&field1=' + textVal,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
Now you just make another $_POST['field1'] in your PHP file.
var userQuery = $('#ID of query input element').val();
var field1 = $('#ID of input 1 element').val();
$.ajax({
type: "POST",
url: '',
data: {query: QueryVariable, input1: input1variable},
success: function(data) {
// code within this block
},
error: function() {
alert('System Error! Please try again.');
},
complete: function() {
console.log('completed')
}
}); // ***END $.ajax call

Categories