I am trying to update my div content (#update_div) by sending the value of two input fields to a php file (search_value.php) using the .ajax() function from jQuery.
It works, if I just redirect the two values of the input fields using the html form POST method. So the search_value.php should be correct.
My HTML Code:
<form id="my_form">
<input id="food" name="food">
<input id="amount" value="amount in gram" name="amount">
<input type="button" value="Update" id="submit" name="submit" />
</form>
<div id="update_div">
</div>
My Javascript Code:
$("#submit").click(function() {
var food = $("#food").val();
var amount = $("#amount").val();
$.ajax({
url: 'search_value.php',
type: 'GET',
data: {"food":food,"amount":amount},
success: function(data)
{
$('#update_div').html(data);
}
});
});
My PHP Code:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=calotools', 'root', '');
$food = $GET_['food'];
$amount = $GET_['amount'];
$query="SELECT * FROM nahrungsmittel WHERE name = '$food'";
$user = $pdo->query($query)->fetch();
echo $user['name']."<br />";
echo $user['kcal'] / 100 * $amount;
?>
I do not really get a feedback by clicking the button. Maybe you guys can tell me why?
For GET request, there should not be data part, make it as a query string as below js code:
$("#submit").click(function() {
var food = $("#food").val();
var amount = $("#amount").val();
$.ajax({
url: 'search_value.php?food='+ food + '&amount='+amount,
type: 'GET',
datatype: "html",
success: function(data)
{
$('#update_div').html(data);
},
failure : function(ex)
{
console.log(ex);
}
});
});
And use $_GET instead of $GET_ in php
Are you running your code after the page has loaded? I've made that mistake several times, and if you're not, I suggest wrapping the whole thing in a $(function(){ /* Everything you have */ });
I prefer using post
in your php script replace $GET_ by $_POST
<?php
$pdo = new PDO('mysql:host=localhost;dbname=calotools', 'root', '');
$food = $_POST['food'];
$amount = $_POST['amount'];
$query="SELECT * FROM nahrungsmittel WHERE name = '$food'";
$user = $pdo->query($query)->fetch();
echo $user['name']."<br />";
echo $user['kcal'] / 100 * $amount;
?>
in your javascript code the result is found in data.responseText
here the new script
$("#submit").click(function() {
var food = $("#food").val();
var amount = $("#amount").val();
$.ajax({
url: 'search_value.php',
type: 'POST',
data: {"food":food,"amount":amount},
success: function(data)
{
$('#update_div').html(data.responseText);
}
});
});
Tested and your JavaScript code works. The issue may be in the PHP code.
Have you tried correcting the "$_GET" as suggested by others?
Related
I have been at this for few hours now and need some help. I am a little new to jquery - it seems straightforward enough, but I can't get this to work. If I submit the data through a form straight to the php page, it works perfectly, but I can't get the ajax to execute. It is pretty simple with just one variable to send for marking an item for review. Any help is appreciated.
<input type="hidden" id="flag_item" name="flag_item" value="<?php echo $row[0]; ?>" />
<input type="button" class="grn_button2" id="report_btn" name="report_btn" onclick="MM_changeProp('flag1','','display','none','SPAN'), MM_changeProp('flag2','','display','inline','SPAN')" value=" Report Item "/>
the jquery code
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('click','#report_btn',function(e) {
var data = $("#flag_item").val();
$.ajax({
data: data,
type: "POST",
url: "flag.php",
success: function(data) {
alert("Item has been reported");
}
});
});
});
</script>
and the php
$flag_item = mysqli_real_escape_string($dbgo, $_POST["flag_item"]);
$query = "SELECT flag FROM listings WHERE item_num = '$flag_item'";
$result = mysqli_query($dbconnect, $query);
if(!$result){
die('Invalid query: ' . mysql_error());
}
$row = mysqli_fetch_row($result);
$new_row = $row[0] + 1;
You missed param name here:
var data = $("#flag_item").val();
Try this:
var data = {"flag_item":$("#flag_item").val()};
I got it working now. I ditched the jquery I was using and started over. This jquery code is working.
$('#flag_form').submit(function(){
return false;
});
$('#flag_form').click(function(){
$.post(
$('#flag_form').attr('action'),
$('#flag_form :input').serializeArray(),
function(result){
alert("Item has been reported");
}
);
});
I also added the form tag and the action to input fields. Thank you for trying to help, I appreciate it.
I'm currently into developing simple 'one score' votting system and I'm facing the problem: though php script workd fine I cant get AJAX updating the answer div without reloading page. I've tried different methods, some do nothing, other reload page, for example, I've tried adding (return: false) after AJAX or PreventDefault in it. Here is html and php index page:
<body>
<div align="center">
<h3>Voting with jQuery, Ajax and PHP</h3>
<?php
include('config.php');
$sql=mysqli_query($bd, "SELECT * FROM messages LIMIT 9");
while($row=mysqli_fetch_array($sql))
{
$msg=$row['msg'];
$mes_id=$row['mes_id'];
$total_score=$row['total_score'];
?>
<div id="main">
<div class="box1">
<img class='image'src="img/thumbsup.png">
<span class='this'><?php echo $total_score; ?></span><div class='tr'></div>
<img class='image' src="img/icon-down.png"></div>
<div class='box2' ><?php echo $msg; ?></div>
</div>
<?php
}
?>
</div>
</body>
And here is my working up_vote.php (down_vote.php is almost same, so I wont add it)
<?php
include("config.php");
$ip=$_SERVER['REMOTE_ADDR'];
if($_POST['id'])
{
$id=$_POST['id'];
$ip_sql=mysqli_query($bd,"select ip_add from Voting_IP where mes_id_fk='$id' and ip_add='$ip'");
$count=mysqli_num_rows($ip_sql);
$sql = "update Messages set total_score=total_score+1 where mes_id='$id'";
mysqli_query($bd, $sql);
$sql_in = "insert into Messages (mes_id_fk,ip_add) values ('$id','$ip')";
mysqli_query($bd, $sql_in);
$count=mysqli_num_rows($ip_sql);
}
?>
And finally, the complete JQUERY - AJAX script (this's my problem - need to show the results in (div class = 'this') without refreshing the page):
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='up')
{
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success:function(data){
$(".this").append(data);
},
complete: function() {alert('complete');};
});} else
{
$(this).fadeIn(200).html('<img src="img/icon-down.png" align="absmiddle" style="height: 10px;width:10px;">');
$.ajax({
type: "POST",
url: "down_vote.php",
data: dataString,
cache: false
}).done(function ( data ) {
$('.this').append(data);
});
}
return false;
});
});
I have spent whole my day and I know the solution is obvious, Im just really new in this all and so I would appreciate any helpful response. Thanks in advance.
I have added this code to up_vote.php at the buttom:
$result=mysqli_query($bd, "select total_score from Messages where mes_id='$id'");
$row=mysqli_fetch_array($result);
$up_value=$row['total_score'];
echo $up_value;
Thanks to all of you guyz!!! It works now! The problem was that php script didnt return anything!!! As I though - obviouse))) THANKS!
HAve NEW PROBLEM NOW - WHEN I CLICK ON ICONS IT UPDATES ALL OF THEM!! IN EVERY DIV! I VOTE FOR ONE THING - AND IT ADDS VOTES FOR EACH ONE!! whats wrong with that?
Hi I am trying to run a delete script that will delete the record from my database using ajax and php. Used without the ajax javascript file the delete_file.php script works fine and is removed from the database.(So I am asssuming the problem lies in the javascript file somewhere.) Once I add the javascript file only it appears to run and delete_file.php does notk. Basically I pass three id's through to delete_file.php find them all in their respective tables then use those variables to find the right file to delete. Any Help is greatly appreciated. I need a fresh pair of eyes, thanks
What I am Clicking
[![enter image description here][1]][1]
html
<?php echo'<li class="col student_file">
<i class="fa fa-times-circle-o"></i>
<a class="the-file student_'.$student_id.'" id="file_'.$file_id.'" href="/application/student/file_management'.$file_path.'" target="_blank"><i class="fa fa-file-archive-o"></i></i></i>'.$file_name.' <span>'.$file_size.'</span></a>
</li>
delete_file_ajax.js
$(document).ready(function() {
"use strict";
$(".delete-file").click(function() {
var container = $(this).parent();
var id = $('.the-file').attr("id");
var string = 'id='+ id ;
if(confirm("Are you sure you want to delete this?")) {
$.ajax({
type: "POST",
url: "delete_file/delete_file.php",
data: string,
cache: false,
success: function(){
container.slideUp('slow', function() {$(this).remove();});
}
});
}
return false;
});
});
delete_file.php
<?php
session_start();
//Connect to Database
require_once('../../../../db_config.php');
$db_connect = connectDB($mysqli) or die(mysqli_error());
//First lets make sure the user is allowed
require_once('../../../../auth/admin_session.php');
//Create our session on session_id
$session_id = $_SESSION['ADMIN_ID'];
//Get the IDs
$s_id = $_GET['student'];
$a_id = $_GET['agent'];
$f_id = $_GET['file'];
//Lets find the Id of the Agency User
$session_query = mysqli_query($db_connect, "SELECT * FROM agency WHERE agency_id = $a_id");
$session_row = mysqli_fetch_assoc($session_query);
$session_num_rows = mysqli_num_rows($session_query);
$agency_id = $session_row['agency_id'];
//Lets find the Id of the Agency User
$student_session_query = mysqli_query($db_connect, "SELECT * FROM students WHERE student_id = $s_id");
$student_session_row = mysqli_fetch_assoc($student_session_query);
$student_session_num_rows = mysqli_num_rows($student_session_query);
$student_id = $student_session_row['student_id'];
//Lets find the Id of the File we want to delete
$file_session_query = mysqli_query($db_connect, "SELECT * FROM uploaded_files WHERE file_id = $f_id AND agency_id = $a_id AND student_id = $s_id");
$file_session_row = mysqli_fetch_assoc($file_session_query);
$file_session_num_rows = mysqli_num_rows($file_session_query);
$file_id = $file_session_row['file_id'];
if(!mysqli_connect_errno()){
$stmt = $db_connect->prepare("DELETE FROM uploaded_files WHERE file_id = ? AND agency_id = ? AND student_id = ?") or die('We Could not locate the file you wish to delete');
$stmt->bind_param('iii', $file_id, $agency_id, $student_id);
$stmt->execute();
$stmt->close();
}
?>
Solution
html
echo '<form class="delete-student-file" action="delete_file/delete_file.php" method="post">';
echo '<li class="col student_file">';
echo '<input type="hidden" name="student-id" value="'.$student_id.'">';
echo '<input type="hidden" name="agency-id" value="'.$agency_id.'">';
echo '<input type="hidden" name="file-id" value="'.$file_id.'">';
echo'<a class="the-file student_'.$student_id.'" id="file_'.$file_id.'" href="/application/student/file_management'.$file_path.'" target="_blank"><i class="fa fa-file-pdf-o"></i>'.$file_name.' <span>'.$file_size.'</span></a>';
echo '<button class="delete-file" name="submit"><i class="fa fa-times-circle-o"></i></button>';
echo'</li>';
echo'</form>';
delete_file.php
//Get the IDs
$s_id = $_POST['student-id'];
$a_id = $_POST['agency-id'];
$f_id = $_POST['file-id'];
delete_file_ajax.js
$(document).ready(function() {
"use strict";
$(".delete-file").click(function(e) {
e.preventDefault();
var container = $(this).parent();
var formData = $('.delete-student-file').serialize();
if(confirm("Are you sure you want to delete this?")) {
$.ajax({
type: "POST",
url: "delete_file/delete_file.php",
data: formData,
cache: false,
beforeSend: function(){
container.animate({'backgroundColor': '#fb6c6c'}, 300);
},
success: function(){
container.slideUp('slow', function() {$(this).remove();});
}
});
}
});
});
It looks like your problem is sending the ajax call as POST and requesting it as GET. Try this:
$.ajax({
type: "GET",
url: "delete_file/delete_file.php",
data: string,
cache: false,
success: function(){
container.slideUp('slow', function() {$(this).remove();});
}
Personally, I would suggest changing your PHP to accept POST rather than GET, but that is just my opinion.
PHP know inside "" is string not variable,but enclose by '' can print variable
I advice you to use '' in sql query.
$session_query = mysqli_query($db_connect, "SELECT * FROM agency WHERE agency_id = '$a_id'");
OR
$session_query = mysqli_query($db_connect, "SELECT * FROM agency WHERE agency_id = '".$a_id."'");
So i have 2 files index.php and changeLikeDislike.php. I think the issue is where javascript is trying to get the type and id but I do not know how I would go about that. My javascript function is being called in the foreach->li->divs. It was working before like this: data: dataString, but I added schoolId into data of ajax as well so it's like this now data: {dataString:dataString, schoolId:schoolId},
index.php
<?php
$last_id = 0;
foreach ($list as $rs) {
$last_id = $rs['id']; // keep the last id for the paging
?>
<li>
<div style="width:100%; color:#000;">
<?php echo '<div class="product_like thumb-div"><img src="like.png" class="rating-image " onclick=changeLikeDislike("like","'.$rs['id'].'")> <br><span id="product_like_'.$rs['id'].'">'.$rs['pLike'].'</span></div>';?>
<?php echo '<div class="product_dislike"><img src="dislike.png" class="rating-image" onclick=changeLikeDislike("dislike","'.$rs['id'].'")><br> <span id="product_dislike_'.$rs['id'].'">'.$rs['pDislike'].'</span></div>';?>
</div>
</li>
<?php
}
?>
<script type="text/javascript">
//begin like and dislike
function changeLikeDislike(type,id){
var dataString = 'id='+ id + '&type=' + type;
$.ajax({
type: "POST",
url: "changeLikeDislike.php",
data: {dataString:dataString, schoolId:schoolId},
cache: false,
success: function(result){
if(result){
console.log('working');
}
}
});//end ajax
}
schoolId works in data but not dataString in ajax How would i go about grabbing those. My php file for reference:
//checks if school page id was brought and stores into variable
if (isset($_POST['schoolId'])) {
$schoolIdFinal = $_POST['schoolId'];
}else {
echo "nope";
}
if (isset($_POST['type'])) {
$type = $_POST['type'];
}else {
echo "nope type";
}
if (isset($_POST['id'])) {
$id = $_POST['id'];
}else {
echo "nope id";
}
my page is echoing out "nope type nope id"
Please change
data: {dataString:dataString, schoolId:schoolId},
to
data: {type:type, id:id, schoolId:schoolId},
to match the params to your PHP script.
data can either be a query string (like your dataString) OR a json struct (like {type:type, id:id, schoolId:schoolId}).
See the documentation of jQuery.ajax():
"The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}."
see http://api.jquery.com/jquery.ajax/
The issue is in the data bracket. change
data: {dataString:dataString, schoolId:schoolId}
to
data: {dataString:'dataString', schoolId:'schoolId'}
next time do a print_r of $_REQUEST or $_POST to see what fields are being recognized and in this case it looks like its not detecting anything.
I'm trying send select query and set the result as value attribute for different input fields, the query should be sent upon selecting a value from dropdown list. After doing some researches I found this can be reached through jQuery.
jQuery will send request to php file which contains my query and fetch result and then return values in json format. At this point everything is working great, my php file is working and return valid json data but I cannot get these data append in the input fields I have. Here is my script that should run the php file and return the results in json then append results in text fields.
Check my code on fiddle
<script>
var flight_destination = $('#destination).text();
var flight_departure = $('#departure).text();
var flight_arrival = $('#arrival).text();
$('#flight_number').on('change', function() {
var flight_info = $('#flight_number :selected').text();
$.ajax({
url: "getFlightData.php",
type: "get",
data: '?flight_number=$flight_number',
success: function(data){
var flight_destination = data[1];
var flight_departure = data[2];
var flight_arrival = data[3];
}
}
$('#destination').val(flight_destination);
$('#departure').val(flight_departure);
$('#arrival').val(flight_arrival);
})
</script>
getFlightData.php
<?php
include "dbConnect.php";
$flight_number = $_GET['flight_number'];
$query = mysql_query("SELECT * FROM flights WHERE flight_number='$flight_number'");
$data = array();
while($row = mysql_fetch_array($query))
{
$row_data = array(
'flight_number' => $row['flight_number'],
'destination' => $row['destination'],
'departure' => $row['departure'],
'arrival' => $row['arrival']
);
array_push($data, $row_data);
}
echo json_encode($data);
?>
GOOD NEWS
A friends of mine helped me out with a syntax error in data: line. I did change it from data:'flight_number='+$('#flight_number').val(), to data:{'flight_number':$('#flight_number').val()},
In browser console window the json objects returned perfectly on change the drop down list value but still cannot append these objects to the input fields as value attribute
Update 2
Now I have this Still the data returned in the browser's console window perfectly, but the only what appended in the first text field is [object]
of the browser after selecting option from drop down list
Update 3
With great help and effort from #satyrwilder I'm now able to retrieve the first text field value. This is working version of the script snippet
$(function(){
var flight_destination = $('#destination');
var flight_departure = $('#departure');
var flight_arrival = $('#arrival');
var flight_number = $('#flight_number');
$('#flight_number').on('change', function() {
var flight_info = $('#flight_number :selected').text();
$.ajax({
url: "getFlightData.php",
type: "get",
dataType: "json",
data: { 'flight_number' : flight_number.val() }
})
.done(function(data) {
$("#destination").val(data[0].destination);
$("#departure").text(data[0].departure).val(data[0].departure);
$("#arrival").text(data[0].arrival).val(data[0].arrival);
});
});
});
I'm now looking forward to append the datetime-local values as well. I will keep this question updated regularly until it's 100% compelted
you must declare what type of data going to receive your inquiry.
dataType: "json"
$.ajax({
url: "getFlightData.php",
type: "get",
data: '?flight_number=$flight_number',
success: function(data){ ... },
dataType: "json", //<--------- this
});
Documentation of $.ajax()
And header from json in the start of you code php
For JSON:
header('Content-Type: application/json');
For JSON-P:
header('Content-Type: application/javascript');
Finally I came to the final working code where everything is working perfectly. First I'd like to thank #satyrwilder for correcting my javascript part.
Here is the final code, which appends values from database into text and datatime-local fields using jquery + php
getFlightDate.php
<?php
header('Content-Type: application/json');
include "dbConnect.php";
function datetime()
{
return date( 'Y-m-d\TH:i:s', time());
}
$flight_number = $_GET['flight_number'];
$query = mysql_query("SELECT * FROM flights WHERE flight_number='$flight_number'");
$data = array();
while($row = mysql_fetch_array($query))
{
$row_data = array(
'flight_number' => $row['flight_number'],
'destination' => $row['destination'],
'departure' => datetime($row['departure']),
'arrival' => datetime($row['arrival'])
);
array_push($data, $row_data);
}
echo json_encode($data);
?>
print.php
<?php
include "dbConnect.php";
$flight_numbers = mysql_query("SELECT flight_number FROM flights");
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title>Test</title>
</head>
<body>
<select id="flight_number">
<?php while($row = mysql_fetch_array($flight_numbers))
{
Print "<option>".$row['flight_number'] . "</option> ";
}
?>
</select>
<br>
<input type="text" id="destination">
<input type="datetime-local" id="departure" />
<input type="datetime-local" id="arrival" />
<script>
$(function(){
var flight_destination = $('#destination');
var flight_departure = $('#departure');
var flight_arrival = $('#arrival');
var flight_number = $('#flight_number');
$('#flight_number').on('change', function() {
var flight_info = $('#flight_number :selected').text();
$.ajax({
url: "getFlightData.php",
type: "get",
dataType: "json",
data: { 'flight_number' : flight_number.val() }
})
.done(function(data) {
$("#destination").val(data[0].destination);
$("#departure").text(data[0].departure).val(data[0].departure);
$("#arrival").text(data[0].arrival).val(data[0].arrival);
});
});
});
</script>
</body>
</html>
The trick was to change the datetime format before json_encode, because datetime-local input fields shows values in specific format which is 2014-12-05T08:30:59 -> Y-m-d\TH:i:s