I had a function below which stores distances from two locations using google maps api. those results are stored in volunteerDist and there is a defined jid array. Document.write in line 5 showed the contents of each element in the array. Now, when I alert the Object.prototype... of volunteerDist, is says object Array. But when I called $.ajax and transferred volunteerDist into data and alert it (as shown below), it returns undefined and success (meaning data is stored but the contents are undefined). Any help? Thanks
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');
}
});
}
Update:
Below is my toDistance.php
<?php
$distance=array();
$volunteerid=array();
if(empty($_GET)){
echo "Hello";
}
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];
");
}
}
?>
It's now the same data variable! It's in other scope.
The data in the success function is what the server returned. Give it other name if it confuses you.
$.ajax({
type:'POST',
url: 'toDistance.php',
data : ({
distance:volunteerDist,
id:jid
}),
success: function(result){ // Data sent from the server. not the data above!
alert(result);
alert('worked');
},
error :function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
complete : function(){
alert('thanks');
}
});
Related
I am attempting use a variable that I create through data being sent from php in one ajax function in a another ajax function. I'm not sure what I am doing wrong. I tried creating making this a global variable by doing var nameOutput and also tried var nameOutput = 0. You will see alert code in the second ajax function. This is outputting nothing. If I remove the .val(), I receive object Object.
The code in question is in the second Ajax function: data: {
'nameOutput': nameOutput.val()
}
Does anyone have any idea what I have to do?
var nameOutput;
$('#shuffle').on('click', function() {
$.ajax({
url: 'php/name-selection.php',
type: 'POST',
success: function(data) {
nameOutput = $('#name-output').html(data);
$(nameOutput).html();
},
complete:function(){
$('#send-info').slideDown(1500);
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
}
});
});
//var datastring1 = $('#name-output').serialize();
$('.check').click(function() {
alert(nameOutput.val());
$.ajax({
url: 'php/name-selection-send.php',
type: 'POST',
data: {
'nameOutput': nameOutput.val()
}
,
success: function(data) {
if (data == 'Error!') {
alert('Unable to submit inquiry!');
alert(data);
} else {
$('#success-sent').html(data);
}
},
complete:function(){
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
}
});
if you can set inner html of nameOutput using .html('blah') , so you can extract the html again using nameOutput.html() not nameOutput.val();
however I think you have to define the element like this to be a HTML element:
var nameOutput=$('<div></div>');
also in first ajax function,set the html using this:
nameOutput.html(data);
and if there is a real element with ID name-output , and you want the result to be visible, do both of these:
nameOutput.html(data);
$('#name-output').html(data);
I am having a very tough time transfering a php variable to javascript through json.
I have debugged it throughly and Ive come to the conclusion that something must be wrong with the javascript code. I am saying this because I output the json encoding in my php and see that I get {"result":"4","success":true}, where 4 is the variable value.
But when I try to get the variable in javascript like this:
$('#add').on('submit',function(){
var that = $(this), contents = that.serialize;
console.log("after serialize");
$.ajax({
url: 'caradded.php',
contentType: 'json',
data : contents,
type: 'post',
success : function(data){
/*
try {
var result = JSON.parse(data);
alert(result);
} catch (e) {
alert("Output is not valid JSON: " + data);
}*/
console.log("result0!! " + data.result);
console.log("result1!! " + data);
try{
localStorage.setItem("storageName",data);
} catch (e) {
alert("couldnt set item: " + data);
}
}
});
/*
error: function (request, error) {
alert(" Can't do because: " + error);
},
*/
//dataType: 'json',
//data: contents,
//So we do not submit data:
//return false;
// console.log(arguments);
});
then I get the following output on submit (a form submission):
result0!! null
result1!! [Object object]
The following is my php json encoding:
header("Content-type:application/json");
echo json_encode(array(
'result' => $GLOBALS['price'],
'success' => true
));
exit();
If I change $GLOBALS['price'] with a string like "test" then it works just fine. Again note that $GLOBALS['price'] outputs a value in my console.
Anyone who has any idea what Im doing wrong?
Thank you very much!
Best regards
William.
function update(){
var name= document.getElementById("TextBox").value;
$.ajax({
url: '....',
type: 'post',
data: {....//many data include// 'name' : name, ....},
success: function(data) {
var replacevalue=data.replace(/[\[\]']/g,'' );
alert(replacevalue);
var stringstatus=replacevalue.replace(/['"]+/g, '');
alert(stringstatus);
if(stringstatus == "success"){
alert ("Successfully Update ")
}
else{
alert("Failed!");
return ;
}
returnToDisplayPage();
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
});
}
function returnToDisplayPage(){
var id = document.getElementById("TextBox").text;
window.location = './DisplayPage.php?Name='+id;
}
Please suggest me. How should I do to get the updated data when click update button and refresh or reload page ? In function returnToDisplayPage() methods. I got only the name of update data and other related fields data didn't get back.
Try something like this:
$.post('url', {params}, function(response){
//Here you check if you got response from url
// And then you can do whatever you like to do with received data
if(response == 'ok'){
//do your stuff
//then
window.location.reload();
}
}
When we will get result in response then After 5 seconds page will be refresh..
success: function(data){
if(data.success == true){ // if true (1)
setTimeout(function(){// wait for 5 secs(2)
location.reload(); // then reload the page.(3)
}, 5000);
}
}
I have a problem with jQuery calling an AJAX function, basically everytime a user changes a select box, I want it to call the getSubCategories function, but for some reason, nothing is happening. Any ideas?
If I load the page and add console.log inside the getSubCategories function it logs it, should that even be happening?
function getSubCategories() {
var id = $("#category").prop('selectedIndex');
var selectedCategory = $("#category").val();
//should change this into a response from AJAX and grab the slug from there, this is fine for now.
var slugOfCategory = convertToSlug(selectedCategory);
id++;
console.log('here');
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/product/get_subcategories', // This is the url we gave in the route
data: {
'id': id
}, // a JSON object to send back
success: function(response) { // What to do if we succeed
$("#sub_category option").remove(); //Remove all the subcategory options
$.each(response, function() {
$("#sub_category").append('<option value="' + this.body + '">' + this.body + '</option>'); //add the sub categories to the options
});
$("#category_slug").attr('value', slugOfCategory);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
function getCategories() {
var id = $("#type").prop('selectedIndex');
var selectedType = $("#type").val();
//should change this into a response from AJAX and grab the slug from there, this is fine for now.
var slugOfType = convertToSlug(selectedType);
console.log(slugOfType);
//add one to the ID because indexes dont start at 0 as the id on the model
id++;
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/product/get_categories', // This is the url we gave in the route
data: {
'id': id
}, // a JSON object to send back
success: function(response) { // What to do if we succeed
$("#category option").remove(); //Remove all the subcategory options
$.each(response, function() {
$("#category").append('<option value="' + this.name + '">' + this.name + '</option>'); //add the sub categories to the options
});
$("#type_slug").attr('value', slugOfType);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
function convertToSlug(Text) {
return Text
.toLowerCase()
.replace(/ /g, '_')
.replace(/[^\w-]+/g, '');
}
$(document).ready(function() {
var firstCatgegory = $("#category").val();
var slugOfFirstCategory = convertToSlug(firstCatgegory);
$("#category_slug").attr('value', slugOfFirstCategory);
var firstType = $("#type").val();
var slugOfFirstType = convertToSlug(firstType);
$("#type_slug").attr('value', slugOfFirstType);
$("#type").change(getCategories());
$("#category").change(getSubCategories());
});
Thanks for any help. (Sorry the code is a little messy, i've just been trying to get it to work so far)
This is due to the fact that the ajax call you are trying to make is asynchronous. When you call getSubCategories() it returns undefined which is why your code is not working.
To make this work you need to put your code within the success callback function instead.
<script>
function getSubCategories()
{
var id= $("#category").prop('selectedIndex');
$.ajax({
method: 'GET',
url: '/product/get_subcategories',
data: {'id' : id},
success: function(response){
// DO SOMETHING HERE
},
error: function(jqXHR, textStatus, errorThrown) { }
});
}
$( document ).ready(function() {
// This is also wrong. Currently you're passing
// whatever is returned from getSubCategories
// (which is undefined) as the callback function
// that the "change" event will call. This instead
// should be the reference to the function. Which
// in this case is getSubCategories
$("#category").change(getSubCategories);
});
Please put getCategories() and getSubCategories() Methods inside Change function like this.Sorry for not code formatting.
<script>
$(document).ready(function(){
$("#category").change(function(){
getSubCategories();
});
$("#type").change(function(){
getCategories();
});
});
</script>
I have a javascript function which executes on the change of a dropdown:
<script type="text/javascript">
$(function()
{
// Executes when the status dropdown changes value
$('select[name="status_dropdown"]').change(function(event)
{
var $this = $(event.target);
var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table
var result = null;
var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data)
{
result = data;
alert(result);
}
});
});
})
</script>
I am trying to get the alert call to show the return value of the following php code (which is true):
<?php
.
.
.
return true;
?>
The alert doesn't pop up. Anyone know why ???
I tried your code with another URL and it's working well.
There are three cases:
scriptUrl is not calculated properly and doesn't point to your PHP script
your server is down
you are accessing an URL not served under the same domain as the one of your script (same-origin policy)
You can see detail of your error if you add an error handler to ajax parameters :
error : function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
Return only returns a value within the php script - to output it to ajax you need to actually output the result to the page, in this case something like echo "true"; or print("true");
Try this
$(document).ready(function(){
$('select[name="status_dropdown"]').change(function(event)
{
var $this = $(event.target);
var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table
var result = null;
var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data)
{
result = data;
alert(result);
}
});
});
});