How can i use ajax data variable use under submit button - javascript

When I click submit button, I cannot receive the value yearend. Instead I got an undefined value. How can I get yearend value when I click submit button?
My code:
$("#company").change(function() {
$("#dFrom").val("");
$("#dTo").val("");
var pass_code = $("#company").val();
var callpage = "dentrycomp.php?pass_code=" + pass_code
var yearend= null;
$.ajax({
type: "GET",
url: callpage,
async: false,
success: function(data) {
yearend= data,
$("#content").html("")
$("#content").html(data)
}
});
//var yearend = "<?php echo $_SESSION['yearend'] ; ?>"
alert(yearend +"company");
this alert box getting the right value yearend.i want that value recieve in under submit button
return true;
});
$('#submit').live('click',function() {
//var yearend = "<?php echo $_SESSION['yearend'] ; ?>"
alert("this is submit button"+yearend);

var yearend = null;
$("#company").change(function() {
$("#dFrom").val("");
$("#dTo").val("");
var pass_code = $("#company").val();
var callpage = "dentrycomp.php?pass_code=" + pass_code
$.ajax({
type: "GET",
url: callpage,
async: false,
success: function(data) {
yearend = data,
$("#content").html("")
$("#content").html(data)
}
});
//var yearend = "<?php echo $_SESSION['yearend'] ; ?>"
alert(yearend + "company");
this alert box getting the right value yearend.i want that value recieve in under submit button
return true;
});
$('#submit').live('click', function() {
//var yearend = "<?php echo $_SESSION['yearend'] ; ?>"
alert("this is submit button" + yearend); });
You should declare yearend globally i.e. at the top of the code.

I think it's because of var scope. You must define variable before the request and then redefine it and get it after the AJAX request.

That's the expected behavior with ajax outside your ajax call yearned is undefined. Put your on click function in ajax call itself. So, once your ajax call is finished and successful you'll attach your event listener in the success function. Use this logic instead:
$.ajax({
type: "GET",
url: callpage,
async: false,
success: function(data) {
yearend= data,
$("#content").html("")
$("#content").html(data)
$('#submit').live('click',function(){
//var yearend = "<?php echo $_SESSION['yearend'] ; ?>"
alert("this is submit button"+yearend);
});
}
});

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: callpage,
async: false,
success: function(data) {
yearend= data,
$("#content").html("")
$("#content").html(data)
$('#submit').live('click',function(){
alert("this is submit button"+yearend);
});
}
});
});
</script>
</head>
<body>
</body>
</html>

Related

echo js using php to append more options to select input

Okay so I'm having that JS :
<script>
$('#building').change(function () {
var selectedValue = $(this).val();
$.ajax({
url: 'getunits.php',
type: "POST",
async:false,
contentType: "application/x-www-form-urlencoded;charset=utf-8",
data:{
building: selectedValue,
},
success: function (result) {
var e = document.getElementById('div1');
e.innerHTML = result;
eval(document.getElementById('runscript').innerHTML);
}
});
});
</script>
<div id="div1">
</div>
And that in the PHP :
$selectunits = mysqli_query($con,"SELECT * FROM `units` WHERE `building`='".$building."'");
echo '<script type="text/javascript" id="runscript">';
while($rowunits = mysqli_fetch_assoc($selectunits))
{
//echo '<option value="'.$rowunits["ID"].'">'.$rowunits["unit_number"].'</option>';
echo '$("#unit").append("<option value="'.$rowunits["ID"].'">'.$rowunits["unit_number"].'</option>");';
}
echo'</\script>';
All I'm trying to do is after I select from the first select, an Ajax goes to that URL and fills up the 2nd select with different data. So what I was able to do is do a loop in the PHP to create the required JS to fill up.

my ajax post method works but i can not catch the value by php

post method , it can post value, my success alert is working but i can not echo in my php. i tried to send to same page and another page. Both they haven't work. Here is my ajax code :
<script>$( "#il" ).change(function() {
var aa = $("#il").val();
$.ajax({
url: 'never.php',
type: 'POST',
data: { aa1 : 'mynameis'},
success: function () {
alert($("#il").val());
},
});
});
</script>
and here is my php code to catch :
<?php
$aa = $_POST['aa1'];
if($aa != ""){
echo $aa;
} else { echo "puuf";}
?>
In order to catch the data returned from the PHP echo you need to add a parameter to the success method for javascript to place the value in for you to then make use of
<script>
$( "#il" ).change(function() {
var aa = $("#il").val();
$.ajax({
url: 'never.php',
type: 'POST',
data: { aa1 : 'mynameis'},
success: function (data) {
// - - - - - - - - ^^^^
alert($("#il").val(data));
// - - - - - - - - - ^^^^
}
});
});
</script>
You'll have to define a data parameter on the success callback, because the echoed data have to be passed as argument to it. So,
The client script:
<script type="text/javascript">
$("#il").change(function () {
var aa = $("#il").val();
$.ajax({
url: 'never.php',
type: 'POST',
data: {
aa1: 'mynameis'
},
success: function (data) {
alert(data);
},
});
});
</script>
And the PHP:
<?php
$aa = $_POST['aa1'];
if (isset($aa) && !empty($aa)) {
echo $aa;
} else {
echo "puuf";
}
?>

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

Add one or two more PHP variables to the javascript code

I am a decent PHP programer and recently I got stuck in a javascript code.
I have the code below:
$(function () {
$('.more').live("click", function () {
var ID = $(this).attr("id");
if (ID) {
$("#more" + ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "scripts/loadmore.php",
data: "lastmsg=" + ID,
cache: false,
success: function (html) {
$("div#updates").append(html);
$("#more" + ID).remove();
}
});
} else {
$(".morebox").html('The End');
}
return false;
});
});
This code submit without problems one PHP variable to the process page loadmore.php using this input
<div id="more<?= $load_id ?>" class="morebox" style="margin-bottom: 200px;">
<a href="#" class="more" id="<?php echo $load_id; ?>">
load more
</a>
</div>
How can put more variables in the input and the javascript code to work with them on the process page?
I want to set one or two more variables.
UPDATE:
I updated the code like this:
HTML input:
<div id="more<?= $load_id ?>" class="morebox" style="margin-bottom: 200px;">
load more</div>
JAVASCRIPT CODE:
<script type="text/javascript">
$(function() {
$('.more').live("click",function()
{
var ID = $(this).attr("data-id");
var ACT = $(this).attr("data-act");
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "scripts/loadmore.php",
data: {"lastmsg="+ ID, "act="+ ACT},
cache: false,
success: function(html){
$("div#updates").append(html);
$("#more"+ID).remove();
}
});
}
else{
$(".morebox").html('The End');
}
return false;
});
});
</script>
I am not sure if the data lines was writed properly because the script looks like it's frozen now
SOLVED:
I just used a datastring like this
<script type="text/javascript">
$(function() {
$('.more').live("click",function()
{
var ID = $(this).attr("data-id");
var ACT = $(this).attr("data-act");
var dataString = 'lastmsg='+ ID + '&act=' + ACT;
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "scripts/loadmore.php",
data: dataString,
//data: {"lastmsg="+ ID, "act="+ ACT },
cache: false,
success: function(html){
$("div#updates").append(html);
$("#more"+ID).remove();
}
});
}
else{
$(".morebox").html('The End');
}
return false;
});
});
</script>
Just send data as an object:
data: {
"lastmsg": "lastmsg="+ ID,
"anotherData": "someData"
}
You'll retrieve them in your PHP script as follows:
$_POST["lastmsg"];
$_POST["anotherData"];

auto submit form to a url if textfield is not empty

I'm trying to auto submit a form when the username column is not null. i've got my script down there but since i'm new to jquery, i've got it missed up and its not working
$(function() {
var $username = $('#username'),
if ($username != null){
$("#form1").submit,function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "http://mysample.com/ans.php",
data: data,
success: function(data) {
$('#log_msg').html(data);
var result = $.trim(data);
if(result==="ok"){
window.location = 'page.html';
}
});
});
});
Try to use on change listener, like
$(document).on('change', '#input_id', function(e) {
$('form_selector').submit();
});
$(document).on('submit', 'form_selector', function(e) {
//Your ajax submit logic
});
If you want to do an AJAX submission, just call $.ajax in the if:
$(function() {
var $username = $("#username").val();
if ($username != '') {
$.ajax({
type: "POST",
url: "/ans.php",
data: $("#form1").serialize(),
success: function(data) {
$('#log_msg').html(data);
var result = $.trim(data);
if(result==="ok"){
window.location = 'page.html';
}
});
}
});
You don't need to define a $("#form1").submit() handler for this.

Categories

Resources