I have the following issue.
I'm trying to send a AJAX call whenever a checkbox is checked. The value of the checkbox is send to my PHP file where the DB will be checked to get all the data of that value.
The problem is, I would like to show the data on the page but I don't know how.
Below is my code:
HTML:
<input type="checkbox" name="category[]" id="1" value="1" /> <label for="1">Administratieve Sector</label><br />
<input type="checkbox" name="category[]" id="2" value="2" /> <label for="2">Bouw Sector</label><br />
<input type="checkbox" name="category[]" id="3" value="3" /> <label for="3">Financiele Sector</label><br />
<input type="checkbox" name="category[]" id="4" value="4" /> <label for="4">Gezondheidszorg Sector</label><br />
<input type="checkbox" name="category[]" id="5" value="5" /> <label for="5">Horeca- en toerisme Sector</label><br />
JQuery:
function calculate() {
var arr = $.map($('input:checkbox:checked'), function(e, i) {
return +e.value;
});
$.ajax({
url: '/company/test.php',
data: {key: arr, i: 1},
type: 'post',
success: function(output) {
obj = JSON.parse(output);
console.log(obj);
// Don't know where to go next
}
});
}
calculate();
$("div[class='col-md-12'").delegate("input:checkbox[name='category[]']", 'click', calculate);
PHP:
<?php
require_once '../core/init.php';
$v = new Vacatures();
if(isset($_POST['key']) && isset($_POST['i']) && !empty($_POST['key'])) {
$key = $_POST['key'];
$i = $_POST['i'];
$vacs = $v->getFiltered($key, $i);
echo json_encode($v->data());
exit();
}
require_once VIEW_ROOT . '/company/test_view.php';
UPDATE (Content of obj)
[Object]0: Objectcategory: "1"company: "c1"content: "test"foto: "test"id: "2"region: ""title: "Test"__proto__: Objectlength: 1__proto__: Array[0]
Something like
$('body').append('<div><ul id="output"></ul></div>');
obj.data.forEach(function(x) {
$('#output').append("<li>"+x+"</li>");
});
Edit:
was some typo in there
forEach or $.each works only on json arrays, so you have to look whats inside your obj
I fixed it using the following AJAX call:
$.ajax({
url: '/company/test.php',
data: {key: arr, i: 1},
type: 'post',
dataType: "json",
success: function(output) {
$.each(output, function(key, element) {
$('#output').append("<li>"+element.title+"</li>");
});
}
});
Related
I don't know how to send text, checkbox, radio data and also image file at the same time using ajax jquery post (in order not to refresh the page).
Here are the codes I have.
index.php
<form action="save.php" method="POST">
Your Name : <input type="text" name="username" id="username">
<BR>
Your Sex :
<input type="radio" class="get_gender" name="gender" id="genderM" value="Male">Male
<input type="radio" class="get_gender" name="gender" id="genderF" value="Female">Female
<BR>
Your Hobbies :
<input type="checkbox" class="get_hobby" name="basket" id="basket" value="Basketball">Basketball
<input type="checkbox" class="get_hobby" name="foot" id="foot" value="Football">Football
<input type="checkbox" class="get_hobby" name="volley" id="volley" value="Volleyball">Volleyball
<BR>
Your Grade :
<select name="grade" id="grade">
<option value="1>1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<BR>
Upload Photo : <input type="file" name="image" id="image">
<BR>
<input type="button" name="save" id="save" value="Save" onclick="save()">
</form>
save.php
<?php
include "connection.php";
$usename = $_POST['username'];
$gender = $_POST['gender'];
$hobby = $_POST['hobby'];
$grade = $_POST['grade'];
$photo = $_FILES['image']['name'];
$sql = "insert into user
(username, gender, hobby, grade, photo)
values('$username','$gender','$hobby','$grade','$photo')";
$query = mysqli_query($con,$sql);
header("location: index.php");
?>
index.js
function save(){
var username = document.getElementById("username").value;
var grade = document.getElementById("grade").value;
var hobby = [];
$('.get_hobby').each(function(){
if($(this).is(":checked"))
{
hobby.push($(this).val());
}
});
hobby = hobby.toString();
var gender = [];
$('.get_gender').each(function(){
if($(this).is(":checked"))
{
gender.push($(this).val());
}
});
gender = gender.toString();
$.ajax({
type: "POST",
url: 'save.php',
data: {
username: username,
hobby: hobby,
hobby: hobby,
grade: grade
},
success: function(result){
}
});
}
Please help
You can simplify your save function - and send both form data and an image at the same time by using a FormData object:
function save_data() {
var formData = new FormData($('#userform')[0]);
$.ajax({
url: '/test13.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (response) {
alert(response);
}
});
}
Note you need a couple of other changes. The form needs an id attribute e.g.
<form id="userform">
You should change the name attributes of the hobbies to hobby[] i.e.
<input type="checkbox" class="get_hobby" name="hobby[]" id="basket" value="Basketball">Basketball
<input type="checkbox" class="get_hobby" name="hobby[]" id="foot" value="Football">Football
<input type="checkbox" class="get_hobby" name="hobby[]" id="volley" value="Volleyball">Volleyball
And you need to add
processData: false,
contentType: false,
To your ajax object.
In your PHP code, you would need to assemble $hobby from the raw form values:
$hobby = implode(',', $_POST['hobby']);
and you should include a check for $_POST['gender'] being set:
$gender = $_POST['gender'] ?? '';
I needed to change the name of your function as save was causing conflicts. I renamed it to save_data. You may not find this is an issue.
Hello in my laravel eshop i have list of currency value in checkbox . When the checkbox get selected my page will get reloaded and update the currency value, But checkbox selection is missing after page reload, Any idea .
<script>
$(document).ready(function (){
$(function() {
// Currency change in checkout
$('#usd').on('ifChecked', function() {
var currency = $("input[name='currency']:checked").val();
$.ajax({
type: 'POST',
url: "{{URL::to('/')}}/cart/setcurrency",
data: {'currency':currency},
dataType: 'json',
success: function(data) {
window.location.reload();
$('input#usd').html("input[name='currency']:checked");
}
})
})
$('#aed').on('ifChecked', function() {
$("#tot_val").css("font-size", "14px");
$("#tot_text").css("font-size", "14px");
var currency = $("input[name='currency']:checked").val();
$.ajax({
type: 'POST',
url: "{{URL::to('/')}}/cart/setcurrency",
data: {'currency':currency},
dataType: 'json',
success: function(data) {
window.location.reload();
$('#aed').html("{{Session::get('currency')}}");
}
})
})
$("input[name='currency']:checked").bind( "change", function(event, ui) {
console.log('Lang: '+$(this).val());
})
</script>
<div class="cart_currency">
<form action="#">
{{Session::get('currency')}}
<p>CURRENCY</p>
<input type="radio" name="currency" value="USD" id="usd">USD
<input type="radio" name="currency" value="AED" id="aed">AED
<a href="{{URL::to('/')}}/cart/shipping">
<input type="button" name="currency_sub" value="CONTINUE" class="currency_submit">
</a>
</form>
</div>
public function postSetcurrency(){
$data = Input::all();
Session::set('currency',$data['currency']);
return Response::json('success');
}
#if (Session::has('currency'))
$value = Session::get('currency');
#if(strcmp($value,"USD") == 0)
<input type="radio" name="currency" value="USD" checked id="usd">USD
<input type="radio" name="currency" value="AED" id="aed">AED
#else if(strcmp($value,"AED") == 0)
<input type="radio" name="currency" value="USD" id="usd">USD
<input type="radio" name="currency" value="AED" checked id="aed">AED
#endif
#else
<input type="radio" name="currency" value="USD" id="usd">USD
<input type="radio" name="currency" value="AED" id="aed">AED
#endif
I haven't used Laravel before, but just looking at a few off-site examples, you could try this. It should replace your current radio buttons.
You could save the states of the checkbox and pass them as POST by php or using javascript to set local storage
https://developer.mozilla.org/es/docs/Web/API/Storage/setItem
javascript:
//set the checkbox state
localStorage.setItem('checkbox_one','true');
localStorage.setItem('checkbox_one','false');
//on page load
if(localStorage.getItem('checkbox_one') == 'true'){
//checkbox was checked
}else{
//checkbox checked not true
}
I have an HTML form with text, radio and checkbox inputs. When I submit it with AJAX, I only get the last checkbox value in array.
My HTML file:
<form class="ajaxonsubmit" action="process.php" method="post">
<label>Name</label><input type="text" name="name">
<label>Father's Name</label><input type="text" name="father_name">
<label>Gender</label>
<input type="radio" value="1" name="gender">Male <br>
<input type="radio" value="2" name="gender">Female <br>
<label>Options</label>
<select name="campus">
<option value="1">Option1 </option>
<option value="2">Option2 </option>
</select>
<label>Check List</label>
<input type="checkbox" name="check[]" value="1">
<input type="checkbox" name="check[]" value="2">
<input type="checkbox" name="check[]" value="3">
<button name="submit" type="submit">Submit</button>
My JS file.
$('.ajaxonsubmit').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(data) {
$("#wrap").html(data);
}
});
return false;
});
I am using var_dump($_POST); function in process.php to check the array and I get ["check"]=> array(1) { [0]=> string(1) "3" }
You can serialize the form data , and access in PHP side
$('.ajaxonsubmit').on('submit', function(e) {
e.preventdefault();
$.ajax({
url: url,
type: type,
data: $(this).serialize(),
success: function(data) {
$("#wrap").html(data);
}
});
});
in PHP
print_r($_POST);
Add class="checkBoxClass" to your checkbox,
Then in your js, just add the following code to add the data into your chkArray
var chkArray = [];
$(".checkBoxClass:checked").each(function() {
chkArray.push($(this).val());
});
Finally append the array to the data you are posting
Cheers.
I have the following set up for my ajax call but it is not working when I click on a star (this is a star rating), Although if i access the ajax.php directly it inserts, but the ajax call is not happening.
html in php file
echo '<table>
<tr>
<td style="padding:10px;">
<input type="hidden" name="userID" value="'.$user_id.'">
<span style="font-size: 20px; vertical-align:top;">Comments</span>
</td>
<td style="padding:10px;">
<textarea name="comments" cols="60" rows="2"></textarea>
</td>
<td>
<div>
<input name="star1000" value "1" type="radio" class="star"/>
<input name="star1000" value="2" type="radio" class="star"/>
<input name="star1000" value="3" type="radio" class="star"/>
<input name="star1000" value="4" type="radio" class="star"/>
<input name="star1000" value="5" type="radio" class="star"/>
</div>
</td>
<tr>
</table>';
JS - being used to send the values
<script>
$('.star').rating({
callback: function(value, link) {
var name = $(this).attr('name');
var userID = $(this).closest('td').find('input[name="userID"]').val();
var comments = $(this).closest('td').find('textarea[name="comments"]').val();
$.ajax({
url: "http://localhost/mywebsite/ajax.php",
type: "POST",
data: {
name: name,
value: value,
userID: userID,
comments: comments
},
cache: false,
success: function(response) {
try {
console.log(response);
} catch (err) {
alert(response);
}
}
});
}
});
</script>
My ajax.php located at http://localhost/mywebsite/ajax.php
<?php
extract($_POST);
$rate_val = $_POST['value'];
$user_id = $_POST['userID'];
$comments = $_POST['comments'];
$insert_q = "INSERT INTO ratings (rate_comments, rate_num, option_id, rate_date,user_id)
values ('$comments','$rate_val','1',now(),'$user_id')";
include 'opendbconn.php';
if(!($result = mysql_query($insert_q, $database)))
{
print("Could not execute query!<br/>");
die(mysql_error()."</div>
</div>
</body>
</html>");
}
include 'closedbcon.php';
?>
You have to bind the event click with your function .rating() so javascript knows that it has to execute the function .rating() when ".star" is clicked.
You could do it like this:
$(document).ready(function(){
//other javascript code...
$('.star').bind('click',function(){
//your rating function
});
});
I have this star rating, I implemented from jQuery and I need to save the comments, the user id and the value of the star clicked. What I do not know is how to pass that through the ajax call and what the PHP should have at the least to process the call? Here is my code
stars code - as you can see it has a comments box , the stars with star value and the user id is stored in a variable called
$user_id
Here is the code
<tr>
<td style="padding:10px;">
<span style="font-size: 20px; vertical-align:top;">Comments</span>
</td>
<td style="padding:10px;">
<textarea name="comments1" cols="60" rows="2"></textarea>
</td>
<td>
<div>
<input name="star1" value "1" type="radio" class="star"/>
<input name="star1" value="2" type="radio" class="star"/>
<input name="star1" value="3" type="radio" class="star"/>
<input name="star1" value="4" type="radio" class="star"/>
<input name="star1" value="5" type="radio" class="star"/>
</div>
</td>
<tr>
The ajax call - This is the attempted call to the page where I am sending the request, but how can I include the comments and user id on this call?
$('.star').rating({
callback: function(value, link) {
var name = $(this).attr('name');
$.ajax({
url: "ajax.php",
data: "name=" + name + "&value=" + value,
cache: false,
success: function(response) {
try {
console.log(response);
} catch (err) {
alert(response);
}
}
});
}
});
Now, ajax.php has variables $passed_user_id, $passed_comments, $passed_ratingval. How am I retrieving these values when the call is triggered in php? something like
$passed_comments = //get the value being passed from ajax call
$passed_ratingval = //get the value being passed for the rating value
$passed_user_id = //get the value being passed for the user_id`
I do have all set up, the insert query, connection everything works. I'm just not sure how to make this work with the ajax call.
Kinda hacky, but this will work for you. It also will allow for multiple ratings on one page (which I assume you might be doing considering the TR).
HTML:
<tr>
<td style="padding:10px;">
<input type="hidden" name="userID" value="<?php echo $user_id ?>">
<span style="font-size: 20px; vertical-align:top;">Comments</span>
</td>
<td style="padding:10px;">
<textarea name="comments" cols="60" rows="2"></textarea>
</td>
<td>
<div>
<input name="star1" value "1" type="radio" class="star"/>
<input name="star1" value="2" type="radio" class="star"/>
<input name="star1" value="3" type="radio" class="star"/>
<input name="star1" value="4" type="radio" class="star"/>
<input name="star1" value="5" type="radio" class="star"/>
</div>
</td>
<tr>
JS:
$('.star').rating({
callback: function(value, link) {
var name = $(this).attr('name');
var userID = $(this).closest('tr').find('input[name="userID"]').val();
var comments = $(this).closest('tr').find('textarea[name="comments"]').val();
$.ajax({
url: "ajax.php",
data: "name=" + name + "&value=" + value + "&userID=" + userID + "&comments=" + comments,
cache: false,
success: function(response) {
try {
console.log(response);
} catch (err) {
alert(response);
}
}
});
}
});
Also, if you use POST instead of GET, you can format your ajax call a bit nicer like below. Remember to use $_POST[] in your ajax.php file.
$('.star').rating({
callback: function(value, link) {
var name = $(this).attr('name');
var userID = $(this).closest('tr').find('input[name="userID"]').val();
var comments = $(this).closest('tr').find('textarea[name="comments"]').val();
$.ajax({
url: "ajax.php",
type: "POST",
data: {
name: name,
value: value,
userID: userID,
comments: comments
},
cache: false,
success: function(response) {
try {
console.log(response);
} catch (err) {
alert(response);
}
}
});
}
});
Here is example code of mine, which I use on one project:
jQuery.post("load.php", {
op_type : opType,
xor : xor.toString(),
or : or.toString(),
and : and.toString(),
from : seeds.toString(),
last_id : jQuery("input[type=hidden]:last").val(),
last_update : last_update_time
}, function(data) {
var json = jQuery.parseJSON(data);
if (json.list.length > 0) {
last_update_time = Math.floor(new Date().getTime() / 1000);
jQuery("div#list_content ul.no-list").append(json.list);
}
});
And in PHP to receive data I use:
$_POST['op_type']
and in this manner I get other variables too.
To return something I do like this:
echo json_encode(array("list"=>$html));
So afyer jQuery parses JSON it can get access to $html variable via list property.
So what you need is to specify request type in jQuery and get that request type in PHP. Sending data in JSON is one of the options. jQuery and PHP also support XML, but I didn't worked with it.