Doing an ajax call to a php page - php

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.

Related

How split comma in AJAX data

I use this script to send if a checkbox is checked or unchecked:
<script>
$(document).ready(function() {
$('.model').click(function() {
var formData = $('#myForm').serialize();
console.log('Posting the following: ', formData);
// send ajax
$.ajax({
url: 'av_check.php', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#myForm").serializeArray(), // post data || get data
success : function(result, status, xhr) {
alert("response was "+result);
// you can see the result from the console
// tab of the developer tools
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
</script>
And this is for my checkboxes:
<input id="model" name="model[]" class="model" type="checkbox" value="VARIABLE">
And my PHP:
echo json_encode($_POST['model']);
When multiple checkboxes are checked, then I get:
response was
08:15,08:30,08:45
(the values of the checkboxes are different times)
So far so good, but I want to handle this data on the PHP page.
So I tried $str_arr = explode (",", $_POST['model']); to split the values, but it doesn't seem to work.
So I searched for how to handle this data, but I can't seem to find it. Maybe I am not using the right terms, but is there anybody who knows how to handle this data?
I am entireley rewriting my response here. Lesson learned, don't try to help on NYE.
Update your HTML page to something like this
<html>
<body>
<form id="myForm">
<input id="model" name="model[]" class="model" type="checkbox" value="value1">
<input id="model1" name="model[]" class="model" type="checkbox" value="value2">
<input id="model2" name="model[]" class="model" type="checkbox" value="value3">
<input id="model3" name="model[]" class="model" type="checkbox" value="value4">
<input id="model4" name="model[]" class="model" type="checkbox" value="value5">
<button type="button" id="submit" onClick="submitForm()">Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script type="text/javascript">
function submitForm(){
var myData = $('#myForm').serialize();
$.ajax({
url: "av_check.php",
data: myData,
success: function (data) { // success callback function
console.log(data)
}
});
}
</script>
</body>
</html>
Then in your PHP, simply reference the $_GET['model'] variable
PHP file - av_check.php
<?php
print_r($_GET['model']);
?>
If you submit that, the console will output the value of the checked checkboxes.
Output:
Array
(
[0] => value1
[1] => value2
)

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

Laravel 5 get AJAX array POST in Controller

I have the following form:
<td>
<input type="text" name='name[]' class="form-control"/>
</td>
<td>
<input type="text" name='mail[]' class="form-control"/>
</td>
<td>
<select name="gender[]" class="form-control">
<option value="m">Male</option>
<option value="f">Female</option>
</select>
</td>
<td>
<input type="date" name='birth[]' class="form-control"/>
</td>
<td>
<input type="number" name='dni[]' class="form-control"/>
</td>
<td>
<input type="number" name='phone[]' class="form-control"/>
</td>
My ajax call when i try to submit my form
$('#form-reserve-list').on('submit', function(e) {
e.preventDefault();
var names = $("input[name='name[]']").serialize();
var mails = $("input[name='mail[]']").serialize();
var genders = $("select[name='gender[]']").serialize();
var births = $("input[name='birth[]']").serialize();
var dnis = $("input[name='dni[]']").serialize();
var phones = $("input[name='phone[]']").serialize();
var _token = $('input[name=_token]').val();
var est_id = $('input[name=est_id]').val();
var event_id = $('input[name=event_id]').val();
var url = 'http://localhost:82/boulevard/public/event/reserve/list';
$.ajax({
type: 'POST',
url: url,
data: {names:names, mails:mails, genders:genders, births:births, dnis:dnis, phones:phones, _token: _token, est_id:est_id, event_id:event_id},
cache: false,
success: function(data){
alert(data);
}
});
I want to receive this in my Controller and do a foreach or for loop and save it to my db, but the problem is when i try:
$names = Input::get('names'); //from ajax names
foreach($names as $name){
$name[];
//also tried $name[$key] after i added $key =>
}
am i doing something wrong? thank you for the help.
EDIT:
when i do alert($names) in ajax it shows as name%5B%D=carlos&name%5B%D=kevin is this the way its suppose to be? i also did dd($names); and also shows name%5B%D=carlos&name%5B%D=kevin but when i use foreach loop as mentioned above, the chrome console shows me internal error 500, am i suppose to use foreach?
EDIT2:
when i do dd(Input::all())
name%5B%5D=carlos&name%5B%5D=mendieta&name%5B%5D=cordero
how do i loop thru these?
//No need to serialize each field.
//You could do it like this:
$('#form-reserve-list').on('submit', function(e) {
e.preventDefault();
var formData = $(this).serialize();
var url = 'http://localhost:82/boulevard/public/event/reserve/list';
$.ajax({
type: "POST",
url: url,
data: formData,
dataType: "json",
success: function(data) {
},
error: function(){
alert('opps error occured');
}
});
});

trying to make ajax call work with php and mysql

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

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