Fetch mulitple values using Jquery post getting undefined value - javascript

Below is my jquery ajax method
<script type="text/javascript">
$(document).ready(function () {
$('#c_select').change(function(){
var one = 10;
var two = 20;
var three = 30;
var four = 40;
$.ajax({
type:'post',
url:'getvalues.php',
dataType: JSON,
success:function(resp){
alert(resp.first);
}
error:function(resp){
alert(resp.first);
}
});
});
});
</script>
Below given file is where i get the values (PHP File)
<?php
$output = array('first'=>'Steven',
'last'=>'Spielberg',
'address'=>'1234 Unlisted Drive');
echo json_encode($output,JSON_FORCE_OBJECT);
?>
success part is not getting executed i am getting undefined error

Try following code, it should work
$(document).ready(function() {
$('#c_select').change(function() {
var one = 10;
var two = 20;
var three = 30;
var four = 40;
$.ajax({
type: 'post',
url: 'getvalues.php',
dataType: 'json',
success: function(resp) {
alert(resp.first);
},
error: function(resp) {
}
});
});
});

Related

jquery ReferenceError: is not defined variable as array index

I'm getting this error ReferenceError: postCssID is not defined
My script is working if I add js code inside my php file but not working if I use separated js file
in php is working
<script type="text/javascript">
var offsets = offsets || new Array();
offsets["<?=$pst_cssid?>"] = 5;
$("#cmt-a-ii<?=$pst_cssid?>").click(function(){
$.ajax({
url: "<?=Url::to(['/comment/view-more'])?>",
type: 'POST',
data: ({st: '<?=$pst_id?>', cssid: '<?=$pst_cssid?>', offset: offsets["<?=$pst_cssid?>"]}),
success: function(result){
$("#cmt-d-ii<?=$pst_cssid?>").append(result);
}
});
offsets["<?=$pst_cssid?>"] += 5;
});
</script>
But if I use separated js file is not working , the error is in this : offsets[postCssID]; in my php file I only declare variables
<script type="text/javascript">
var postCssID = "<?=$pst_cssid?>";
var postID = "<?=$pst_id?>";
var urlLink = "<?=Url::to(['/comment/view-more'])?>";
</script>
I add path to my js file : <script src="/sxct/js/ly-extra-script.js"></script>
var offsets = offsets || new Array();
offsets[postCssID] = 5;
$("#cmt-a-ii"+postCssID).click(function(){
$.ajax({
url: urllink,
type: 'POST',
data: ({st: postID, cssid: postCssID, offset: offsets[postCssID]}),
success: function(result){
$("#cmt-d-ii"+postCssID).append(result);
}
});
offsets[postCssID] += 5;
});

Unable to change image onChange function on ajax success return

Hi I'm new to this javavascript/ajax. I am trying to create a dropdown that dynamically changes the images by the different options as shown in this Fiddle here but the change function does not seem to be working.
I made sure that I am able to get the data from pictureList but the image source did not change successfully as the fiddle.
$('#selectVariant').change(function () {
var sku = $('#selectVariant :selected').val();
var sessionId="<?php echo $sessionId; ?>";
var dataString='sku='+ sku +'&sessionId='+sessionId;
$.ajax({
type:"post",
url: "<?php echo $base_url; ?>ajax-helper/search_variant.php",
data:dataString,
cache:false,
dataType: "JSON",
success: function(data){
var pictureList = {};
//example of my data list
//var pictureList = {'Apple SKU2': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png",
//'Pear1': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/pears.png"
//};
$.each(data.productVariantImages,function(i, productVariantImages){
pictureList[data.sku] = this.imagePath;
});
console.log(pictureList);
$('.content img').attr({"src":[pictureList[this.value]]});
}
});
return false;
});
However, when I do test it outside the ajax post, it is able to run.
Instance of this is change in ajax success function scope.
In this line $('.content img').attr({"src":[pictureList[this.value]]}); this
is not the instance of selectVariant element.
The usual practice for this is declare a variable that and use that variable in other scope. try the below code.
$('#selectVariant').change(function () {
var sku = $('#selectVariant :selected').val();
var sessionId="<?php echo $sessionId; ?>";
var dataString='sku='+ sku +'&sessionId='+sessionId;
var that = this;
$.ajax({
type:"post",
url: "<?php echo $base_url; ?>ajax-helper/search_variant.php",
data:dataString,
cache:false,
dataType: "JSON",
success: function(data){
var pictureList = {};
//example of my data list
//var pictureList = {'Apple SKU2': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png",
//'Pear1': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/pears.png"
//};
$.each(data.productVariantImages,function(i, productVariantImages){
pictureList[data.sku] = this.imagePath;
});
console.log(pictureList);
$('.content img').attr({"src":[pictureList[that.value]]});
}
});
return false;
});

Passing arrays js variable to php

Currently I have stored variables in a Javascript array. The goal here is to turn them into PHP variables so that I can use these variables and insert them into my database.
The problem with this code is that the AJAX part doesn't work. Please get me in the right direction as I am extremely new to AJAX. I did try to read about them but still do not understand much. Doing it without refreshing the page is not necessary. Methods other than AJAX are welcomed.
Here is my current code:
<button onclick="Bookings()">Book</button>
<script>
function Bookings() {
var t2Cells = document.getElementsByClassName("t2");
for (var i = 0; i < t2Cells.length; i++) {
var t2CellsIndex [i] = t2Cells[i].cellIndex
var t2CellsRow [i] = t2Cells[i].parentNode.rowIndex
//alert('Coordinates are: '+t2Cells [i].cellIndex+'x'+t2Cells [i].parentNode.rowIndex);
var tbl = document.getElementById("tblMain");
//alert (tbl.rows[0].cells[t2CellsIndex].innerHTML);
var studioSelected = tbl.rows[0].cells[t2CellsIndex].innerHTML
var Timeselected = tbl.rows[t2CellsRow].cells[0].innerHTML
$.ajax({
type: "POST",
url: 'bookingconfirm.php',
data: "studioSelected=" + studioSelect,
success: function(data) {
alert("success!");
}
});
}
}
</script>
<?php
//bookingconfirmed.php
if (isset($_POST['studioSelect'])) {
$uid = $_POST['studioSelect'];
//steps to insert into database.
First, you should move ajax call outside of foreach
var usefulData = [];
var t2Cells = document.getElementsByClassName("t2");
for (var i = 0; i < t2Cells.length; i++) {
var t2CellsIndex [i] = t2Cells[i].cellIndex
var t2CellsRow [i] = t2Cells[i].parentNode.rowIndex
//alert('Coordinates are: '+t2Cells [i].cellIndex+'x'+t2Cells [i].parentNode.rowIndex);
var tbl = document.getElementById("tblMain");
//alert (tbl.rows[0].cells[t2CellsIndex].innerHTML);
var studioSelected = tbl.rows[0].cells[t2CellsIndex].innerHTML
// add data to array
usefulData.push(studioSelected);
var Timeselected = tbl.rows[t2CellsRow].cells[0].innerHTML
}
$.ajax({
type: "POST",
url: 'bookingconfirm.php',
data: {'usefuldata': usefulData},
success: function(data) {
alert("success!");
}
});
Then in your php file:
if (isset($_POST['usefuldata'])) {
var_dump($_POST['usefuldata']);
}

I don't understand AJAX callbacks

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);
}
});
});
});

How Can I Do to my textbox autocomplete, works

I'm trying to do an autocomplete to my textbox, but it doesn't work. Follow my code.
$(function () {
var credenciada = '<%= credenciadaId %>';
xml_NomeCompleto = "";
var Nomes = "";
var retorno = '';
var count = 0;
var t = '';
$.ajax({
url: "../Xml/AcessoExterno.aspx?Credenciada=" + credenciada,
type: "get",
dataType: 'xml',
async: false,
success: function (data) {
$(data).find("REGISTRO").each(function () {
t = $(this).find("NOMECOMPLETOUSUARIO").text();
Nomes += ["\"" + t + "\","];
});
}
});
$("#ctl00_contentConteudo_txtNome").autocomplete({ source: Nomes });
});
The variable 't' receives all the names of my users, normally, but the autocomplete don't work.
Wait for ajax response to complete and then initialize the autocomplete because before you initialize the plugin data is not available. Also the way you are creating Nomes(source) is wrong. Declare it as an array and use push method to populate it.
Try this
var Nomes = [];
$.ajax({
url: "../Xml/AcessoExterno.aspx?Credenciada=" + credenciada,
type: "get",
dataType: 'xml',
async: false,
success: function (data) {
$(data).find("REGISTRO").each(function () {
Nomes.push($(this).find("NOMECOMPLETOUSUARIO").text());
});
$("#ctl00_contentConteudo_txtNome").autocomplete({ source: Nomes });
}
});

Categories

Resources