trying to make ajax call work with php and mysql - php

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

Related

Can't Send while looped input field data from ajax to php

I have two input fields with same class name and the same data.
Here is my while loop generated input field
<tr>
<td>
<input onchange="mySubmit(this.form)" class="ot_value" name="ot_value" type="text" value="10">
<input type="hidden" name="ot_id" class="ot_id" value="1">
</td>
</tr>
<tr>
<td>
<input onchange="mySubmit(this.form)" class="ot_value" name="ot_value" type="text" value="11">
<input type="hidden" name="ot_id" class="ot_id" value="2">
</td>
</tr>
I was trying to send data from ajax to php when user change any value.
Here is my jquery
function mySubmit(theForm) {
var ot_value= $(".ot_value").val();
var ot_id= $(".ot_id").val();
$.ajax({
type:"post",
url:"../apis/update_ot.php",
data: "ot_value=" + ot_value+ "&ot_id=" + ot_id,
success:function(data){
alert(data);
}
});
}
I was able to send data when user is changing any input field data. But the problem is that, it's taking only the 1st row data.
How can I get the exact data, that what user are changing in input field.
You have jQuery, use it
remove onchange="mySubmit(this.form)" from the field and do
$(function() {
$(".ot_value").on("change", function() {
const ot_value = $(this).val();
const ot_id = $(this).next(".ot_id").val();
console.log("about to submit",ot_value,ot_id)
$.ajax({
type: "post",
url: "../apis/update_ot.php",
data: "ot_value=" + ot_value + "&ot_id=" + ot_id,
success: function(data) {
alert(data);
}
});
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>
<input class="ot_value" name="ot_value" type="text" value="10">
<input type="hidden" name="ot_id" class="ot_id" value="1">
</td>
</tr>
<tr>
<td>
<input class="ot_value" name="ot_value" type="text" value="11">
<input type="hidden" name="ot_id" class="ot_id" value="2">
</td>
</tr>
</tbody>
</table>

How to Send Text and Image File Data at The Same Time to MySQL Database Without Refreshing The Page

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.

Send array data through AJAX

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

Doing an ajax call to a php page

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.

why is my ajax unable to get the currently typed string in the input form?

I have a simple form, then I placed some data from the table to each of the input forms value attribute. now my problem is, whenever i typed something new to the input form, to update the data, it's unable to pick up the currently typed string, am not sure how to solve this, because I think it is picking up the value echoed out instead of the currently typed string when on this update page,
here's my front-end
<fieldset id="personaldetails">
<legend>Personal Details</legend>
Resume Title: <input type="text" name="resumetitle" id="resumetitle" value="<?php echo $v['ResumeTitle']; ?>" size="50" maxlength="50" /><br />
Name: <input type="text" name="cvname" id="cvname" size="30" maxlength="30" value="<?php echo $v['Name']; ?>" /><br />
DOB: <input type="text" id="datepicker" name="dob" value="<?php $date = new DateTime($v['DOB']); echo $date->format('m/d/Y'); ?>" /><br />
Gender: <input type="radio" name="gender" id="gender-male" value="1" <?php if($v['Gender'] == 1){ echo "checked"; } ?>/> <b>Male</b> |
<input type="radio" name="gender" id="gender-female" value="0" <?php if($v['Gender'] == 0){ echo "checked"; } ?>/> <b>Female</b><br /><br />
<input type="hidden" name="cvid" id="cvid" value="<?php echo $v['ResumeID']; ?>" />
<button name="pdetails" id="pdetails">Update</button>
</fieldset><br /><br />
//here's my js
$(document).ready(function(){
var resumetitle = $('#resumetitle').val();
var cvid = $('input[type="hidden"]').val();
var name = $('#cvname').val();
var dob = $('#datepicker').val();
var gender = $('input[name="gender"]:checked').val();
$('button#pdetails').click(function(){
$.ajax({
type: "POST",
url: "classes/ajax.resumeupdate.php",
data: "resumeid="+cvid+"&resumetitle="+resumetitle+"&name="+name+"&dob="+dob+"&gender="+gender,
success: function(){
//window.location = "resumeview.php?cvid="+cvid;
},
});
});
});
//here's my php code
require 'class.resume.php';
$db = new Resume();
if(isset($_POST['resumetitle']) || isset($_POST['name']) || isset($_POST['dob']) ||
isset($_POST['gender']) || isset($_POST['cvid'])){
$result = $db->updatepdetails($_POST['resumetitle'],$_POST['name'],$_POST['dob'],$_POST['gender'],$_POST['cvid']);
if($result){
echo "success!";
} else {
echo "failed! ".$db->error;
}
}
You are only reading the values on document ready, move that code into the click event:
$(document).ready(function(){
$('button#pdetails').click(function(){
var resumetitle = $('#resumetitle').val();
var cvid = $('input[type="hidden"]').val();
var name = $('#cvname').val();
var dob = $('#datepicker').val();
var gender = $('input[name="gender"]:checked').val();
$.ajax({
type: "POST",
url: "classes/ajax.resumeupdate.php",
data: "resumeid="+cvid+"&resumetitle="+resumetitle+"&name="+name+"&dob="+dob+"&gender="+gender,
success: function(){
//window.location = "resumeview.php?cvid="+cvid;
},
});
});
});
Your javascript is resolving the form values just once (on page load), so if you enter something after the page has loaded, the variables don't change.
You can simply calculate the values inside the Ajax callback instead. But what you really should do is use jQuery's $.serialize() function, which creates a standard a=1&b=2&c=3 querystring including the (properly escaped) form data:
$(function(){
$('button#pdetails').click(function(){
$.ajax({
type: "POST",
url: "classes/ajax.resumeupdate.php",
data: $('form').serialize(),
success: function(){
//window.location = "resumeview.php?cvid="+cvid;
}
});
});
});
Also note that you had a trailing comma after the success function - this will fail in IE so I've changed that as well.

Categories