I can best explain my problem by showing the code first. I am working on a project with my friend (Rent a car project), so the code isn't completely mine. I searched (and used) some of the answers i found on similar questions, but none solved my problem. All of the pages here will be used by administrator.
1st
client_requests.php
This page contains javascript function called sureToApprove with which i have a problem : in the url the car variable is undefined (&car=undefined), while id has a value (it works). Also, this page contains some of the data from database.
<script type="text/javascript">
function sureToApprove(id, car) {
if (confirm("Da li ste sigurni?")) {
window.location.href = "approve.php?id=" + id + "&car=" + car;
}
}
function deleteRequest(id){
if (confirm("Da li ste sigurni?")) {
window.location.href = 'delete_request.php?id=' + id;
}
}
</script>
<script>
$(document).ready(function () {
load_data();
function load_data(query) {
$.ajax({
url: "fetch_requests.php",
method: "POST",
data: { query: query },
success: function (data) {
$('#result').html(data);
}
});
}
$('#search_text').keyup(function () {
var search = $(this).val();
if (search != '') {
load_data(search);
}
else {
load_data();
}
});
});
</script>
2nd page is fetch_requests.php which contains a query which will be shown on 1st page (client_requests.php). Query and the rest of the code works perfectly.
<tr>
<td>'.$row["fname"].'</td>
<td>'.$row["lname"].'</td>
<td>'.$row["email"].'</td>
<td>'.$row["phone"].'</td>
<td>'.$row["car_name"].'</td>
<td>'.$row["mpesa"].'</td>
<td>'.$row["status"].'</td>
<td>
IzbriĆĄi
Approve
</td>
</tr>
When the link approve is clicked, it redirects to 3rd page (approve.php) in which the data in database is regulated. The url looks something like this
http://localhost/Rent-a-car/admin/approve.php?id=7&car=undefined
I need the car variable for regulating the database, and i can't find out why it is not picking up the value instead is undefined. Thank you in advance.
Related
I have an AJAX post method that works in two places both on "Ladder" page, but not another, a "matches" page. This method sets posts the "player ID" which php picks up and sets a session variable
$("form .singles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Working page form:
<form><button type='submit' id='playerInfo' class='singles-player-name' name='viewPlayer' value='",$sglsPlayerID,"'>", $curSGLSRankLName, ", ", $curSGLSRankFName, "</button></form>
Sets session variable
if (!empty($_POST['viewPlayerID'])){
$viewPlayer = isset($_POST['viewPlayerID']) ? $_POST['viewPlayerID'] : 'No data found';
$viewPlayerSql = "SELECT * FROM `PLAYERS` WHERE `ID` LIKE '".$viewPlayer."'";
$viewPlayerQuery = #$conn->query($viewPlayerSql);
$viewPlayerRow=mysqli_fetch_assoc($viewPlayerQuery);
$_SESSION['playerID'] = $viewPlayerRow["ID"];
echo "", $_SESSION['playerID'],"";}
Second working version that lives on the same page as the first but is for doubles players:
$("form .doubles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Form for that ajax method:
<form><button type='submit' id='playerInfo' class='doubles-player-name' name='viewPlayer' value='",$dblsPlayerID,"'>", $curDBLSRankLName, ", ", $curDBLSRankFName, "</button></form>
Then on complete, the ajax methods redirect to the player page and pulls up that players info on that page (ex. https://urlexample.com/Player). This part, from this point-up, works! However, I have another page, the "Matches" page, where I want it to do the same exact thing, and set that session variable, then redirect to the player page, so I have this method below. But for some reason, this one does not work:
$("form .singlesMatch-player1-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
console.log(data);
window.location.href = "Player";
});
});
Not working form:
<form><button type='submit' id='playerInfo' class='singlesMatch-player1-name' name='viewPlayer' value='",$sglsPlayer1ID,"'>", $P1LN, ", ", $P1FN, "</button></form>
For some reason, all this second method does is post it to the URL (ex. https://urlexample.com/WeeklyMatchUps?viewPlayer=1) instead of setting the session variable and redirecting to the player page (ex. https://urlexample.com/Player). All thats different between the 2 is the class name of the button.
$sglsPlayer1ID should probably be $sglsPlayerID.
Also, try adding a success and error condition to your AJAX conditions instead of just using a done operator. This will allow you to dump helpful error codes on a failure to better resolve these kinds of issues in the future.
I had a function being called on the page that was commented out causing an error before jQuery was added in a script at the bottom of the page. removing that function from being called fixed the issue.
S/O to #line88 for the assistance!
I'll preface this with I'm still new to JavaScript. So problem is in a larger application, our controller is passing in a list of information to the view where certain JavaScript functions rely on certain ViewModel properties. I've written a simple application to hopefully illustrate what I'm getting at.
Below is a sample controller that's passing in List to the Index page:
public ActionResult Index() {
List<int> activeIds = new List<int>();
SqlConnection sqlConn = new SqlConnection(connection_String);
sqlConn.Open();
string sqlStr = "SELECT * FROM dbo.[JS-Test] WHERE Active = 1";
SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlConn);
SqlDataReader sqlDR = sqlCmd.ExecuteReader();
if(sqlDR.HasRows) {
while (sqlDR.Read()) {
activeIds.Add((int)sqlDR["ID"]);
}
}
sqlDR.Close();
sqlCmd.Dispose();
sqlConn.Close();
return View(activeIds);
}
This returns the current "active" items in the database. The (rough) view is as follows...
#model List<int>
#{
ViewBag.Title = "Index";
}
<p>Current Recognized Count: #Model.Count() </p>
Print
<script>
$(document).ready(function () {
$('#printBtn').click(function () {
var numberOfActiveIds = #Model.Count();
$.ajax({
type: "POST",
url: "/Home/PostResults",
data: { ids: numberOfActiveIds},
success: function (results) {
if(results == "Success") {
window.location.href = '/Home/Results';
}
}
});
});
});
</script>
The issue is getting the current number of active items from the database when the button is clicked. Let's say that the user remains idle on the page after it loads for a few minutes. When their page originally loaded, the model returned 5 items listed as active... but while they've been waiting 3 additional items were switched to active in the database for a total of 8. However, when the user finally clicks the button it'll submit 5 items instead of the current 8.
I'm unable to run the query to get the current number of active items in the "/Home/PostResults" ActionResult due to the nature of how the larger application is set up. Is there a way I could refresh the page (getting the updated model) before the rest of the function carries out using values of the refreshed model?
If you have any additional questions, please let me know and I will gladly comply. I've looked at other questions and answers on SO but I haven't found one that quite works for my situation. Thanks!
Edit #1
So, I've added this function to the Home controller which just returns the list count as Json.
public ActionResult GetIds(){
List<int> activeIds = new List<int>();
SqlConnection sqlConn = new SqlConnection(connection_String);
sqlConn.Open();
string sqlStr = "SELECT * FROM dbo.[JS-Test] WHERE Active = 1";
SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlConn);
SqlDataReader sqlDR = sqlCmd.ExecuteReader();
if (sqlDR.HasRows) {
while (sqlDR.Read()) {
activeIds.Add((int)sqlDR["ID"]);
}
}
sqlDR.Close();
sqlCmd.Dispose();
sqlConn.Close();
return Json(activeIds.Count());
}
The view script now looks like this...
<script>
$(document).ready(function () {
$('#printBtn').click(function () {
var numberOfActiveIds = #Model.Count();
$.ajax({
type: "GET",
url: "/Home/GetIds",
success: function(response) {
numberOfActiveIds = response;
$.ajax({
type: "POST",
url: "/Home/PostResults",
data: { ids: numberOfActiveIds},
success: function (results) {
if(results == "Success") {
window.location.href = '/Home/Results';
}
}
});
}
});
});
});
</script>
I'm currently getting the following error...
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Edit #2
I had to set the JsonRequestBehavior to AllowGet for it to work properly. Thanks again, everyone!
gforce301 mentioned to GET the current actives via an ajax call to an additional, separate method making the query to the database and THEN ajax post the returned "actives". Is that possible?
Yes this is possible. That's why I mentioned it. Irregardless of other peoples opinions on how they think you should do this, I understand that you may be limited on why you can't do it their way even if they don't.
The code below is a restructuring of your code. It chains 2 ajax calls together, with the second one depending on the success of the first. Notice the comment block in the success handler of the first ajax call. Since I don't know what the response will be, I can't fill in the part on how to use it. This accomplishes your goal of having the user only make a single button click.
<script>
$(document).ready(function () {
$('#printBtn').click(function () {
var numberOfActiveIds = #Model.Count();
$.ajax({
type: 'GET',
url: '/path/to/get/activeIds',
success: function(response) {
/*
Since I don't know the structure of response
I have to just explain.
use response to populate numberOfActiveIds
now we just make our post ajax request.
*/
$.ajax({
type: "POST",
url: "/Home/PostResults",
data: { ids: numberOfActiveIds},
success: function (results) {
if(results == "Success") {
window.location.href = '/Home/Results';
}
}
});
}
});
});
});
</script>
I can give you an idea, i hope it can help,
run another ajax 1st on btnclick to get the data(or datat count) again, if the record count is greater then current then update the view and don't PostResults and if its same then just PostResults
on ajax success you can reload the data or view
and on failure(when no new record) just do PostResults
I'm head below water on this, using Laravel I have a search page of which ajax calls a url and updates the html for filter by the way of html links which contain get vars ($(this).attr('href'); which contains ?var=test sent via ajax) to return filtered results. As ajax this doesn't update the url I'm using history.replaceState to update that.
Now here's my issue, the links which be shown as buttons (using BS) - so my link href will include the ?thisbuttonvar=whatever BUT if that get var already exists then the link href should not include ?thisbuttonvar=whatever it should remove it
I have created a function to try to handle this as follows (sorry I can't get it to paste properly):
function href_append_query($param) {
parse_str($_SERVER["QUERY_STRING"], $query_array);
if (array_key_exists(current(array_keys($param)), $query_array))
{
$key = current(array_keys($param));
if ($param[$key] == $query_array[$key])
{
unset($query_array[$key]);
}
}
else
{
$query_array = $query_array + $param;
}
$query = http_build_query($query_array);
return '?' . $query; }
The issue with this is when I do a
#foreach ($category->subCategories()->get() as $sub_category)
<li><a class="search-filter" href=<?=href_append_query(['sub_category' => $sub_category->sub_category_url])?>>{!! $sub_category->sub_category !!}</a></li>
It works for the first link, but all the rest of my href's come back the same (as the first one that enters the function)
Can anyone assist in getting this function to work so the foreach link has the appropriate href OR an entirely different "easier" way all together :)
My jQuery if it helps paint a better picture
$(document).on("click", '.search-filter', function(e) {
e.preventDefault();
$('#spinner-modal').modal('show');
$('#spinner-modal p').html('<b>Searching,</b> please wait...<br />');
query = $(this).attr('href');
history.replaceState(null, null, query);
$.ajax({
type: "GET",
url : query,
success : function(data, status){
$('#job-results').html(data);
$('#spinner-modal').modal('hide');
},
error : function(status){
console.log(status);
},
});
});
I am using jQuery to delete some data from database. I want some functionality that when jQuery returns success I want to execute a query. I want to update a another table on success of jQuery without page refresh. Can I do this and if yes how can I do this?
I am newbie to jQuery so please don't mind if it's not a good question for stackoverflow.
This is my script:
<script type="text/javascript">
$(document).ready(function () {
function delete_comment(autoid, btn_primary_ref) {
$.ajax({
url: 'rootbase.php?do=task_manager&element=delete_comment',
type: "POST",
dataType: 'html',
data: {
autoid: autoid
},
success: function (data) {
// I want to execute the Update Query Here
alert("Comment Deleted Successfully");
$(btn_primary_ref).parent().parent().hide();
var first_visible_comment = $(btn_primary_ref).parent().parent().parent().children().find('div:visible:first').eq(0).children('label').text();
if (first_visible_comment == "") {} else {
$(btn_primary_ref).parent().parent().parent().parent().parent().parent().prev().children().text(first_visible_comment);
}
load_comment_function_submit_button(autoid, btn_primary_ref);
},
});
}
$(document).on('click', '.delete_user_comment', function (event) {
var autoid = $(this).attr('id');
var btn_primary_ref = $(this);
var r = confirm("Are you sure to delete a comment");
if (r == true) {
delete_comment(autoid, btn_primary_ref);
} else {
return false;
}
});
});
</script>
You can't do database operations directly in Javascript. What you need to do is to simply make a new AJAX request on success to a php file on the backend to update given table. However this would mean two AJAX requests to the backend, both of which manages database data. Seems a bit unnecessary. Why not just do the update operation after the delete operation in the php file itself?
add a server sided coded page that will execute your query.
example :
lets say you add a page named executequery.php.
with this code:
when you want to execute your query do the following :
$.post("executequery.php",//the URL of the page
{
param1:value1,
param2:value2....//if you want to pass some parameters to the page if not set it to null or {}
},
function(data){
//this is the callback that get executed after the page finished executing the code in it
//the "data" variable contain what the page returened
}
);
PS : tha paramters sent to the page are conidired like $_POST variables in the php page
there is an other solution but its UNSAFE i recomand to NOT use it.
its to send the query with the paramters and that way you can execute the any query with the same page example :
$.post("executequery.php",//the URL of the page
{
query:"insert into table values("
param1:value1,
param2:value2....//if you want to pass some parameters to the page if not set it to null or {}
},
function(data){});
I have a page that contains a captcha. whenever the user enters the captcha incorrectly the form will submit and they will move on. If not, i want to refresh the captcha image so that the user has to enter the new number. this code currently works in Chrome, but the image wont refresh in firefox. does not work in IE either.
javascript method:
function CheckCaptcha() {
var UserInput = $("#Captcha").val();
$.ajax({
type: "POST",
url: "/Messaging/CheckUserCaptcha",
data: { userCaptcha: UserInput },
success: function (data) {
//alert("SUCCESS: " + data.success);
//alert("SUCCESS2: " + data.message);
var correct = data.success;
if (correct == true) {
document.forms[0].submit();
} else { THIS IS WHERE I NEED TO REFRESH THE CLASS
alert(data.message);
$(".captchaImage").attr("src", "<%= Url.Action("CaptchaImage", "Messaging", new {prefix = "CaptchaImage"}) %>");
}
}
});
return false;
}
this is what the HTML looks like
<img src="/Messaging/CaptchaImage?prefix=CaptchaImage" class="captchaImage"></img>
i used the answer from this question to answer mine:
How to reload/refresh an element(image) in jQuery
so essentially my question may have been a copy of his question. it just took me a while to find the answer.
i added a var d, which was instantiated as a new instance of the Date object. then i concatenated onto my image the getDate() method.