I have a div popup and there are some links that show this popup.
the problem is here that the content of popup will be different depending on what user click on links:
//my div popup
<div id="show-popup">
<p>$value</p>
</div>
//one,two and three values fetch from database by using Ajax.
show popup = the value must be one
show popup = the value must be two
show popup = the value must be three
now, I don't know how to send 1,2,3 to database by Ajax then how to open that popup after fetch value from database .
I know by below method I can send some value to my url but how I can open popup and then load new value on this popup ?
$.post('myurl' , {id:id} , function(data){
//do stuf
})
Use .html() ; chain .show() to .html() if element is not displayed before click.
To append data instead of replacing existing data at #show-popup , substitute .append() for .html()
function toGetValues(id) {
$.post("myurl", {id:id}, function(data) {
// do stuff
// `.html()` replaces `html` of `#show-popup`
$("#show-popup").append("<p>$" + data + "</p>")
// .show()
})
}
You can also try this
function toGetValues(myvar)
{
$.ajax({
url: "test.php",
type: "post",
data: {mypar: myvar},
success: function (response) {
$( "#show-popup").html(response);
$( "#show-popup").dialog();
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
$.get( "url", {id: id} ).done(
function( data ) {
$("#show-popup").append("<p>" + data + "</p>");
});
You will get the id from the onclick event you have just to send it and put the the value you get back as responce from your PHP page to the paragraph p using text() :
function toGetValues(id)
{
$.post("myurl", {id:id}, function(value) {
$("#show-popup p").text(value); //append returned value from php to the paragraph
$("#show-popup").dialog(); //Show popup
})
}
Related
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 have a script that makes an ajax request to the server. Then the server returns HTML code. After the request finish, I want to take the HTML code and put it on my site.
The problem that I am having is that the function .html() will display the html as text instead of making it an html.
Here is what I have done
var postData =
{
'campaign_id': 1,
'page_role': 'intro'
};
$.ajax({
type: 'POST',
url: 'url/to/get/html',
data: postData,
dataType: "text",
beforeSend: function(jqXHR, settings){
$('#MasterContentViewer').html('<div class="well innerwell">' +
'<h3>Please wait while loading the next page</h3>'+
'</div>');
},
error: function( jqXHR, textStatus, errorThrown ){
alert('Loading content failed! Error Code: ' + jqXHR.status);
},
success: function(page){
$('#MasterTable').removeClass('heightForIFrame');
$('#MasterContent').removeClass('heightForIFrame');
$('#MasterContentViewer').html(page);
}
}).done(function(page) {
var tags = $("meta[name^='is_system_'],meta[name^='is_attr_']" );
$.each(tags, function(index, tag){
var value = $(tag).attr('value');
var name = $(tag).attr('name').replace('is_attr_', '').replace('is_system_', '');
$('#attr_' + name + ':input').val( value );
$('#attr_' + name).not('input').text( value );
$('.attr_' + name + ':input').val( value );
$('.attr_' + name ).not('input').text( value );
});
I tried to change the following like
$('#MasterContentViewer').html(page);
to
$('#MasterContentViewer').empty().append(page);
which also did not work.
I also tried to change the dataType from "text" to "html" which also did not work.
How can I make the force the page to display html code instead of text?
UPDATED
Here is sample of what the user sees on the screen
<strong>Store Name: </strong><span class="attr_storename"></span> </div> <div class="scripter_header_label"> <strong>Store Number: </strong><span class="attr_alt_id_1"></span>
If .html(string) is appending elements as text, then that means that the elements are already HTML Encoded (e.g., <'s are in the string as >'s). jQuery will only encode html if you tell it to by using .text(string) instead of html(string).
Two possible solutions are:
Modify your server-side code to send non-encoded HTML
HTML Decode the string using Javascript (I would not recommend this method, however, because it caters to HTML Injection attacks).
I have included a contact form in my page. In the same page I have a script that gets prices depending on the value of a dropdown. Now when I try to submit the contact message I have a conflict with the script for prices. Basically it tries to run it and I have no clue why. Also the contact form when submitted never works...I just get a new page to open with URL..?message=blablabla
Any idea what is going wrong?
I am working on Laravel 4.2 and so the route you see redirects to my php function.
Here is the JSfiddle and here is the php code:
public function postSendMessage() {
echo "<span class=\"alert alert-success\" >Your message has been received. Thanks!</span><br><br>";
}
Cancel the click so the form will not submit
$("button#send").click( function(evt){
evt.preventDefault();
New error, form has an id of contact, not a class
data: $('form.contact').serialize(),
needs to be
data: $('form#contact').serialize(),
This is what I do for the same situation
//For your drpbox use this code
$(document).on("change", "#yorDropBoxId", function(){
dropBoxValue=$("#yorDropBoxId").val();
var request = $.ajax({//http://api.jquery.com/jQuery.ajax/
url: "samePagePHPcript.php",
type: "POST",
data: {
ObjEvn:"dropBoxEvent",
dropBoxValue: dropBoxValue //You will use $myVar=$_POST["dropBoxValue"] to retrieve the information from javascript
},
dataType: "json"
});
request.done(function(dataset){
//If you want to retrieve information from PHP sent by JSON.
for (var index in dataset){
JsResponse=dataset[index].phpResponse;
}
if(JsResponse test someting){
"do dometing"
control the beheaivor of your HTML elements
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
//To submit your form use this code. You must use Prevent default if you are using a button or using a <a> link tag to trigger the evenrmrnt
$(document).on("click", "#btn_sendForm", function(e){
e.preventDefault();
var dt={
ObjEvn:"FormEvent",
input1:$("#txt_input1").val(),
input2: $("#txt_input2").val(),
input3: $("#txt_input3").val()
};
var request = $.ajax({//http://api.jquery.com/jQuery.ajax/
url: "samePagePHPcript.php",
type: "POST",
data: dt,
dataType: "json"
});
request.done(function(dataset){
//If you want to retrieve information from PHP send by JSON.
for (var index in dataset){
JsResponse=dataset[index].phpResponse;
}
if(JsResponse test someting){
"do dometing"
control the beheaivor of your HTML elements
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
//In the samePagePHPcript.php you can do this:You will return your information from PHP using json like this
$event = $_POST["ObjEvn"];
if(event==="FormEvent"){//Event to insert in your form
$arrToJSON = array(
"phpResponse"=>"data you want to send to javascript",
"asYouWant"=>"<div class=\".class1\">more data</div>"
);
echo json_encode(array($arrToJSON));
}
elseif(event==="dropBoxEvent"){//Event to your dropbox - if you want
$arrToJSON = array(
"phpResponse"=>"data you want to send to javascript",
"asYouWant"=>"<div class=\".class1\">more data</div>"
);
echo json_encode(array($arrToJSON));
}
I have a custom function that I have defined and then I subsequently call when the the page loads. I need the function to run when the page loads because it is populating a group selectlists:
<!---Populate Custom Service Description select lists --->
<script type="text/javascript">
function PopulateSelectLists(){
// Important: Must append the parameter "&returnformat=json"
$.ajax({
url: 'cfcs/get_descriptions.cfc?method=getDescriptions&returnformat=json'
, dataType: 'json'
, success: function(response){
$.each(response.DATA, function(I, row){
// get value in first column ie "description"
var description = row[0];
// append new option to list
$("#descriptionDD1").append($('<option/>', {
value: description,
text : description
}));
$("#descriptionDD2").append($('<option/>', {
value: description,
text : description
}));
$("#descriptionDD3").append($('<option/>', {
value: description,
text : description
}));
$("#descriptionDD4").append($('<option/>', {
value: description,
text : description
}));
});
},
error: function(msg){
console.log(msg);
}
})
}
$(document).ready(PopulateSelectLists);
</script>
I am trying to call my custom function PopulateSelectLists() when another AJAX call successfully completes so I can refresh my selectlists but it never seems to call my function:
<!---Script to add new description to DB --->
<script>
$(function(){
//Add a new note to a link
$("#addDescriptionForm").submit(function(){
// prevent native form submission here
$.ajax({
type: "POST",
data: $('#addDescriptionForm').serialize(),
url: "actionpages/add_descriptions_modal.cfm",
success: function() {
PopulateSelectLists(); //Call Function to refresh selectlist
$("#addDescriptionResponse").append( "Successfully added description." );
}
});
return false;
});
});
</script>
Where am I going wrong here?
In the problematic case, does the request actually return successfully? Inspect the response with Firebug or Fiddler or whatever dev toolbar you are using. It may be that there is a server error, a connection error, or any other reason that can drop the request, so it is not successful.
You can also look into using the complete handler: http://api.jquery.com/jquery.ajax/.
Is there any way to get the text inside an element which is a response from an ajax jquery load. I need to get the text inside element which is present inside the response text from ajax page. Following is my ajax code:
var url = '...';
var saveData = $.ajax({
type: 'POST',
url: url,
data: {data : data},
dataType: "text",
success: function (resultData) {
callback(resultData); // need to get the <h2> text here..
}
});
saveData.error(function () {
console.log("Request to API not send");
});
You can pass HTML to jQuery and use it in the same way as if the element was on the DOM, for example with find():
console.log( $(resultData).find('h2').text() );
If your HTML doesn't have a root element then you can wrap it like so:
resultData = '<div>' + resultData + '</div>';
console.log( $(resultData).find('h2').text() );
How about:
$(resultData).find('h2').text()