jQuery get div contents and send to php script via ajax - php

I am trying to get the contents of a div and send that to ajax.
Here is a sample code of ajax that sends data but how can I put the html contents of a div in this post and send it to another php script via ajax?
I need to send ALL the HTML in the "sortable" ui and not just the text.
<ul id="sortable">
<li class="ui-state-default">Hello, please send me to Ajax! :)</li>
</ul>
$("button").click(function()
{
$.post("get_sorted_content.php", // Example script
{
data: $("#sortable").html(); // My NEEDED content - Does not work!
function(data)
{
alert("Data: " + data + ");
});
});
Again, This code may be missing some elements but regardless it doesn't work. It's just an example showing what I am trying to do.

I'll use the AJAX method as an example here because I think it's a little clearer about what you want to do. Let's retrieve the li contents and sent it to your PHP script.
Don't bind to the button element, that is not very specific at all and will bind to any button on the page. Instead, give it an id and bind to that.
Your main problem is that you're getting the HTML of the ul with id sortable, not the specific li element you're after.
<ul id="sortable">
<li class="ui-state-default">Hello, please send me to Ajax! :)</li>
</ul>
<button id="clickme">Click me!</button>
// bind to the button with clickme ID
$("button#clickme").click(function() {
$.ajax({
url: 'get_sorted_content.php',
type: 'POST', // GET is default
data: {
yourData: $('#sortable li').html()
// in PHP, use $_POST['yourData']
},
success: function(msg) {
alert('Data returned from PHP: ' + msg);
},
error: function(msg) {
alert('AJAX request failed!' + msg);
}
});
});
Now in your PHP script, you can access that data with $_POST['yourData']:
<?php
// get_sorted_content.php
if(!empty($_POST['yourdata']))
echo 'data received!';
else
echo 'no data received!';
?>
EDIT: following having seen your statement: I need to send ALL the HTML in the "sortable" ui and not just the text., if you need the entire ul contents, use what you had originally:
data: {
yourData: $('ul#sortable').html();
}

Your $.post call needs to change as follows:
$.post('get_sorted_content.png',
{ data: $("#sortable").html()},
function(data){
//data is whatever you send back from php script.
}
);
if $("#sortable").html() does not work, try to escape the HTML like:
escape($("#sortable").html());

Related

how to change the jquery code from onclick to show content always

I want to show a comments section always. Now a user has to click, to start the javascript code to display the content (onclick). a simple change to "onload" is not working. I tried it.
//Show reviews
function reviews_show(value) {
jQuery.ajax({
type:'POST',
url:'<?php echo site_root?>/members/reviews_content.php',
data:'id=' + value,
success:function(data){
if(document.getElementById('comments_content'))
{
document.getElementById('comments_content').innerHTML = data;
}
}
});
}
html code on .tpl page:
<li>Comments</li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="comments_content"></div> </div>
If you mean with always -> on page load -> then this is the answer:
document.addEventListener("DOMContentLoaded", function(event) {
var value='{ID}'; // use value variable for your ID here
jQuery.ajax({
type:'POST',
url:'<?php echo site_root?>/members/reviews_content.php',
data:'id=' + value, // or replace to => data:'id={ID}',
success:function(data){
if(document.getElementById('comments_content'))
{
document.getElementById('comments_content').innerHTML = data;
}
}
});
});
Edit: Of course this was just an example how to make the browser to execute the jQuery.ajax on Page Loaded Completed. I edited the code and put the var value='{ID}' for your example. Make sure that there is your ID inserted (as it was inserted before in your onclick="reviews_show({ID});".

ajax inject html into a div but keep the html elements including their ids

I am using some ajax to call a php file that returns some html (an image and couple of buttons) and then place the contents of this into a div. The trouble is that I want to be able to use the id of one of the buttons that is returned from the php to hook up an event handler. The output of the source if I do view source in browser simply shows the div that the html is injected into and not the html:
<div class="displaysomething"></div>
My AJAX is as follows:
$(document).ready(function () {
getServiceDisplay();
$('#stop-service').click(function(e)
{
e.preventDefault();
runHDIMService();
});
}
function getServiceDisplay(){
$.ajax(
{
url: 'includes/dosomething.php',
type: 'POST',
success: function(strOutput)
{
$(".displaysomething").html(strOutput);
}
});
};
PHP - Ultimately returns a button amongst other stuff. This is what I need to hook up to the event handler, based on its id.
echo '<input id="stop-service" type="button" value="Run" class="'.$strRunActionButtonClass.'"/>';
If I simply put a button on the page without injecting it using AJAX into the div my button hookup code works great.
Does anybody have any ideas?
Thanks
In jQuery, the .click(... method of adding an event handler will only add the event to existing elements. New elements added later are no included.
You can use the jQuery on method of event binding to include elements added later.
$("body").on("click", "#stop-service", function(e){
e.preventDefault();
runHDIMService();
});
I have created a simple example on JSFiddle.
The problem is that
$(document).ready(function () {
getServiceDisplay();
$('#stop-service').click(function(e) // this doesn't exists yet
{
e.preventDefault();
runHDIMService();
});
This should work:
function getServiceDisplay(){
$.ajax(
{
url: 'includes/dosomething.php',
type: 'POST',
success: function(strOutput)
{
$(".displaysomething").html(strOutput);
// so after you attached the div from ajax call just register your event
$('#stop-service').click(function(e)
{
e.preventDefault();
runHDIMService();
});
});
};

jQuery/JavaScript ajax call to pass variables onClick of div

I am trying to pass two variables (below) to a php/MySQL "update $table SET...." without refreshing the page.
I want the div on click to pass the following variables
$read=0;
$user=$userNumber;
the div Basically shows a message has been read so should then change color.
What is the best way to do this please?
here's some code to post to a page using jquery and handle the json response. You'll have to create a PHP page that will receive the post request and return whatever you want it to do.
$(document).ready(function () {
$.post("/yourpath/page.php", { read: "value1", user: $userNumber}, function (data) {
if (data.success) {
//do something with the returned json
} else {
//do something if return is not successful
} //if
}, "json"); //post
});
create a php/jsp/.net page that takes two arguments
mywebsite.com/ajax.php?user=XXX&secondParam=ZZZZ
attache onClick event to DIV
$.get("ajax.php?user=XXX&secondParam=ZZZZ". function(data){
// here you can process your response and change DIV color if the request succeed
});
I'm not sure I understand.
See $.load();
Make a new php file with the update code, then just return a json saying if it worked or not. You can make it with the $.getJSON jQuery function.
To select an element from the DOM based on it's ID in jQuery, just do this:
$("#TheIdOfYourElement")
or in your case
$("#messageMenuUnread")
now, to listen for when it's been clicked,
$("#messageMenuUnread").click(function(){
//DO SOMETHING
}
Now, for the AJAX fun. You can read the documentation at http://api.jquery.com/category/ajax/ for more technical details, but this is what it boils down to
$("#TheIdOfYourImage").click(function(){
$.ajax({
type: "POST", // If you want to send information to the PHP file your calling, do you want it to be POST or GET. Just get rid of this if your not sending data to the file
url: "some.php", // The location of the PHP file your calling
data: "name=John&location=Boston", // The information your passing in the variable1=value1&variable2=value2 pattern
success: function(result){ alert(result) } // When you get the information, what to do with it. In this case, an alert
});
}
As for the color changing, you can change the CSS using the.css() method
$("#TheIdOfAnotherElement").css("background-color","red")
use jQuery.ajax()
your code would look like
<!DOCTYPE html>
<head>
</head>
<body>
<!-- your button -->
<div id="messageMenuUnread"></div>
<!-- place to display result -->
<div id="frame1" style="display:block;"></div>
<!-- load jquery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
//attach a function to messageMenuUnread div
$('#messageMenuUnread').click (messageMenuUnread);
//the messageMenuUnread function
function messageMenuUnread() {
$.ajax({
type: "POST",
//change the URL to what you need
url: "some.php",
data: { read: "0", user: "$userNumber" }
}).done(function( msg ) {
//output the response to frame1
$("#frame1").html("Done!<br/>" + msg);
});
}
}
</script>
</body>

How to get parameters from a link that callls a jQuery function?

I have a link that looks like this:
<p class="half_text">
<?php echo $upvotes; ?>
<strong><a class="vote_up" style="color: #295B7B; font-weight:bold;" href="#">Vote Up</a></strong> |
<?php echo $downvotes; ?>
<strong><a class="vote_down" style="color: #295B7B; font-weight:bold;" href="#">Vote Down</a></strong>
</p>
and I have the jQuery code that looks like this:
<script type="text/javascript">
$(document).ready(function()
{
$('.vote_up').click(function()
{
alert("up");
alert ( "test: " + $(this).attr("problem_id") );
// $(this).attr("data-problemID").
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(json)
{
// ? :)
}
});
//Return false to prevent page navigation
return false;
});
$('.vote_down').click(function()
{
alert("down");
//Return false to prevent page navigation
return false;
});
});
</script>
How can I get the parameter value which is problem_id ? If I add a url in the href parameter, I think the browser will just go to the url, no? Otherwise - how can I pack parameter values into the jQuery?
Thanks!
Because your $.ajax is defined in the same scope of the variable, you can use problem_id to obtain the variable value.
An overview of your current code:
var problem_id = "something"; //Defining problem_id
...
$.ajax(
...
success: function(){
...
//problem_id can also be accessed from here, because it has previously been
// defined in the same scope
...
}, ...)
....
If what you're trying to figure out is how to embed the problem ID in the link from your PHP so that you can fetch it when the link it clicked on, then you can put it a couple different places. You can put an href on the link and fetch the problem ID from the href. If you just do a return(false) from your click handler, then the link will not be followed upon click.
You can also put it as a custom attribute on the link tag like this:
<a class="vote_up" data-problemID="12" style="color: #295B7B; font-weight:bold;" href="#">Vote Up</a>
And, then in your jQuery click handler, you can retrieve it with this:
$(this).attr("data-problemID").
do you mean, getting variables from the php page posted?
or to post?
anyway here's a snippet to replace the $.ajax
$.post('/problems/vote.php', {problem_id: problem_id, action: 'up'}, function(data) {
// data here is json, from the php page try logging or..
// console.log(data);
// alert(data.title);
}, 'json');
{problem_id: problem_id, action: 'up'} are the variables posted... use $_POST['problem_id'] and $_POST['action'] to process..
use simple variables names with jQuery.data and make sure you have latest jQuery..
let me try to round it up..
up
down
<script type="text/javascript">
$('.votelink').click(function() {
$.post('/problems/vote.php', {problem_id: $(this).data('problemid'), action: $(this).data('action')}, function(data) {
// data here is json, from the php page try logging or..
// console.log(data);
// alert(data.title);
}, 'json');
});
</script>

jquery ajax post - how to get data back?

I have a profile page that contains a series of images. I want to use jQuery to allow the user to delete an image from the server and have the page update without reloading the entire page. When it's successful, it will remove the image's containing div from the page. My delete function is PHP; fairly simple:
delete.php
<?php
if (isset($_POST['id'])) {
if (unlink($_POST['id'])) {
echo "success";
}
else {
echo "failure";
}
}
?>
(There's already user authentication in place just to get them to the page that calls delete.php.)
Here's the html of one displayed image - there can be up to 5 of these chunks one after another:
<div class="box">
<img src="uploads/t_10DOT_22C_1111_1300370702_3.jpg" />
<h5><a rel="external" href="uploads/10DOT_22C_1111_1300370702_3.jpg">See full version</a></h5>
<a href="#" id="10DOT_22C_1111_1300370702_3.jpg" class="delete" onclick="return ConfirmDelete();" >x</a>
<div class="clear"></div>
</div>
My jQuery so far looks like this:
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(data){
commentContainer.slideUp('slow', function() {$(this).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
The part I'm concerned with is the ajax post. How does the success part actually work? What do I need to do in my php file so that ajax knows whether the delete was a success or failure?
Once an ajax post request has finished executing the file you sent the request to, if there was no error, the code you add in the "success" section is executed, in this case
success: function(data){
/*The code you need*/
});
The previous part if where the code is executed, the "data" variable contains anything you return from your php file, it can be data, it can be a simple "true" or "false", you choose what to send to let your jQuery know if it was successful.
Hope this helps a bit.
Edit Note:
function(applyData){
if ( applyData.toString() == 'invalid' ){
$('#pollError').html('Global styles cannot be modified.');
$('#pollNotice').html('');
}
else{
$('#pollNotice').html('The changes to the style have been applied.');
}
});
The previous example is a live example of what you can do inside the function in the "success" event. There I handle an "invalid" status and otherwise it's successful, after that I refresh a couple DIVs in case of invalid or update a single DIV in case of success.
This is the php that executes:
if ( !$db->isGlobal($id_css)){
$data['id_poll'] = $id_poll;
$data['id_css'] = $id_css;
$data['css'] = $css;
$db->applyCssChanges($data);
}
else{
echo 'invalid';
}
You've two obvious options I can think of:
Your returned text should appear in the data parameter supplied to your success callback function - however you'll probably also need to make sure it's in a format compatible with the MIME Content-Type returned by your PHP, or jQuery might complain that it can't parse it, or:
Send back a 5xx Failure type message from your PHP using the header() function if the delete didn't work. That should then trigger an AJAX error callback, which you'll need to supply.
From delete.php return whether the delete succeeded or not. In the success even check for that data and handle it appropriately.
HTH.

Categories