event is not defined javascript firefox (json) - javascript

can any body tell me why my code error on firefox?
HTML:
Size : <select class="size" id="size<?php echo $dat_women->id; ?>" name="size" onchange="change_size(<?php echo $dat_women->id; ?>)">
JS:
function change_size(id_product){
var size = document.getElementById(event.target.id).value;
$.ajax({
dataType:"json",
url: site_url + "main/add_cart/" + id_product + "/" + size,
success:function(data){
window.location.assign("cart");
},
error: function(data){
alert('Anda belum memilih ukuran');
}
});
};
Error:
event is not defined

Try sending the element as a parameter to the function call:
In your HTML:
onchange="change_size(this,<?php echo $dat_women->id; ?>)"
and in your function defnition:
function change_size(element, id_product)
then you can get the size like this:
var size = element.value;

Plunker Example
HTML:
<select class="size" id="size2" name="size" onchange="change_size(this, 2)">
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
JS:
function change_size(id_product){
var size = $(this).value;
$.ajax({
dataType:"json",
url: site_url + "main/add_cart/" + id_product + "/" + size,
success:function(data){
window.location.assign("cart");
},
error: function(data){
alert('Anda belum memilih ukuran');
}
});
};

Related

Use specific select option when loading the page (jQuery + Ajax)

I retrieve a URL with jQuery + Ajax and determine the display based on certain select options.
The selection works fine, however I can't manage to place a default. I would like value="3" to be preselected and show the corresponding result already when loading the page, without having selected an option before.
How can I do this?
Here is my code so far:
$(document).ready(function() {
$("#reportMonth").on('change', function() {
var reportMonth = $('#reportMonth :selected').val();
if(reportMonth){
$.ajax({
type: "GET",
url: "https://api.tools.paeddy.de/server_info",
dataType: "json",
timeout: 15000,
})
.done(function(JSONOut) {
var out = "Server " + JSONOut[reportMonth].server + " = " + JSONOut[reportMonth].status;
$('#output').html(out);
})
.fail(function(xhr, status, error) {
$('#output').html("<div class='error'>Error: " + xhr.status + ' - ' + error + "</div>");
});
$('#show_output').html('<div id="output"></div>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<form>
<select id="reportMonth" name="reportMonth">
<option value="">Select:</option>
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
<option value="3">4</option>
</select>
</form>
<div id="show_output"></div>
</body>
</html>
JSFiddle
It looks like you're looking for the selected attribute. You'll also need to run the AJAX code to fetch the result for the default value, so extract your onchange handler into a function, then call it inside the onready handler. Like this:
function getResult() {
var reportMonth = $('#reportMonth :selected').val();
if (reportMonth) {
$.ajax({
type: "GET",
url: "https://api.tools.paeddy.de/server_info",
dataType: "json",
timeout: 15000,
})
.done(function(JSONOut) {
var out = "Server " + JSONOut[reportMonth].server + " = " + JSONOut[reportMonth].status;
$('#output').html(out);
})
.fail(function(xhr, status, error) {
$('#output').html("<div class='error'>Error: " + xhr.status + ' - ' + error + "</div>");
});
$('#show_output').html('<div id="output"></div>');
}
}
$(document).ready(function() {
getResult();
$("#reportMonth").on('change', getResult);
});
<!DOCTYPE html>
<html>
<body>
<form>
<select id="reportMonth" name="reportMonth">
<option value="">Select:</option>
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
<option value="3" selected>4</option>
</select>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="show_output"></div>
</body>
</html>
Just and some timeout and call trigger change.
$(document).ready(function() {
setTimeout(function() {
$("#reportMonth").trigger('change');
});
$("#reportMonth").on('change', function() {
var reportMonth = $('#reportMonth :selected').val();
if(reportMonth){
$.ajax({
type: "GET",
url: "https://api.tools.paeddy.de/server_info",
dataType: "json",
timeout: 15000,
})
.done(function(JSONOut) {
var out = "Server " + JSONOut[reportMonth].server + " = " + JSONOut[reportMonth].status;
$('#output').html(out);
})
.fail(function(xhr, status, error) {
$('#output').html("<div class='error'>Error: " + xhr.status + ' - ' + error + "</div>");
});
$('#show_output').html('<div id="output"></div>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<form>
<select id="reportMonth" name="reportMonth">
<option value="">Select:</option>
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
<option value="3" selected="selected">4</option>
</select>
</form>
<div id="show_output"></div>
</body>
</html>

AJAX loaded select, select option by value

How to select option by value, if the select is loaded via AJAX
index.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div id="data"></div>
</body>
<script>
function LoadSelect() {
var post_data = {
token: "test"
};
$.ajax({
type: 'POST',
url: 'load_select.php',
data: post_data,
dataType: "json",
beforeSend: function() {},
success: function(data) {
$("#data").html(data["msg"]);
},
complete: function() {}
});
}
$(document).ready(function() {
LoadSelect();
});
</script>
</html>
load_select.php
<?php
// Value from the database
$gender = "female";
$html = '
<select class="form-control" id="gender" name="gender">
<option value="female">Female</option>
<option value="male">Male</option>
</select>
<script>
$("#gender").val("'.$gender.'");
</script>
';
echo json_encode(array('msg' => $html));
Tried this code, but it's not working.
The problem solved, the $gender variable gets wrong value from the database like "f" and not "female".
Typically changing the value of a select via code should be followed by triggering the change event, like this $("#gender").trigger('change');
If I understand you correctly then you override the select with html from your ajax request. In order to maintain the value you will need to store the original value, then override the html and then restore the original value. See this snippet below.
Better would be to not override the html element with your ajax call but only update the information that need to be updated.
$("#gender").val("male");
//Lets pretend this onclick handler is your ajax succes handler.
$('#MimicAjax').on('click', function(){
//Fake ajax result for demonstraion purpose
var ajaxResult = '<select class="form-control" id="gender" name="gender"><option value="female">Female</option><option value="male">Male</option></select>';
//store the original value
var originalValue = $("#gender").val();
//Do your ajax thingy
$('#data').html(ajaxResult);
//restore original value
$("#gender").val(originalValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="data">
<select class="form-control" id="gender" name="gender">
<option value="female">Female</option>
<option value="male">Male</option>
</select>
</div>
<button id="MimicAjax">MimicAjax</button>
If you just want to set the value after you added the html with ajax then just use that line within the succes handler after you changed the html.
$.ajax({
type: 'POST',
url: 'src/ajax/load_select.php',
data: post_data,
dataType: "json",
beforeSend: function() {},
success: function(data) {
$("#data").html(data["msg"]);
$("#gender").val("male");
},
complete: function() {
}
});

passing value from javascript to sql via ajax

I have some problem when I pass variable across php , javascript and ajax.
html - when I change the selected value, ajax will post the new value:
<select name="PACKAGE_CATEGORY" id="PACKAGE_CATEGORY" onclick="fireAjax()" class="form-control" >
<option value="0" disabled selected hidden> -- select an option -- </option>
<option value="PLINE">Phone Line Only</option>
<option value="UNIFI">Unifi for New Registration</option>
<option value="STREAMYX">Streamyx for New Registration</option>
<option value="WEBE">Webe</option>
<option value="DOME">Lease Line (DOME)</option>
</select>
ajax - I get the value by javascript and save it in var1:
<script>
function fireAjax(){
$.ajax({
url: 'form.php',
type: 'POST',
data: {var1: document.getElementById('PACKAGE_ID').innerHTML },
success: function(data) {
console.log("success");
}
});
}
javascript function - I want to take the value var1 from ajax, but fail:
<script>
$(function () {
var pricestore = [
<?php
$var1 = $_POST['var1']; // I cannot get the var1, please help me T.T
$sqlpid=mysqli_query($conn, "select no from product where P_NAME = '$var1' ");
//some function
//.............
?>
];
});
</script>
Change onclick() to onchange()
<select name="PACKAGE_CATEGORY" id="PACKAGE_CATEGORY" onchange="fireAjax()" class="form-control" > //Here
<option value="0" disabled selected hidden> -- select an option -- </option>
<option value="PLINE">Phone Line Only</option>
<option value="UNIFI">Unifi for New Registration</option>
<option value="STREAMYX">Streamyx for New Registration</option>
<option value="WEBE">Webe</option>
<option value="DOME">Lease Line (DOME)</option>
Try the following:
Html:
<select name="PACKAGE_CATEGORY" id="PACKAGE_CATEGORY" onchange="fireAjax()" class="form-control" >
<option value="0" disabled selected hidden> -- select an option -- </option>
<option value="PLINE">Phone Line Only</option>
<option value="UNIFI">Unifi for New Registration</option>
<option value="STREAMYX">Streamyx for New Registration</option>
<option value="WEBE">Webe</option>
<option value="DOME">Lease Line (DOME)</option>
</select>
Javscript:
<script>
function fireAjax(){
$.ajax({
url: 'form.php',
type: 'POST',
data: {var1: document.getElementById('PACKAGE_CATEGORY').value},
success: function(data) {
console.log("success");
}
});
}
Changed onclick to onchange, changed id, changed innerHtml to value
Try to change your ajax call into change event of selector,
$('#PACKAGE_CATEGORY').change(function(){
$.ajax({
url: 'form.php',
type: 'POST',
data: {
'var1': $(this).val()
},
success: function(data) {
console.log("success");
}
});
})

PHP not capturing data sent on jquery submit

;;I have a form which allows users to dynamically add a new form input row. Each time a user creates a new row. The inputs are added as an array:
$(document).ready(function() {
var currentItem = 1;
$('#addnew').click(function(){
currentItem++;
$('#items').val(currentItem);
var strToAdd = '<tr><td>Year</td><td>:</td><td><select name="year[]" ><option value="2012">2012</option><option value="2011">2011</option></select></td><td width="7%">Week</td><td width="3%">:</td><td width="17%"><select name="week[]" ><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option></select></td><td width="8%"> </td><td colspan="2"> </td></tr><tr><td>Actual</td><td>:</td><td width="17%"><input name="actual[]" type="text" /></td><td width="7%">Max</td> <td width="3%">:</td></tr>';
$('#data').append(strToAdd);
});
});
Check the Fiddle
The problem I'm having is when I submit the form. I'm not able to capture any of the data through my php:
$("#upload").validate({
submitHandler: function (form) {
$.ajax({
url: '<?php echo base_url(); ?>/ajax_upload',
type: 'POST',
data: $(form).serialize(),
success: function(data) {
if(data)
{
alert("success");
} else {
alert("error");
}
},
error: function(data){
alert("error");
},
cache: false,
contentType: false,
processData: false
});
return false;
}
});
When executing this code:
var_dump($_POST['year']); or echo count($_POST['year'])
I receive the following error: Message: Undefined index: year
In my firebug under the console view. POST I see the data is being posted
year%5B%5D=2012&week%5B%5D=1&actual%5B%5D=test&year%5B%5D=2011&week%5B%5D=2&actual%5B%5D=test+2&items
=3&sub=Submit+values
but it still doesn't seem to be capturing.
Any help will be appreciated

Assign javascript variable to php variable

How to pass javascript variable that came from select option to a PHP variable?
I want to set PHP variable depending on user selection.
I tried that code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function(){
$("select[name='sex']").change(function () {
var submitSearchData = jQuery('#extended-search').serialize();
var selectedValue=$('#sex').val();
jQuery.ajax({
type: "POST",
data: 'selected=' + selectedValue
url: "ajax.php",
success: function () {
// alert(submitSearchData);
alert(selectedValue);
}
});
});
});
</script>
<form id="extended-search" >
<div class="input-container">
<select class="select" name="sex" id="sex">
<option value="0">All</option>
<option value="1">M</option>
<option value="2">F</option>
</select>
</div>
</form>
<?php
var_dump ($_REQUEST['selected']); //that print NULL don't know why!
?>
You are passing data in wrong format. Data is passed as an object. Please refer below.
$("select[name='sex']").change(function () {
var submitSearchData = jQuery('#extended-search').serialize();
var selectedValue=$('#sex').val();
jQuery.ajax({
type: "POST",
data: {'selected': selectedValue},
url: "ajax.php",
success: function (response) {
// alert(submitSearchData);
alert(response);
}
});
});
Is not possible in the same instance of time:
yourfile -> ajax -> yourfile (here is the value, but you can't see this in your current webpage except that instead of ajax, send post form)
I hope this will help you...
dataType: "html",
data: {'selected': selectedValue},
and then u can get it via $_POST/$_REQUEST array since you have set your type to post.
$_REQUEST is null because it is not related to the ajax request you send. Try this for example:
<?php
if (isset($_POST["selected"])) {
echo $_POST["selected"];
} else {
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<form id="extended-search">
<div class="input-container">
<select class="select" name="sex" id="sex">
<option value="0">All</option>
<option value="1">M</option>
<option value="2">F</option>
</select>
</div>
</form>
<script>
$(function() {
$("select[name='sex']").change(function () {
var selected = $(this).val();
$.ajax({
type: "POST",
data: {
selected: selected
},
url: "ajax.php",
success: function (data) {
alert(data);
}
});
});
});
</script>
</body>
</html>
<?php } ?>
EDIT:
I updated the script and tested it. You had some errors in your code. Hope this works for you.

Categories