I had an ajax implementation below and it working fine. Now, how can I get distance and id in toDistance.php? I had my code pasted below and does not add the data into my database. What is wrong?
function getABC(){
for(s=0;s<length;s++){
volunteerlocation = new GLatLng(jlat[s], jlng[s]);
volunteerDist[s] = (Math.round((eventlocation.distanceFrom(volunteerlocation) / 1000)*10)/10);
document.write(volunteerDist[s] + '<br> ');
document.write(jid[s] + '<br> ');
}
alert(Object.prototype.toString.call(volunteerDist));
$.ajax({
type:'POST',
url: 'toDistance.php',
data : ({
distance:volunteerDist,
id:jid
}),
success: function(data){
alert(data);
alert('worked');
},
error :function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
complete : function(){
alert('thanks');
}
});
}
Below is my toDistance.php
<?php
$distance=array();
$volunteerid=array();
if(empty($_GET)){
}
else{
$distance = isset($_GET['distance']) ? $_GET['distance'] : 0;
$volunteerid = isset($_GET['id']) ? $_GET['id'] : 0;
$connect = mysql_connect("localhost","root","");
mysql_select_db("mapping");
for($i=0;$i<$distance.length;$i++){
$updateDistance = mysql_query("
UPDATE volunteerbio
SET volunteerDistance = $distance[$i]
WHERE volunteerID = $volunteerid[$i];
");
}
}
?>
you are sending the data in a POST request, and trying to fetch it in the PHP from $_GET instead of $_POST
another thing:
$distance.length is not php
you need to use
count($distance)
for example:
for ($i=0, $n=count($distance); $i<$n; $i++) { ... }
// instead of running the count() function on every iteration
Related
I'm not sure how to pass the result of mysql query into html page via ajax JSON.
ajax2.php
$statement = $pdo - > prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement - > execute(array(':key2' => $key2, ':postcode2' => $postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while ($row = $statement - > fetch()) {
echo $row['Name']; //How to show this in the html page?
echo $row['PostUUID']; //How to show this in the html page?
$row2[] = $row;
}
echo json_encode($row2);
How to pass the above query result to display in the html page via ajax below?
my ajax
$("form").on("submit", function () {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function (data) {
//how to retrieve the php mysql result here?
console.log(data); // this shows nothing in console,I wonder why?
}
});
return false;
});
Your json encoding should be like that :
$json = array();
while( $row = $statement->fetch()) {
array_push($json, array($row['Name'], $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);
And in your javascript part, you don't have to do anything to get back your data, it is stored in data var from success function.
You can just display it and do whatever you want on your webpage with it
header('Content-Type: application/json');
$row2 = array();
$result = array();
$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement->execute(array(':key2' => $key2,':postcode2'=>$postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while( $row = $statement->fetch())
{
echo $row['Name'];//How to show this in the html page?
echo $row['PostUUID'];//How to show this in the html page?
$row2[]=$row;
}
if(!empty($row2)){
$result['type'] = "success";
$result['data'] = $row2;
}else{
$result['type'] = "error";
$result['data'] = "No result found";
}
echo json_encode($row2);
and in your script:
$("form").on("submit",function() {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
if(data.type == "success"){
for(var i=0;i<data.data.length;i++){
//// and here you can get your values //
var db_data = data.data[i];
console.log("name -- >" +db_data.Name );
console.log("name -- >" +db_data.PostUUID);
}
}
if(data.type == "error"){
alert(data.data);
}
}
});
return false;
});
In ajax success function you can use JSON.parse (data) to display JSON data.
Here is an example :
Parse JSON in JavaScript?
you can save json encoded string into array and then pass it's value to javascript.
Refer below code.
<?php
// your PHP code
$jsonData = json_encode($row2); ?>
Your JavaScript code
var data = '<?php echo $jsonData; ?>';
Now data variable has all JSON data, now you can move ahead with your code, just remove below line
data = $(this).serialize() + "&" + $.param(data);
it's not needed as data variable is string.
And in your ajax2.php file you can get this through
json_decode($_REQUEST['data'])
I would just..
$rows = $statement->fetchAll(FETCH_ASSOC);
header("content-type: application/json");
echo json_encode($rows);
then at javascript side:
xhr.addEventListener("readystatechange",function(ev){
//...
var data=JSON.parse(xhr.responseText);
var span=null;
var i=0;
for(;i<data.length;++i){span=document.createElement("span");span.textContent=data[i]["name"];div.appendChild(span);/*...*/}
}
(Don't rely on web browsers parsing it for you in .response because of the application/json header, it differs between browsers... do it manually with responseText);
I'm new Jquery and AJAX and I've really been struggling with the syntax I've been trying to use other tutorials as reference but nothing seems to work. I feel I have the right idea but syntax is wrong somewhere please help.
Here is the Ajax side
var var_numdatacheck = <?php echo $datacheck; ?>;
var var_numcheck = parseInt(var_numdatacheck);
function activitycheck(){
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var json = eval('(' + data + ')');
$('#datacheck').html(json['0']);
var var_numcheck = parseInt(msg);
//setTimeout('activitycheck()',1000)},
error:function(msg) {
console.log(msg);
}
});
}
$(document).ready(function() {
activitycheck();
});
Here is the php the AJAX calls
<?php
require "dbc.php";
$function = $_POST['function'];
$datacheck = $_POST['datacheck'];
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$update= mysql_fetch_array($request);
$updateid = $update['id'];
$updatecheck = mysql_num_rows($request);
$data = array();
if ($function == $datacheck){
echo $updatecheck;
echo $datacheck;
}
if ($function == "3test" && $updatecheck > $datacheck ) {
$updatesearch="SELECT * FROM Feedtest WHERE id = '$updateid' ORDER BY id DESC";
$updatequery = mysql_query($updatesearch);
$data['id'] = $updateid;
while ($row = mysql_fetch_array($updatequery))
{
?>
<?php $data[]= $row['First Name']; ?>
<?php
}
echo json_encode($data);
}
?>
</div>
</ul>
first of all ,always use JSON.parse(data) instead of eval.It is considereda a good practice.
second thing is always try to debug your code by checking it in console or alerting.In your context,this is what is happening-:
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var data = eval('(' + data + ')');
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i=0;i< data.length;i++)
{
alldata += "<li>"+data[i][0]+"<li><hr>";
}
$('#datacheck').html(alldata);
});
}
For JSON.parse:
success: function(data) {
var data = JSON.parse(data);
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i in data)
{
alldata += "<li>"+data[i].First Name+"<li><hr>";
}
$('#datacheck').html(alldata);
});
I'm trying to write a script in javascript/jquery that will send values to a php file that will then update the database. The problem is that the values aren't being read in by the PHP file, and I have no idea why. I hard-coded in values and that worked fine. Any ideas?
Here's the javascript:
var hours = document.getElementById("hours");
var i = 1;
while(i < numberofMembers) {
var memberID = document.getElementById("member"+i);
if(memberID && memberID.checked) {
var memberID = document.getElementById("member"+i).value;
$.ajax({
type : 'post',
datatype: 'json',
url : 'subtract.php',
data : {hours : hours.value, memberID : memberID.value},
success: function(response) {
if(response == 'success') {
alert('Hours subtracted!');
} else {
alert('Error!');
}
}
});
}
i++;
}
}
subtract.php:
if(!empty($_POST['hours']) AND !empty($_POST['memberID'])) {
$hoursToSubtract = (int)$_POST['hours'];
$studentIDString = (int)$_POST['memberID'];
}
$query = mysql_query("SELECT * FROM `user_trials` WHERE `studentid` = '$studentIDString' LIMIT 1");
Edit: Updated code following #Daedal's code. I'm still not able to get the data in the PHP, tried running FirePHP but all I got was "profile still running" and then nothing.
This might help you:
function subtractHours(numberofMembers) {
var hours = document.getElementById('hours');
var i = 1;
while(i < numberofMembers) {
// Put the element in var
var memberID = document.getElementById(i);
// Check if exists and if it's checked
if(memberID && memberID.checked) {
// Use hours.value and memberID.value in your $.POST data
// {hours : hours.value, memberID : memberID.value}
console.log(hours.value + ' - ' + memberID.value);
// $ajax is kinda longer version of $.post api.jquery.com/jQuery.ajax/
$.ajax({
type : 'post',
dataType : 'json', // http://en.wikipedia.org/wiki/JSON
url : 'subtract.php',
data : { hours : hours.value, memberID : memberID.value},
success: function(response) {
if( response.type == 'success' ) {
alert('Bravo! ' + response.result);
} else {
alert('Error!');
};
}
});
}
i++;
}
}
and PHP part:
$result = array();
// Assuming we are dealing with numbers
if ( ! empty( $_POST['hours'] ) AND ! empty( $_POST['memberID'] ) ) {
$result['type'] = "success";
$result['result'] = (int) $_POST['hours'] . ' and ' . (int) $_POST['memberID'];
} else {
$result['type'] = "error";
}
// http://php.net/manual/en/function.json-encode.php
$result = json_encode( $result );
echo $result;
die();
Also you probably don't want to CSS #ID start with a number or to consist only from numbers. CSS Tricks explained it well http://css-tricks.com/ids-cannot-start-with-a-number/
You can simple fix that by putting some string in front:
var memberID = document.getElementById('some_string_' + i);
This is not ideal solution but it might help you to solve this error.
Cheers!
UPDATE:
First thing that came to my mind is that #ID with a number but as it seems JS don't care about that (at least not in a way CSS does) but it is a good practice not to use all numbers. So whole error was because document.getElementById() only accepts string.
Reference: https://developer.mozilla.org/en-US/docs/DOM/document.getElementById id is a case-sensitive string representing the unique ID of the element being sought.
Few of the members already mentioned converting var i to string and that was the key to your solution. So var memberID = document.getElementById(i); converts reference to a string. Similar thing could
be accomplished I think in your original code if you defined wright bellow the loop while(i < numberofMembers) { var i to string i = i.toString(); but I think our present solution is better.
Try removing the '' fx:
$.post (
"subtract.php",
{hours : hours, memberID : memberID}
try this
$.ajax({type: "POST",
url:"subtract.php",
data: '&hours='+hours+'&memberID='+memberID,
success: function(data){
}
});
Also you could try something like this to check
$(":checkbox").change(function(){
var thisId = $(this).attr('id');
console.log('Id - '+thisId);
});
$studentID = $_GET['memberID'];
$hoursToSubtract = $_GET['hours'];
Try this:
$.post("subtract.php", { hours: hours, memberID : memberID })
.done(function(data) {
document.body.style.cursor = "auto";
});
Try n use this...
$.post("subtract.php", { hours: hours, memberID : memberID })
.done(function(data) {
$(body).css({ 'cursor' : 'auto' });
});
this is my code:
class_search.php
case 'users':
if(!empty($_REQUEST['user'])){
if(strlen($_REQUEST['user']) >= 3){
$_REQUEST['user'] = $this->sanitize($_REQUEST['user'], 'string');
$stmt = $this->sql->prepare('SELECT
id,
nome,
url
FROM
animes
WHERE
nome LIKE ?
LIMIT 10');
$stmt->execute(array('%'.$_REQUEST['user'].'%'));
$this->queries++;
$c = 0;
if($admin){
$result['users'] = array();
}
if($stmt->rowCount() > 0){
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
if($admin){
$result['users'][$c] = array('name'=>($prefix ? '[usr] ' : '').$row['nome'], 'id'=>$row['id']);
$c++;
}else{
$result[] = ($prefix ? '[usr] ' : '').$row['nome'];
}
}
}
}
}
break;
general.js
$('#top_search').typeahead({
source: function(typeahead, query) {
$.ajax({
url: baseurl + "/ajax_calls.php",
dataType: "json",
type: "POST",
data: {
call: 'top_search',
user: query
},
success: function(data) {
typeahead.process(data);
}
});
},
onselect: function(obj) {
location.href= baseurl + '/animes/'+obj;
}
})
ajax_calls.php
case 'top_search':
$status = $site->process_autosearch('users');
break
;
I am having problem with onselect, I need to select the row url in my MySQL and encode to json, because when I click in one result I am redirect to mysite.com/animes/name of anime/ (yes, with space) and I need to fix this.
Table animes in phpMyAdmin:
http://s18.postimage.org/3ulrcmss9/Animes_Table.jpg
Quickly video: http://www.screenr.com/plZ7
You would need to use urlencode().
In your class_search.php file, update this part:
if($admin){
$result['users'][$c] = array('name'=>($prefix ? '[usr] ' : '').urlencode($row['nome']), 'id'=>$row['id']);
$c++;
}else{
$result[] = ($prefix ? '[usr] ' : '').urlencode($row['nome']);
}
And to make the names looks good in the searche auto-complete as well, you need to modify your jQuery as well, wrapping the decodeURIComponent() function around the obj like so:
onselect: function(obj) {
location.href= baseurl + '/animes/' + decodeURIComponent(obj);
}
I am developing ajax Based Search , This is demo of how it will be. I am faceing Problem in returning result. I need to show the Result 2 times. But its only showing once. Below is my HTML code
<form action="" method="post" id="demoform">
<select style="width:250px;padding:5px 0px;color:#f1eedb;" name="product" class="product">
<option>TENNIS</option>
<option>FOOTBALL</option>
<option>SWIMMING</option>
</select>
</form>
<div id="result">Display Result Here</div>
I Using The Below Ajax Script to Retrieve Data :-
$(".product").change(function(){
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
product : $(".product option:selected").text(),
},
success : function(data){
$('#result').removeClass().addClass((data.error === true) ? 'error' : 'success')
.html(data.msg).show();
if (data.error === true)
$('#demoForm').show();
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#result').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show();
}
});
});
The post.php file has the following code :-
<?php
require('connect.php');
$get_select = $_POST[product];
if($get_product!='FOOTBALL'){
$return['error'] = true;
return['msg'] = 'Incorrect Selection';
echo json_encode(return);
}
else {
$return['error'] = false;
$i=0;
while($i<2) {
return['msg'] = $get_product;
}
echo json_encode(return);//Returns only one result.
}
?>
I need to show the result Two times as "CRICKET CRICKET", but its only showing once.
What should i do to get both the result.
Is it possible that this line is confusing php:
while($i<2) {
return['msg'] = $get_product;
}
Should it be $return? Using a reserved word like 'return' is a tad iffy too.
Please change the following code:
else {
$i=0;
$messageToReturn = "";
while($i<2) {
$messageToReturn .= $get_product; //Append to your variable
}
return json_encode($messageToReturn); //Returns the result
}
I would suggest to change the while to a for loop.
In that case you will get this:
else {
$messageToReturn = "";
for($i = 0; $i < 2; $i++)
{
$messageToReturn .= $get_product; //Append to your variable
}
return json_encode($messageToReturn);
If you know the times you need to repeat, use a for loop. The while is never ending. So you can get a possible stack overflow...