jQuery AJAX POST; Not posting - javascript

I'm fairly certain the issue I'm having is related to the jQuery's $.ajax({...}); function . When printing the array in PHP i get Notice: Undefined index.
I'd sincerely appreciate it if i could get some advice here.
<script>
$(document).ready(function(){
$("#submit").click(function() {
var platform_var = $('input[name="platform"]').val();
var bandwidth_var = $("#bandwidth-widget").val();
alert(bandwidth_var); // Returns the array as an alert.
$.ajax({
url: "index.php",
type: "POST",
data: {
platform_var: platform_var,
bandwidth_var: bandwidth_var
}
});
});
});
</script>
<?php
print_r($_POST['platform_var']);
?>
Demo (w/o PHP)

You need to assign the values to the variables on document load.
$(document).ready(function() {
platform_var = $('input[name="platform"]').val();
bandwidth_var = $("#bandwidth-widget").val();
});
EDIT: if the values are not instanciated on document load, you need to assign them when they actually have the correct value, just before you do the Ajax request.
$(document).on('submit', '#compare', function(e) {
var platform_var = $('input[name="platform"]').val();
var bandwidth_var = $("#bandwidth-widget").val();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: {
platform: platform_var,
bandwidth: bandwidth_var
}
});
});
Currently, you are assigning them before the values actually exists.
Hope this helps.

Your have two problems in your code:
The selector is wrong - you're searching for an input with the name attribute which equals to platform and in the html you have an array input with the name platform[]. Therefore it will not find any matching inputs, which is why the var platform_var is undefined or null.
To fetch the checked checkboxes, you need to add :checked to the selector, otherwise jQuery will return all of the checkboxes regardless of their checkbox status.
To fix this, simply change
var platform_var = $('input[name="platform"]').val();
to
var platform_var = $('input[name="platform[]"]:checked').map(function(){return $(this).val();}).get();
Also, have in mind that in your php script, the $_POST['platform'] variable will be an array.
I would advice you to have a look at the jQuery API documentation to further understand how the selectors work.
Here is the edited fiddle.
Edit:
I've code I've added below confirms that the code in the fiddle is working fine. Apparently you are having trouble with your own php code rather than your JavaScript.
I believe you should sit down and check your code.
<?php
// Save everything here in a file called "test.php"
if (isset($_POST) && !empty($_POST)){
print_r($_POST);
exit();
}
?>
<html>
<head>
<title>Testing page</title>
<link rel="stylesheet" type="text/css" href="http://www.hostingarchive.com/wp-content/themes/My-theme/assets/styles/jquery.selectBox.css"/>
<link rel="stylesheet" type="text/css" href="http://www.hostingarchive.com/wp-content/themes/My-theme/assets/styles/jquery.nouislider.min.css"/>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://www.hostingarchive.com/wp-content/themes/My-theme/assets/scripts/jquery.selectBox.js"></script>
<script type="text/javascript" src="http://www.hostingarchive.com/wp-content/themes/My-theme/assets/scripts/jquery.nouislider.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.cmp-select').selectBox();
$("#price-widget").noUiSlider({
range: [5, 150], start: [5, 75], step: [5], connect: true, direction: 'ltr', serialization: {
mark: '.', resolution: 1, to: [
[$("#low-price"), 'html'],
[$('#high-price'), 'html']
]
}
});
$("#bandwidth-widget").noUiSlider({
range: [0, 2000], start: [10, 1000], step: [10], connect: true, direction: 'ltr', serialization: {
mark: '.', resolution: 1, to: [
[$("#low-bandwidth"), 'html'],
[$('#high-bandwidth'), 'html']
]
}
});
$("#submit").click(function () {
var platform_var = $('input[name="platform[]"]:checked').map(function () {
return $(this).val();
}).get();
var bandwidth_var = $("#bandwidth-widget").val();
alert(bandwidth_var);
console.log(platform_var);
console.log(bandwidth_var);
$.ajax({
url : "test.php",
type: "POST",
data: {
platform_var : platform_var,
bandwidth_var: bandwidth_var
}
});
});
});
</script>
</head>
<body>
<div id="compare">
<h3>Platform</h3>
<input name="platform[]" type="checkbox" value="shared" checked="checked">Shared</input>
<input name="platform[]" type="checkbox" value="dedicated">Dedicated</input>
<input name="platform[]" type="checkbox" value="cdn">CDN</input>
<input name="platform[]" type="checkbox" value="vps">VPS</input>
<input name="platform[]" type="checkbox" value="vds">VDS</input>
<h3>Bandwidth</h3>
<div id="bandwidth-slide">
<p class="inline-block"><span id="low-bandwidth"></span><span><small>GB</small></span></p>
<div class="inline-block" id="bandwidth-widget"></div>
<p class="inline-block"><span id="high-bandwidth"></span><span><small>GB</small></span></p>
</div>
<h3>Price</h3>
<div id="pricing-slide" class="clearfix">
<p class="inline-block">$<span id="low-price"></span></p>
<div class="inline-block" id="price-widget"></div>
<p class="inline-block">$<span id="high-price"></span><span>/mo</span></p>
</div>
<input type="submit" id="submit" value="enter">
</div>
</body>
</html>

Related

Losing Button value on form submit with Confirm dialogue

I'm trying to pass a button value on a form submit in conjunction with a jquery confirm dialogue, but it's not going through. I understand it has something to do with the script using a "form.submit" function but I'm not familiar enough with JS to code a workaround to the problem.
Is there a way to maybe reassign the first button's value to a new JS variable and pass that instead?
I've simplified the form down to its basic elements to make it easy to follow. The data I'm trying to pass in this example is "123" using the button tied to the confirm dialogue script. A second "regular button" is added to demonstrate a successful form submission. Some PHP gathers in the POST data and displays it.
// Results:
// $regularbutton = '456';
// $alertbutton = '';
testpage.php:
<html>
<head>
<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript">
//<![CDATA[
$(function () {
'use strict';
function confirmDialog(title, message, success) {
var confirmdialog = $('<div></div>').appendTo('body')
.html('<div><h6>' + message + '</h6></div>')
.dialog({
modal: true,
title: title,
zIndex: 10000,
autoOpen: false,
width: 'auto',
resizable: false,
buttons: {
Yes: function () {
success();
$(this).dialog("close");
},
No: function () {
$(this).dialog("close");
}
},
close: function() {
$(this).remove();
}
});
return confirmdialog.dialog("open");
}
$('#submit_alert').on('click', function (e) {
e.preventDefault();
var form = document.getElementById('form_alert');
confirmDialog('Confirm', 'Are you sure you want to proceed?', function () {
form.submit();
});
});
});
//]]>
</script>
<link rel="stylesheet" type="text/css" href="//code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
</head>
<body>
<?php
extract($_POST);
echo "button1: $alertbutton <br>";
echo "button2: $regularbutton <br>";
?>
<form method="post" id="form_alert" action="testpage.php">
<button name="alertbutton" value="123" id="submit_alert">Alert Button</button>
<button name="regularbutton" value="456">Regular Button</button>
</form>
</body>
</html>
The value of the button is not commited.
You could inject a hidden field before calling the form.submit():
confirmDialog('Confirm', 'Are you sure you want to proceed?', function () {
$('#form_alert').append('<input type="hidden" name="alertbutton" id="submit_alert_hidden" value="' + $('#submit_alert').val() + '" />');
form.submit();
});
You can use the attribute data-* to pass some datas :
$(function()
{
$(".MyButton").on('click', function(e)
{
// note that some-value is camelCased to someValue
console.log(e.target.dataset.someValue);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="MyButton" name="alertbutton" data-some-value="123" id="submit_alert">Alert Button</button>
<button class="MyButton" name="regularbutton" data-some-value="456">Regular Button</button>

jQuery autocomplete dynamic ajax

I'm trying to build a search input with the autocomplete feature. However, the suggestions depend on the input and are not static - which means that I have to retrieve the list every time the user types into the field. The suggestions are based on Google autosuggest: "http://google.com/complete/search?q=TERM&output=toolbar".
I'm currently using http://easyautocomplete.com.
This is my code:
var array = [];
var options = {
data: array
};
$("#basics").easyAutocomplete(options);
$("#basics").on("keyup",function() {
var keyword = $(this).val();
array = [];
updateSuggestions(keyword);
});
function updateSuggestions(keyword) {
$.ajax({
type: "POST",
url: "{{ path('suggestKeywords') }}",
data: {keyword:keyword},
success: function(res){
var res = JSON.parse(res);
for(var i in res)
{
var suggestion = res[i][0];
array.push(suggestion);
console.log(suggestion);
}
}
});
var options = {
data: array
};
$("#basics").easyAutocomplete(options);
}
I know this is not a very good way to do this - so do you have any suggestions as to how to do it?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete functionality</title>
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- Javascript -->
<script>
$(function() {
var availableTutorials = [
"ActionScript",
"Boostrap",
"C",
"C++",
];
$("#automplete-1").autocomplete({
source: availableTutorials
});
});
</script>
</head>
<body>
<!-- HTML -->
<div class="ui-widget">
<p>Type "a" or "s"</p>
<label for="automplete-1">Tags:</label>
<input id="automplete-1">
</div>
</body>
</html>

Why is event parameter forgotten after recursion?

Consider the following code:
<html>
<head>
<meta charset="UTF-8">
<title>title...</title>
<link type="text/css" rel="stylesheet" href="jquery-ui-1.10.4.custom.css" />
<script type="text/javascript" src="jquery-1.10.2.js"></script>
<script type="text/javascript" src="jquery-ui-1.10.4.custom.min.js"></script>
</head>
<body>
<div id="dialog1" style="display: none">
<p>some text</p>
</div>
<input id="but1" type="button" value="clickme" />
</body>
<script>
$("#but1").on ('click', {valu: 1}, f);
$("#dialog1").dialog({ autoOpen:false });
function f (event) {
console.log(event.data.valu); // EXISTS
$.ajax({
type: "POST",
url: "event.xml",
dataType: "xml",
success: function (result) {
console.log(event.data.valu); // DOESN'T EXIST
var promptDialog = $("#dialog1");
var promptDialogButtons = {};
promptDialogButtons['ok'] = function(){
$("#dialog1").on('click', { valu: 0 }, f);
$("#dialog1").click();
$("#dialog1").dialog('close');
};
promptDialogButtons['cancel'] = function(){
$("#dialog1").dialog('close');
};
promptDialog.dialog({ width:333, modal: true, title: "sometitle", buttons:promptDialogButtons});
$("#dialog1").dialog('open');
}
});
}
</script>
</html>
When clicking on "clickme" and then "ok" the output will be:
1
1
0
TypeError: event.data is null
Why is event.data.valu forgotten in the $.ajax() after recursion? No redeclaration of parameter event in the $.ajax(). Please fill in the valid path to the JQuery libraries. Use any valid event.xml file.
Apparently the jquery-ui dialogue does handle the click event of the ok button differently. your problem could be solved by calling the function f directly within the success function.
f({ data:{
valu: 0
}
});
see http://jsfiddle.net/klickagent/3L1zro7w/8/
for a working example

Ajax call to dynamically populate dropdown works in FF, but not in Chrome and IE

I really don't know why my code works perfectly in Firefox, but when I test it in Chrome or IE, it doesn't populate a dynamic dropdown. I read some similar posts, but most of them said it's because of an unclosed div which I don't have!
Here is the code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"/>
</head>
<body>
<input type="textbox" name= "tag" id="tags">
<p>
<select id="movieImdbId" name="movieImdbId[]" multiple="multiple" width="200px" size="10px" style=display:none;>
</select>
</p>
<script type="text/javascript">
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php", //php file which fetch actors name from DB
minLength: 2,
select: function (event, ui){
var selectedVal = $(this).val();
// Here goes your ajax call.
$.post("actions.php", {q: selectedVal}, function (response){
// response variable above will contain the option tags.
$("#movieImdbId").html(response).show();
});
}
});
});
</script>
</body>
</html>
Try to Explicitly Map your response here's an example from my code change to be applicable
From your post request return a json object, with two values, the label, what you want to display from the autocomplete and the value, what value you want to associate with that label, in this example I saved the value in a property (.url) as the value because I wanted my autocomplete to sync to a url.
The response function binds your results to the control. It takes in the $.map a jquery delegate which maps the array to the required structure (label is mapped to templab item.label (a property I serialized in json from the post))
(value is mapped to the item.url).
I'm not sure if this will solve your porblem but now you will be explicitly binding your data
success: function (data) {
response($.map(data, function (item) {
// this line below is a hack to get out the html encoded entities (> <...)
var templab = $('#searchhtmlconverter').html(item.label).text();
return { label: templab, value: item.url };
}))
Thanks to this post, I could finally solved my problem by just using autocompletechange event, instead of change event.
So This is the code worked for me:
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
select: function (event, ui){
$("#tags").on('autocompletechange change', function (){
var selectedVal = $(this).val(); //this will be your selected value from autocomplete
$.post("actions.php", {q: selectedVal}, function (response){
$("#movieName").html(response).show();
});
}).change();
}
});
});

JQuery add Checkbox not working

I am currently experimenting with the google chart api and jquery. I don't have any problems with the google chart api so far, however i have not been able to get jquery working. What I want to do is I want to loop over my json objects I got and add Checkboxes depending on what I get out of the json.
<html>
<head>
<title>Test</title>
<!-- Load jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<!-- Load Google JSAPI -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
addSensorCheckboxes();
function drawChart() {
var jsonData = $.ajax({
dataType: "json",
url: "getValues.php",
data: window.location.href.slice(window.location.href.indexOf('?') + 1),
async: false
}).responseText;
var obj = jQuery.parseJSON(jsonData);
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: ''
};
var chart = new google.visualization.LineChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
function addSensorCheckboxes() {
var jsonData = $.ajax({
dataType: "json",
url: "getSensors.php",
async: false
}).responseText;
var obj = jQuery.parseJSON(jsonData);
for (i in obj)
{
var checkbox = '<input type="checkbox" name="sensors[]" value="'+obj[i][0]+'" />'+obj[i][1];
//alert(checkbox);
$("#test").append(checkbox);
}
}
</script>
</head>
<body>
<form id="theForm" name="theForm" action="index.php" method="get">
<span id="test"></span>
<input id="submit" type="submit" value="Submit" /><br>
</form>
<div id="chart_div" style="width: 100%; height: 100%;">
</div>
</body>
</html>
Any specific mistake I made?
Thanks in advance,
Best regards
Germinator
Try
var checkbox = $('<input type="checkbox" name="sensors[]"
value="'+obj[i][0]+'" />'+obj[i][1]);
A lot of possibilities. Make sure addSensorCheckboxes() is being called and that obj is populated. console.log() is the easiest way to figure out where the application is failing.
Fix your for-in loop as well....for (var i in obj) otherwise 'i' would be global.
Make sure var checkbox is a DOM element, HTML string, or jQuery object (as per the jquery documentation)

Categories