I am getting no responses when I try to fire this ajax request from jquery:
/********************************
CHANGE USER SETTINGS
*********************************/
$(".submitUserSetting").live('click', function() {
//get values
var department = $("#us_department").val();
var sortOrder = $("input[#name=us_sortOrder]:checked").val();
$.ajax({
type: "POST",
url: "lib/includes/updateUserSettings.php",
data: "empname=" + empname + "&department=" + department + "&sortOrder=" + sortOrder,
success: function(data) {
alert(data);
}
});
});
I mean nothing. No javascript errors, no errors on the MySQL query, not even POST data in the console.log. Just a taunting batch o' silence. Even if I comment out all the code in the PHP page and just echo the data I sent over to it, nothing. Here's the PHP page (the class exists, the functions work, I'm using them on a dozen or so other pages)
<?php
require_once("../classes/mysqlconnect.php");
$db = new dbconnect();
$db->makeConnections("TimeSheetManager");
$empname = $_POST['empname'];
$department = $_POST['department'];
$sortOrder = $_POST['sortOrder'];
//get the department id
$dQuery = "SELECT id FROM departments WHERE department = '" . $department . "'";
$dResults = $db->getResults($query);
if (mysql_num_rows($dResults) > 0) {
while($rows = mysql_fetch_array($dResults) {
$deptID = $rows['id'];
}
}
//update database
$query = "UPDATE users SET `department` = '" . $department "', `displayOrder` = '" . $sortOrder . "' WHERE username = '" . $empname . "'";
$results = $db->getResults($query);
if ($results) {
echo "!success";
} else {
echo "!fail";
}
?>
Here's the form code:
<div id="userSettingsForm">
<form name="userSetting">
<p><label for="sortOrder">Display Order:</label></p>
<p class="userSettingElement">Oldest First <input type="radio" name="us_sortOrder" value="asc"> Newest First <input type="radio" name="us_sortOrder" value="dsc"></p>
<p><label for="us_department">Department:</label></p>
<p class="userSettingElement">
<select id="us_department" name="us_department">
<option value="null">Select A Department</option>
<?php
$query = "SELECT * FROM departments";
$results = $db->getResults($query);
while($row = mysql_fetch_array($results)){
if (count($results) > 0) {
//get department and id
$department = $row['department'];
$deptID = $row['id'];
print "<option value=\"" . $deptID . "\">" . $department . "</option>";
}
}
?>
</select>
</p>
<p>Submit</p>
</form>
</div>
Thanks for all the help and suggestions. I rebooted Firefox and the error was in empname, I wasn't setting it (doh!). Beluga was on to that but it took a bit for it to dawn on me. Wish I could award everyone with the answer.
How can you tell you're not getting an error? Add an error handler to your .ajax() call:
$.ajax({
type: "POST",
url: "lib/includes/updateUserSettings.php",
data: "empname=" + empname + "&department=" + department + "&sortOrder=" + sortOrder,
success: function(data) {
alert(data);
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
OK, some more investigation shows that the error is actually in a peculiar combination of pieces of code that you are using.
Apparently, href="javascript:void(0)" prevents event propagation. The event is triggered on the element itself (so handlers bound with .click(fn) work) but ancestor elements are not notified of the event.
Since you are using the .live() method, which relies upon event propagation, this doesn't work here.
I would suggest the following instead:
Submit
and JS:
$(".submitUserSetting").live('click', function(e) {
e.preventDefault(); // disable the link action
[snip]
});
See jsFiddle demonstrating this.
The issue is the way you send the data.
Try enclosing the property in { } 's and changing the variable format to
{ "propertyName" : "value", "propertyName" : "value" }
i.e
data: { "empname" : empname ,"department" : department, "sortOrder" :sortOrder }
alternatively if it is a form you can even say
data : { $("#form").serialize() }
you need to return some value in your php function
data: "empname=" + empname + "&department=" + department + "&sortOrder=" + sortOrder,
define empname in your call which is missing.
this gives you Uncaught ReferenceError
Related
Everything works perfectly except the submit button typically takes three to four times before it works. So I'll have the necessary cid number, plug it into the form, and hit submit. It might work the first time, but it also might take me seven attempts. I've got a bit of a deadline on this thing, and I have no idea how to even go about troubleshooting this so any help at all would be hugely appreciated!
So I've got this form:
<form action="" onsubmit="redirect()">
<input type="text" name="val1" id="val1" placeholder="CID (ten digits)">
<br>
<input type="submit" value="Submit" id="submit">
</form>
Which triggers this javascript function:
function redirect() {
var userID = document.getElementById("val1").value;
var userID = userID.replace(/-/g, "");
//alert(userID);
//var userID = "9183179265";
$.ajax({
type: "POST",
url: './getNetworkType.php',
data: "userID=" + userID,
success: function(data) {
//alert(data);
if(data.indexOf("Search") > -1) {
//alert(data.substr(data.length - 10));
window.location = "http://jumpsixdashboard.com/Reporting/display_search.php?cid=" + data.substr(data.length - 10);
}
else {
//alert(data.substr(data.length - 10));
window.location = "http://jumpsixdashboard.com/Reporting/display_report.php?cid=" + data.substr(data.length - 10);
}
}
});
}
Which executes this script:
<?php
$val1 = $_POST['userID'];
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql3 = "SELECT * FROM account_type WHERE cid ='" . $val1 . "'";
$result3 = $mysqli->query($sql3);
if ($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()) {
echo $row3["network"];
}
}
?>
I think the problem is in your function onsubmit.
You should try something like this.
Set ID to form to example "myForm". Remove onsubmit from Form.
And add this code. This should send data successfull and avoid the submit that you don't won't.
$("#myForm").submit(function() {
redirect();
return false; // this avoid submit.
});
I have two dropdowns generating from MySQL database. The second dropdown is based on the first dropdown select option.
The problem is that, I am unable to generate the second dropdown data.
I am getting the second dropdown values as Undefined. But the number of values that should come in the second dropdown is correct.
Please suggest where am I doing wrong. Thanks.
Below are my codes:
Index.php (connection)
<?php
//Create the connection
$con = mysqli_connect("localhost","root","root","echodeve_mfb_temp") or die("Some error occurred during connection " . mysqli_error($con));
// Write query
$strSQL = "SELECT bp_id, bp_name FROM mfb_billing";
// Execute the query.
$query = mysqli_query($con, $strSQL);
// Close the connection
//mysqli_close($con);
?>
Index.php (Script)
<script>
$(document).ready(function() {
$("#item_1").change(function () {
var group_id = $(this).val();
$.ajax({
type: "POST",
url: "dropdown_select.php?item_1_id=" + group_id,
dataType: "json",
success: function(data){
//Clear options corresponding to earlier option of first dropdown
$('select#item_2').empty();
$('select#item_2').append('<option value="0">Select Option</option>');
//Populate options of the second dropdown
$.each( data, function(i, val){
$('select#item_2').append('<option value="' + val.hospital_id + '">' + val.hospital_name + '</option>');
});
$('select#item_2').focus();
},
beforeSend: function(){
$('select#item_2').empty();
$('select#item_2').append('<option value="0">Loading...</option>');
},
error: function(){
$('select#item_2').attr('disabled', true);
$('select#item_2').empty();
$('select#item_2').append('<option value="0">No Options</option>');
}
})
});
});
</script>
</head>
Index.php (HTML)
<body>
<label id="item_1_label" for="item_1" class="label">#1:</label>
<select id="item_1" name="item_1" />
<option value="">Select</option>
<?php
while($row = mysqli_fetch_array($query)) {
echo '<option value="'.$row['bp_id'].'">'.$row['bp_name'].'</option>'."\n";
}
?>
</select>
<label id="item_2_label" for="item_2" class="label">#2:</label>
<select id="item_2" name="item_2" />
</select>
</body>
dropdown_select.php (Processing PHP)
<?php
$item_1_id = $_GET['item_1_id'];
//Create the connection
$con = mysqli_connect("localhost","root","root","echodeve_mfb_temp") or die("Some error occurred during connection " . mysqli_error($con));
// Write query
$strSQL = "SELECT hospital_id, hospital_name FROM mfb_hospital WHERE bp_id = $item_1_id";
// Execute the query.
$query = mysqli_query($con, $strSQL);
$return_arr = array();
while($row = mysqli_fetch_array($query)) {
$row_array = array("name" => $row['hospital_name'],
"id" => $row['hospital_id']);
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
?>
PHP error exactly tells you what is going wrong and as manual says: Returns FALSE on failure .
Since your error describres $query as boolean given you have to check several thing on your own.
First echo your $strSQL and see if it's proper query, then try to execute it directly on database. There maybe several things, like inproper name of column.
Also, you are returning:
$row_array = array("name" => $row['hospital_name'],
"id" => $row['hospital_id']);
Yet in javascript you are doing:
$.each( data, function(i, val){
$('select#item_2').append('<option value="' + val.hospital_id + '">' + val.hospital_name + '</option>');
});
try this:
$.each( data, function(i, val){
$('select#item_2').append('<option value="' + val.id + '">' + val.name + '</option>');
});
How can i update the database by adding users choices? I have two fields in the database for this purpose, when the user click on yes, it updates the (useful) field and (not_useful) if clicked on no button. I am very new on javascript, so please be patient! :) I appreciate any help in advance.
PHP
<?php
require 'db/conn.php':
$id = (int)$_GET['id'];
if($result = $db->query("SELECT * FROM table_user WHERE table_user_id = $id")){
if($result->num_rows){
while($row = $result->fetch_assoc()) {
echo "
<div class='rating'>
<center>
<p>Are you alrite " . $row['table_user_name'] . "?</p>
<div>
<button type='button' id='yes'>Yes</button>
<button type='button' id='no'>No</button>
</div>
</center>
</div>
<div class='1' style='display:none;'>Text YES</div>
<div class='2' style='display:none;'>Text NO</div>
";
}
}
}
?>
JS
$(document).ready(function(){
$("#yes").click(function(){
$(".rating").hide();
$(".1").show();
});
$("#no").click(function(){
$(".rating").hide();
$(".2").show();
});
});
You can't connect your mySQL database directly with JavaScript from client browser. Event if it would be possible you really don't want to do that because you would have to include mysql login credentials into your JavaScript which is served to client computers.
Of course you could use database like LocalStorage from within JavaScript but these databases are on client computer. If I got it right thats not what you are looking.
You have to send the data to a script on your server which then insert them into your mySQL database. As you stated you don't like the browser to reload to just submitting a form is not an option. In these cases AJAX is used. You will find several tutorials how to send data with JavaScript / JQuery using AJAX to your server.
On server side you could handle for example with a php script. The code you have posted to your question is not PHP but simple HTML. Fred -ii- posted some sample SQL statements to increment a column. I would recommend you to use PHP PDO with mysql driver as this helps you to prevent security issues.
After some working hard, i found a solution. Sharing for those who is facing similar problem. This was my solution. Anyways, have fun! ;)
I think there's a better way to organize the JS script to interact with the php files which manage the sql scripts. If someone would like to help optimize it, will be welcome.
PHP main
<?php
require 'db/conn.php':
$id = (int)$_GET['id'];
if($result = $db->query("SELECT * FROM table WHERE user_id = $id")){
if($result->num_rows){
while($row = $result->fetch_assoc()) {
echo "
<div class='rating'>
<center>
<p>Are you alrite " . $row['user_name'] . "?</p>
<div id='rating-div'>
<a href='#' id='yes' class='custom-btn'>Yes</a>
<a href='#' id='no' class='custom-btn'>No</a>
<input type='hidden' id='" . $id . "' />
</div>
</center>
</div>
";
}
}
}
?>
JS
$(function(){
$('#yes').on('click', function(e){
e.preventDefault();
var usr_id = $('#rating-div input').attr('id');
$.ajax({
url: 'db/rating-yes.php',
type: 'post',
data: {'action': 'rating', 'usr_id': user_id},
success: function(data, status){
if(data == "ok"){
$('.rating').html('<p>Nice!</p>');
}//end of if
},//end of success function
error: function(xhr, desc, err){
console.log(xhr);
console.log("Details: " + desc + "\nError: "+ err);
}
});//end of ajax
}); //end of onclick function
}); //end of main function
$(function(){
$('#no').on('click', function(e){
e.preventDefault();
var usr_id = $('#rating-div input').attr('id');
$.ajax({
url: 'db/rating-no.php',
type: 'post',
data: {'action': 'rating', 'usr_id': user_id},
success: function(data, status){
if(data == "ok"){
$('.rating').html('<p>Oh no! :(</p>');
}//end of if
},//end of success function
error: function(xhr, desc, err){
console.log(xhr);
console.log("Details: " + desc + "\nError: "+ err);
}
});//end of ajax
}); //end of onclick function
}); //end of main function
PHP rating-yes
<?php
$rating = $_POST['action'];
$user_id = $_POST['usr_id'];
if($rating == "rating") {
$conn = mysql_connect('localhost', 'root', '');
$db = mysql_select_db('your_database');
if(mysql_query("UPDATE table SET useful = useful + 1 WHERE user_id = $user_id")){
echo "ok";
}
}
?>
PHP rating-no
<?php
$rating = $_POST['action'];
$user_id = $_POST['usr_id'];
if($rating == "rating") {
$conn = mysql_connect('localhost', 'root', '');
$db = mysql_select_db('your_database');
if(mysql_query("UPDATE table SET not_useful = not_useful + 1 WHERE user_id = $user_id")){
echo "ok";
}
}
?>
I have a PHP form that uses jQuery/AJAX to submit data into a MySQL database table. Currently, I have a message display saying " Done!" once the form is submitted, but would like the actual data to instantly display after it has been submitted. I have a loop setup to display previously added messages in divs with the class name 'msg_container', and would like the new data to display in one of these divs after form submission.
What is the best way to do this? Any help would be greatly appreciated!
index.php javascript
<script type="text/javascript">
$(document).ready(function () {
$(".button").click(function () {
var user_id = $("textarea#uer_id").val();
var msg = $("textarea#msg ").val();
var dataString = 'user_id=' + user_id + '&msg=' + msg;
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function () {
alert("Done!")
}
});
return false
});
});
</script>
index.php query
$user_id = $_GET['user_id'];
require_once('../../includes/connect.php');
$dbh = get_dbh($_SESSION['ORG_ID']);
$sth = $dbh->query ("SELECT *, user.last_name, user.first_name FROM msgs
INNER JOIN users
ON msgs.user_id = users.id
WHERE user_id = '$user_id'
ORDER BY timestamp");
$row = $sth->fetch ();
index.php HTML
<div id="msgs">
<?php while ($row = $sth->fetch ()) { ?>
<div class="msg_container">
<div class="left"><? echo $row['last_name'].', '.$row['first_name']; ?><br />
<? $timestamp = date('m/d/Y g:i a', strtotime($row['timestamp'])); echo $timestamp; ?>
</div>
<div class="right"><? echo $row['msg']; ?></div>
<div class="clear"></div>
</div>
<? } ?>
<div class="add_note">
<div class="left">Add Message</div>
<div class="right">
<form id="add_msg">
<textarea id="msg" name="msg"></textarea>
<input type='submit' class="button right-aligned" value='Submit' />
</form>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
</div>
add.php
<?php
require_once('../../includes/connect.php');
$dbh = get_dbh($_SESSION['ORG_ID']);
$user_id = $_POST['user_id'];
$msg= $_POST['msg'];
date_default_timezone_set("UTC");
$timestamp = date('Y-m-d H:i:s', strftime(gmmktime()));
date_default_timezone_set($_SESSION['TIME_ZONE']);
$sth = $dbh->prepare ("INSERT INTO msgs (id, user_id, msg, timestamp) VALUES (?, ?, ?, ?)");
$data = array (NULL, $user_id, $msg, $timestamp);
$sth->execute ($data);
session_write_close();
?>
You could just append the new message after the previous ones. Something like this:
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function() {
alert ("Done!");
$('#msgs').append('<div class="msg_container">' +
'<div class="left">' + lastNameVariable + ', ' + firstNameVariable +
'<br />' + timeStampVariable +
'</div><div class="right">' + msg + '</div>' +
'<div class="clear"></div></div>');
}
});
You will need to put the first name, last name, timestamp, etc. into variables (or do it a different way, like do an AJAX call to get the info - whatever you prefer). I didn't know what user_id is so I just thought I would let you fill in those variables.
This is just the basic idea of what you could do. If you have any questions, just ask.
I hope this helps.
Edit:
If you created another page called "getname.php" or something like that (to get the first and last name) that would display "first name, last name" based on the user ID passed in the URL, that could work. In the URL it could have ?user_id=1234567 and then on that page, it would do a mysql_query and display the first and last name. This is what I would do:
getname.php ↓
<?
// ...
$user_id = $_GET['user_id'];
$result = mysql_query("SELECT * FROM table WHERE user_id = '$user_id' AND ...");
$row = mysql_fetch_array($result);
// ...
echo $row['last_name'] . ', ' . $row['first_name'];
// ...
?>
Of course you would do this the way you do your queries, but hopefully this helps you understand what I'm saying. Then, after you have that, you can do:
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function() {
alert ("Done!");
var firstAndLast = '';
var theTime =
$.get('getname.php?user_id='+user_id, function(data) {
firstAndLast = data;
});
$('#msgs').append('<div class="msg_container">' +
'<div class="left">' + firstAndLast // this will display: "first name, last name" because of getname.php
+ '<br />' + theTime +
'</div><div class="right">' + msg + '</div>' +
'<div class="clear"></div></div>');
}
});
As for the time, you could either display it with JavaScript (when they refresh it would show the time that was recorded by PHP) or do the same as you did for name.
Consider the jQuery ajax method load. This is a higher level version of ajax. You will send your request and the response will immediately be placed into the preceding selector elements.
$('#result').load('ajax/test.html', data);
Here's just a quick idea to get you going. You need to return the data from the script you call with AJAX; a data that you would use to generate the DIV you want. You'll also need to change the ajax call to something like this:
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function(data) {
console.log(data); //to see what's returned
//use the data to generate content you want
alert ("Done!")
}
});
Due to the structure of your data, it might be the best to send a JSON response.
In the success part add this code:
success: function(data){
$('#flash').css("display","block");;
setTimeout(function () {
$('#flash').slideUp();`enter code here`}, 2000);
}
In the HTML add this code:
<div id="flash" style="display:none;">Data Saved Successfully</div>
My PHP script generates a table with rows which can optionaly be edited or deleted. There is also a possibilety to create a new Row.
I am having a hard time to figure out how to update the HTML rows which are generated through PHP and inserted via jQuery. After the update it must be still editable. The HTML is generated into a div.
jQuery (insert generated HTML/wait for action)
PHP (generate html)
Go back to step 1)
(EDIT: Corrected an error and changed script to answer)
PHP
require_once "../../includes/constants.php";
// Connect to the database as necessary
$dbh = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die("Unaable to connnect to MySQL");
$selected = mysql_select_db(DB_NAME, $dbh) or die("Could not select printerweb");
$action = $_POST['action'];
$name = $_POST['name'];
$id = $_POST['id'];
if ($action == "new") {
mysql_query("INSERT INTO place (id, name) VALUES (NULL, $name)");
}
elseif ($action == "edit") {
mysql_query("UPDATE place SET name = $name WHERE id = $id");
}
elseif ($action == "delete") {
mysql_query("DELETE FROM place WHERE id = $id");
}
echo "<table><tbody>";
$result = mysql_query("SELECT * FROM place");
while ($row = mysql_fetch_array($result)) {
echo "<tr><td id=" . $row["id"] . " class=inputfield_td><input class=inputfield_place type=text value=" . $row["name"] . " /></td><td class=place_name>" . $row["name"] . "</td><td class=edit>edit</td><td class=cancel>cancel</td><td class=delete>delete</td><td class=save>SAVE</td></tr> \n";
}
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>Neu</button>";
JS
$(function() {
$.ajax({
url: "place/place_list.php",
cache: false,
success: function(html) {
$("#place_container").append(html);
}
});
$(".edit").live("click", function() {
$(this).css("display", "none").prevAll(".place_name").css("display", "none").prevAll(".inputfield_td").css("display", "block").nextAll(".cancel").css("display", "block").nextAll(".save").css("display", "block").prevAll(".inputfield_td").css("display", "block");
});
$(".cancel").live("click", function() {
$(this).css("display", "none").prevAll(".edit").css("display", "block").prevAll(".place_name").css("display", "block").prevAll(".inputfield_td").css("display", "none").nextAll(".save").css("display", "none");
});
$(".save").live("click", function() {
var myvariable1 = $(this).siblings().find("input[type=text]").val();
var myvariable2 = $(this).prevAll("td:last").attr("id");
$(this).css("display", "none").prevAll(".cancel").css("display", "none").prevAll(".edit").css("display", "block").prevAll(".place_name").css("display", "block").prevAll(".inputfield_td").css("display", "none");
alert("save name: " + myvariable1 + " save id: " + myvariable2);
});
$(".delete").live("click", function() {
var myvariable3 = $(this).prevAll("td:last").attr("id");
alert(myvariable3);
});
$(".new").live("click", function() {
var myvariable4 = $(this).prevAll("input[type=text]").val();
$.post("place/place_list.php", {
action: "new",
name: "" + myvariable4 + ""
});
});
});
place all your event-handlers outside the ajax function and use the live() method instead. And you need to include what data to send when using ajax. From visualjquery:
$(function() {
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
$(".edit").live("click", function() {
//event handler code here
});
//more event handlers
});
I think you are not getting click events for editing, deleting etc. after new rows from php are appended to the div.
Try using jquery live plugin to bind click events as and when new stuff is created. Please refer to this question dealing with similar problem.
Like peirix and TheVillageIdiot pointed out, the live plugin maybe useful. However, there are some other things you may got wrong in your code:
First, your HTML isn't valid. You have to put quotes around attribut values. You could do this within quotes by escaping inner quotes with a backslash:
echo "<input type=\"text\" class=\"inputfield_visible\" />";
since this looks not that nice, you could leave the PHP part and write pure HTML if you change this:
<?php
...
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>Neu</button>";
?>
To that (IMHO by far more readable):
<?php
...
?>
</tbody>
</table>
<input type="text" class="inputfield_visible" />
<button class="new">Neu</button>
Secondly, and that seems to be even more important, it looks to me like you have a SQLInjection vulnerability, because you pass the field values directly to mysql without using mysql_real_escape_string first. I'm not that into PHP, so maybe I got that wrong, but what happens if you enter ';-- into you input fields?