so I am attempting to pass some information in a JSON object and have a php page insert the data into a database. However, I am running into some trouble. The "update" button exists in a popup window. The user then clicks "update" and the inputted data should be processed accordingly. However, I fear that I am not even reaching my .click function. None of my alerts seems to be triggered. Below I will point out where issues are occurring. Thank you!
<script>
function updateTable()
{
document.getElementById("testLand").innerHTML = "Post Json";
//echo new table values for ID = x
}
$('#update').click( function() {
alert("help!");
var popupObj = {};
popupObj["Verified_By"] = $('#popupVBy').val();
popupObj["Date_Verified"] = $('#popupDV').val();
popupObj["Comments"] = $('#popupC').val();
popupObj["Notes"] = $('#popupN').val();
var popupString = JSON.stringify(popupObj);
alert(popupString);
#.ajax({
type: "POST",
dataType: "json",
url: "popupAjax.php",
//data: 'popUpString = '+ popupString,
data: popupObj,
cache: false,
success: function(data) {
updateTable();
alert("testing tests");
}
});
});
</script>
<html>
<button onClick="openPopup(<?php echo $row['ID'];?>);"><?php echo $row['ID'];?></button> <!--opens a popup with input options-->
<button id="update">Update</button> <!-- this button is supposed to cause the javascript above to run when clicked, however none of my alerts seem to be reached.-->
</html>
Thank you for looking!
1)I can only guess that you're trying to use JQUERY?
Where do you include the library?
2 )#.ajax isnt valid Jquery function
try $.ajax instead
Related
I posted this question ealier today, however I recieved a fix (thank you) that works great against my RequestBin endpoint for testing, however when submitting to my AJAX script, its a different story.
Problem: I cant submit my jQuery toggle values to my PHP AJAX script because there is no form name associated with the POST request (so db never updates). I proven this by making a HTML form with the field names and the database updated right away. However this is not the case with this JS toggle method.
jQuery code
$(document).ready(function() {
$('.switch').click(function() {
var $this = $(this).toggleClass("switchOn");
$.ajax({
type: "POST",
url: "https://--------.x.pipedream.net/",
data: {
value: $this.hasClass("switchOn") ? 'pagination' : 'infinite'
},
success: function(data) {
console.log(data);
}
});
});
});
HTML
<div class="wrapper-toggle" align="center">
<label>
<div class="switch"></div>
<div class="switch-label">Use <b>Paged</b> results instead (Current: <b>Infinite</b>)</div>
</label>
</div>
PHP AJAX script
if (array_key_exists('pagination', $_POST)) {
$stmt = $conn->prepare("UPDATE users SET browse_mode = 'pagination' WHERE user_id = 1");
//$stmt->bindParam(":user_id", $account->getId(), PDO::PARAM_INT);
$stmt->execute();
} else if (array_key_exists('infinite', $_POST)) {
$stmt = $conn->prepare("UPDATE users SET browse_mode = 'infinite' WHERE user_id = 1");
//$stmt->bindParam(":user_id", $account->getId(), PDO::PARAM_INT);
$stmt->execute();
}
I cant figure out how to assign a field name to this, as it is not a traditional post form. This is driving me nuts. So the previous solution was applying hasClass() and calling var $this outside of $ajax(), great (and RequestBin receives both requests), but when submitting to PHP its a dead end (no form names).
Given the code above fixed and revised twice, where do I even start without a form ??
We need:
name="pagination"
name="infinite"
But this toggle JS doesn't allow for this. prop() has been removed to get toggle submitting values over (just not my AJAX script).
Any solution appreciated. Thank you again.
You can set your values as Form Data. So the PHP Function will get it just like a traditional form submission:
$(document).ready(function() {
$('.switch').click(function() {
var $this = $(this).toggleClass("switchOn");
var formdata = new FormData();
$this.hasClass("switchOn") ? formdata.append('pagination', 'name') : formdata.append('infinite', 'name');
$.ajax({
type: "POST",
url: "https://--------.x.pipedream.net/",
data: formdata,
success: function(data) {
console.log(data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
More info on JS Form Data: https://developer.mozilla.org/en-US/docs/Web/API/FormData
I have a bootstrap 3 modal that is launched via a button on the parent and then populate the modal-body with form data coming from my MySQL database. Among the populated data is small gallery showing attachment pictures and one unique delete-button underneath each picture to launch a query to delete the attachment from a specific attachment folder.
Gallery and delete button ON THE MODAL:
<div class=\"row\">
<div class=\"box box-widget widget-user-2\">
<div class=\"widget-user-header bg-gray\">
<div class=\"lightBoxGallery\">";
$files = scandir($log_folder);
foreach ($files as $attachment) {
if (in_array($attachment, array(".",".."))) continue;
echo "
<span class=\"input\"><button type=\"button\" id=\"DeleteAttachmentButton\" name=\"DeleteAttachmentButton\" class=\"form-btn btn-danger btn-xs\" data-filename=\"".$attachment."\"><i class=\"fa fa-trash\"></i></button><img src=\"".$log_folder.$attachment."\" style=\"height:100px; width:150px;\"></span> ";
}
echo "
</div>
<!-- ./lightbox gallery -->
The problem now is that nothing happens when I press the delete button for the specific attachment. I believe this to be caused by the JavaScript code below which is located ON THE PARENT right after the modal.
// DELETE ATTACHMENT - DELETE BUTTON ON EDIT MODAL
$("#DeleteAttachmentButton").click(function(e){
var modal = $(this);
if (confirm('Are you sure you want to delete this attachment?')) {
var attachment_name = $(e.relatedTarget).data('filename'); // Extract info from data-* attribute
$.ajax({
url: "../../plugins/MySQL/ajax_action.php",
type: "POST",
async: true,
data: { action:"delete_attachment",Holidex:$("#dataLogID").val(), LogID:$("#dataLogID").val(), Filename:attachment_name).val()}, // form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#logbook_output').html(data);
drawVisualization();
},
error: function(data) {
console.log(err);
}
});
// close modal and refresh page
$('#EditLogModal').modal('hide');
}
});
I checked with Chrome Debugger to see whether any AJAX call is made, but I do not even get to the JavaScript Confirm Alert nor do I receive any error message in the console.
Any hints please?
Thanks
You have an invalid JSON data in your AJAX call (may be you can see errors in your browser's console),
data: { action:"delete_attachment",Holidex:$("#dataLogID").val(),
LogID:$("#dataLogID").val(), Filename:attachment_name).val()}, // form data to post goes here as a json object
//------------------^ don't use this
Just use Filename:attachment_name}
data: { action:"delete_attachment",Holidex:$("#dataLogID").val(),
LogID:$("#dataLogID").val(), Filename:attachment_name)}
change this
$("#DeleteAttachmentButton").click(function(e){
to this
$(document).on("click","#DeleteAttachmentButton",function(e){
Read about event-delegation
$(document).on('click', '#DeleteAttachmentButton', function(e){
var modal = $(this);
if (confirm('Are you sure you want to delete this attachment?')) {
var attachment_name = $(e.relatedTarget).data('filename'); // Extract info from data-* attribute
$.ajax({
url: "../../plugins/MySQL/ajax_action.php",
type: "POST",
async: true,
data: { action:"delete_attachment",Holidex:$("#dataLogID").val(), LogID:$("#dataLogID").val(), Filename:attachment_name).val()}, // form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#logbook_output').html(data);
drawVisualization();
},
error: function(data) {
console.log(err);
}
});
// close modal and refresh page
$('#EditLogModal').modal('hide');
}
});
I am working with Concrete-5 CMS, I have an issue in passing value form view to controller.In my application I am using following code for displaying employee role.
foreach($rd as $data){
echo "<tr><td>".$data[role_name]."</td><td>".$data[role_description]."</td><td>Edit</td><td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td></tr>";
}
<input type="hidden" name="rno" id="rno" />
script:
$delConfirmJS = t('Are you sure you want to remove this Role?'); ?>
<script type="text/javascript">
function deleteRole(myvar) {
var role = document.getElementById('rno');
role.value = myvar;
if (confirm('<?php echo $delConfirmJS ?>')) {
$('#rolelist').submit();
//location.href = "<?php echo $this->url('/role/add_role/', 'delete', 'myvar')?>";
}
}
</script>
html code
I did edit operation by passing role_id through edit action. But, In case of delete i should ask for a conformation, so I use java script to conform it and call the href location and all.
But i don't know how to pass the role_id to script and pass to my controller. how to achieve this task?
thanks
Kumar
You can pass value to server using ajax calls.
See the following code. Here We use a confirm box to get user confirmation.
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm)
{
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}
In delete.php you can take the employee id by using $_POST['emp_id']
You can do it easily by using jquery
var dataString = 'any_variable='+ <?=$phpvariable?>;
$.ajax({
type: "POST",
url: "otherfile.php",
data: dataString,
success: function(msg){
// msg is return value of your otherfile.php
}
}); //END $.ajax
I would add an extra variable in to the delete link address. Preferrably the ID of the row that you need to be deleted.
I don't know Concrete-5 CMS. But, i am giving you the general idea
I think, you are using some button on which users can click if they want to delete role.
<td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td>
My suggestion,
add onClick to button
onClick="deleteEmployee(roleId);" // roleId - dynamic id of the role by looping over
Frankly speaking dude, i dont know how you will add this to your button that i guess there would surely be some way to simply add this to existing html.
And now, simply use Sajith's function
// Sajith's function here
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm){
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}
i have a html page, which contains a form and i want when the form is successfully submited, show the below div:
<div class="response" style="display: none;">
<p>you can download ithere</p>
</div>
i also have a jquery function:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
$(".response").show();
}
});
});
});
</script>
and in my views.py (code behind) i create a link and pass it to html page. i have:
def backup(request):
if request.is_ajax():
if request.method=='POST':
//create a link that user can download a file from it. (link)
variables = RequestContext(request,{'link':link})
return render_to_response('backup.html',variables)
else:
return render_to_response('backup.html')
else:
return render_to_response("show.html", {
'str': "bad Request! :(",
}, context_instance=RequestContext(request))
backup = login_required(backup)
my problem: it seems that my view doesn't execute. it doesn't show me the link that i send to this page. it seems that only jQuery function is executed. i'm confused. how can i make both of them to execute(i mean jQuery function and then the url i set in this function which make my view to be executed.)
i don't know how to use serialize function. whenever i searched, they wrote that:
The .serialize() method creates a text string in standard URL-encoded notation and produces query string like "a=1&b=2&c=3&d=4&e=5.
i don't know when i have to use it, while i can access to my form field in request.Post["field name"]. and i don't know what should be the data which is in success: function(data) in my situation.
thank very much for your help.
You have to get and display the data from your ajax post function, where data is the response you render through your DJango server, for example:
t = Template("{{ link }}")
c = Context({"link": link})
t.render(c):
Your JS / jQuery should become something like this:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
// 'data' is the response from your server
// (=the link you want to generate from the server)
// Append the resulting link 'data' to your DIV '.response'
$(".response").html('<p>you can download ithere</p>');
$(".response").show();
}
});
});
});
</script>
Hope this helps.
Thats the best description I could think of. I normally do not post, but I honestly cannot figure this out.
Still in jquery learning mode, and basically what I want to accomplish is that depending on the type of button that is submitted, the script assigns variables to div's on the page. What I am making is a admin side of a user script to allow them to update that particular div that appears on the page.
When I put in the actual selectors, the script works.
When the page loads, it will take the field of the database that corresponds with the and load it. Once they push the update button, a new div will appear. The admin inputs his new data (the new information he wants to display) and it updates the mysql table, then pulls it back in through jquery's ajax.
Sorry for the long explanation. Like I said, I've never really posted, just always liked figuring it out on my own.
php page
<?php //
if(isLoggedIn())
{
echo '<button id="adultClassButton">Edit Class Information</button>';
}
?>
<div class="class" id="adultClass"><?php
$row = checkPost('adult');
echo $row['info'];
?>
</div>
<?php
echo '<div id="adultClassInput">
<textarea rows="2" cols="80" id="adultClassUpdate"></textarea>
<input type="hidden" id="className" name="adult"/>
<button id="adult">Save the Updated Class Info</button></div>';
?>
javascript (jquery) file
$(".button").click(function(){
var button = $(this).attr('id');
if (button == 'adult'){
var classDiv = $("#adultClass");
var className = $("#className");
var classDesc = $("#adultClassUpdate").val();
var classUpdateDiv = $("#adultClassInput");
postData(classDiv, className, classDesc, classUpdateDiv);
}
});
function postData(classDiv, className, classDesc, classUpdateDiv){
$.ajax({
url: 'insert.php',
type: 'POST',
data: "name="+ className+ "& info="+ classDesc,
success:function(data){
$("#" + classDiv).html(data);
}
})
$("#" + classDesc).val('');
$("#" + classUpdateDiv).hide();
}
Like I said, if I have normal selectors in the function, it works as intended. But as of right now, I'm just stumped as to whats wrong.
Thanks a bunch!
classDiv is a jquery object not the ID of the element. So when you use this
$("#" + classDiv).html(data);
That's not working as expected.
Try
classDiv.html(data);
Your function should be like this:
function postData(classDiv, className, classDesc, classUpdateDiv){
$.ajax({
url: 'insert.php',
type: 'POST',
data: {"name": className.val(), "info": classDesc}
success:function(data){
classDiv.html(data);
}
})
$("#"+classDesc).val('');
classUpdateDiv.hide();
}
because you already passed jquery objects (not strings) to your function, except for classDesc.
Hope this helps. Cheers