I'm trying to pass a checkbox array into an AJAX call for a search form im working on:
HTML:
<form id="searchForm">
<input type="checkbox" class="typesSearch" name="types[]" value="Fundraiser" checked /> Fundraiser<br>
<input type="checkbox" class="typesSearch" name="types[]" value="Conference" checked /> Conference<br>
</form>
JavaScript:
var types = [];
var eventTypes = document.forms['searchForm'].elements[ 'types[]' ];
for (var i=0, len=eventTypes.length; i<len; i++) {
if (eventTypes[i].checked ) {
types.push($(eventTypes[i]).val());
}
}
$.ajax({
url: "https://www.example.com/search.php",
method: "post",
data:{
eventname: eventname,
types: types
},
dataType:"text",
success:function(data)
{
$('#eventsList').html(data);
$('#eventsList').slick($opts);
}
});
PHP:
$event_types = $_POST['types'];
The types array is fine on the javascript side, its when it hits the PHP side that $_POST['types'] is read as being empty.
Why is it that $_POST['types'] is read as empty? Is there something in the AJAX call where I need to define that I'm passing in an array instead of a string?
Try to use the following at "data":
$.ajax({
url: "https://www.example.com/search.php",
method: "POST",
data:{
eventname: eventname,
types: JSON.stringify(types)
},
dataType:"text",
success:function(data)
{
$('#eventsList').html(data);
$('#eventsList').slick($opts);
}
});
With this, the types is a string and you need to parse it to array object on PHP side.
On server side, you can use the following code to get the array. The $item[0]
$event_types = $_POST['types'];
$item = (json_decode(stripslashes($event_types)));
You need to serialize your array in order to receive it in $_POST, so your ajax should look like:
$.ajax({
url: "https://www.example.com/search.php",
method: "post",
data:{
eventname: eventname,
types: JSON.stringify(types) //serializied types[]
},
dataType:"text",
success:function(data)
{
$('#eventsList').html(data);
$('#eventsList').slick($opts);
}
});
You might want to try this solution too:
JS:
data: { typesArray: types }
PHP:
$types = $_REQUEST['typesArray'];
Related
I'm trying to make it so that when my ajax call is returned with an object/array, I can match up the results to checkboxes so that if there is a match I auto check the boxes
Here are my checkboxes
<input type="checkbox" name='Magazine' data-md-icheck />
<input type="checkbox" name='Website' data-md-icheck />
<input type="checkbox" name='Advertisement' data-md-icheck />
Now my ajax call is successful
I get back:
0: {}
type: "Magazine"
1: {}
type: "Website"
so in my ajax success, what I would like to do is take any result in that object, whether just one or all 3, and if the type matches the 'name' of the checkbox I want to check that box.
Here is my function that makes the successful ajax call. I just can't figure out a way to loop the return that I get so that I can match up any result that comes through
function getDetails(ID) {
console.log(ID);
$.ajax({
url: "/details",
data: {ID:ID},
_token: "{{ csrf_token() }}",
type: "POST",
success: function (data) {
},
});
};
So in this case, how would I modify my ajax success to check the magazine and website boxes?
Here is a pure JS and simple solution to this:-
// Assuming you get the response as an array of objects, which has a key as type
success: function (data) {
data.forEach(obj => {
let ele = document.getElementsByName(obj.type)[0];
if(ele) {
ele.checked = true;
}
});
}
This is how I would tackle it:
function getDetails(ID) {
console.log(ID);
$.ajax({
url: "/details",
data: {ID:ID},
_token: "{{ csrf_token() }}",
type: "POST",
success: function (data) {
for(var i=0;i<data.length;i++){
var item = data[i].type;
var checkbox = $('input[name="'+item+'"]);
if (checkbox.length){
checkbox.prop('checked', true);
}
}
},
});
};
Assume the result is pure text exactly the same as you provided (ES6+)
let a = 'result...'
['Magazine', 'Website', 'Advertisement'].filter(item => a.indexOf(item) != -1).forEach(item => {
let inputs = document.getElementsByName(item)
if (inputs.length > 0)
inputs[0].checked = true
})
My form contains hidden input looping.
in my case, i declare the hidden input in ajax data manually without looping.
so how to loop them in ajax data?
here's my form script
<form method="POST" name="myform">
<?php for($i=1;$i<=5;$i++) { ?>
<input type="hidden" name="data<?php echo $i; ?>" value="data<?php echo $i; ?>">
<?php } ?>
<input type='button' name='submitData' value='Submit' onClick='submitData();'>
</form>
here's my Ajax script
function submitData() {
var form = document.myform;
$.ajax({
url: 'process.php',
type: 'post',
data: {
data1 : form["data1"].value,
data2 : form["data2"].value,
data3 : form["data3"].value,
data4 : form["data4"].value,
data5 : form["data5"].value
},
success: function (result) {
console.log(result);
},
error: function () {
console.log("error");
}
});
}
Your hidden inputs have name and values,
use .serialize()
Encode a set of form elements as a string for submission
data : $('form[name=myform]').serialize()
This will return name=value pairs.
If you need {name:value}, use .each()
var formData = {}
$('form :input:hidden[name^="data"]').each(function(){
formData[this.name] = this.value;
});
And in ajax,
data : formData ,
Demo
If you're posting the whole form, you can use jQuery's .serialize() directly in your request:
$.ajax({
url: 'process.php',
type: 'post',
data: $('#myform').serialize(),
...
Also, a good way to do it is to convert the string to JSON object, and in PHP convert the string in an array:
var dataJSON = JSON.stringify({..Your form obj...});
$.ajax({
url: 'process.php',
type: 'post',
data: dataJSON,
success: function (result) {
console.log(result);
},
error: function () {
console.log("error");
}
});
process.php
$data = json_decode($_POST["data"]);
print_r($data);
I am trying to make an autocomplete widget that will display item's codes returned from a database.
I have successfully made it so my database will return the appropriate JSON response.
The problem now is I don't know why the drop-down list doesn't show up.
Here's the code down below:
<input type="text" id="search" class="form-control" placeholder="">
<form action="post" action="" id="spareParts" class="spareparts">
</form>
$('#search').keyup(function(event) {
var search = $(this).val();
if($.trim(search).length){
var arr = [];
$.ajax({
url: 'get_spareparts',
type: 'POST',
dataType: 'JSON',
data: {item: search},
success: function (data) {
arr = $.parseJSON( data );
console.log(arr);// CONSOLE.LOG WORKS WELL
//[Object { id="1", value="25.00", desc="Fuel pump", more...}]
// AUTOCOMPLETE DOESN'T WORK
$('#spareParts').autocomplete({
minLength:0,
source: arr
});
}
});
}
});
The autocomplete with AJAX loaded data should be configured differently. source property can be a function which accepts a callback parameter. You should feed this callback with data loaded from server.
Also you don't need to bind keyup event manually. Your code will become:
$('#search').autocomplete({
minLength: 0,
source: function(request, response) {
$.ajax({
url: 'get_spareparts',
type: 'POST',
dataType: 'JSON',
data: {item: request.term}
}).done(function(data) {
response(data.map(function(el) {
return {
value: el.value,
label: el.desc
};
}))
});
}
});
I have an MVC application with a controller named Angular (I use AngularJS as well), which has an action called GetQuestion. That action returns a JsonResult which looks like this (grabbed from Chrome):
{"game":{"Title":"Diablo III","ImgPaths":["d31.jpg","d32.jpg"]},"Answers":["Diablo III","World of Tanks","Need for Speed"]}
My JS function is like this:
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { alert(data); })
});
But instead of the Json I wrote above, alert window only says [object Object]
Update
Ok, that was fixed, thaks. However as you may suspect, my goal is not to present this data in alert box, but use it somehow. So here's my controller in Angular
function QuestionCtrl($scope) {
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: function (data) {
$scope.answers = JSON.stringify(data.Answers);
$scope.imgPath = JSON.stringify(data.game.ImgPaths[0]);
}
});
}
And then the view:
<div ng-controller="QuestionCtrl">
<img class="quizImage" src="~/Gallery/{{imgPath}}"/>
#using (Html.BeginForm("Answer", "Angular", FormMethod.Post))
{
<p ng-repeat="answer in answers"><input type="radio" name="game" value="{{answer}}"/> {{answer}}</p>
<p><input type="submit" value="Answer"/></p>
}
</div>
And I don't have neither image or the questions. If I hardcode them in controller then it's ok.
An alert will show that, i would suggest using console.log(data)
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { console.log(data); })
});
or as the comments states:
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { alert(JSON.stringify(data)); })
});
I resolved my second problem like this:
function QuestionCtrl($scope, $http) {
$http.post('/Angular/GetQuestion',null).success(function(data) {
$scope.answers = data.Answers;
$scope.imgPath = data.game.ImgPaths[0];
//console.log($scope.answers);
//console.log($scope.imgPath);
});
}
Note that it's AngularJS.
The reason it's happening is because JSON is an Object in JavaScript. When you type
alert(data);
It will attempt to cast the object to a string which in this case will only output that fact that it's an Object.
To view the contents of an object you can write a simple function to use with an alert or console.log.
function outputProperties(anObject) {
var props = '';
for (var prop in anObject) {
props += '\n' + prop + ' value: ' + anObject[prop];
}
return props;
}
And use it like this
alert(outputProperties(data));
For starters... when ever you are dynamically building the src url for an image (using the {{expression}} syntax from Angular) you need to not use the "src" attribute and use the "ng-src" angular directive. It allows angular time to process your url before the image is loaded.
I am have the below checkboxes and I want to pass the checked values to an array so that I can do an ajax post. However, I am hitting an error and I am not sure where I went wrong...
How do I pass the values into the array and how do I retrieve them?
HTML
<input type="checkbox" name="newCheckboxes" value="1" />
<input type="checkbox" name="newCheckboxes" value="2" />
<input type="checkbox" name="newCheckboxes" value="3" />
Script (not working)
var allFields = $( [] );
$("#newCheckboxes:checked").each(function() {
allFields.add( $(this).val() );
});
$.ajax(
{
type:"POST",
url: "PostedHere",
data:{
checkedValues: allFields
}
});
You only need:
$.ajax({
type:"POST",
url: "PostedHere",
data: { checkedValues: $("#newCheckboxes:checked").serialize() }
});
// checkedValues: "newCheckboxes=1&newCheckboxes=2" etc..
Using karim79 code idea:
$.post('URL', $('[name="newCheckboxes"]:checked').serializeArray(), function(data){
//data
});
What I prefer to do is: Create a new Object and add all checkboxes 'Value' and 'Ischecked' to an array (access), then pass it to page by Json:
$(document).ready(function () {
$("#btnSave").click(function () {
event.preventDefault();
$("#newCheckboxes").each(function () {
var data= new Object()
var access = new Array();
access.ChValue = $(this).attr("value");
if ($(this).attr("checked") == "checked") access.ChChecked = true;
data.push(access);
});
$.ajax({
type: 'POST',
url: '#Url.Content("~/URLofPage")',
data: $.json.encode(data),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
});
});
please do not forgot to add Json reference to your page:
<script src="../../../Scripts/jquery.json.js" type="text/javascript"></script>