How to assign div value to php variable using Jquery Ajax call - ajax

I have a href tag, in that i wrote onclick func,
<?php the_post_thumbnail('portfolio_thumbs'); ?>
in the onclick() function the code is,
<script type="text/javascript">
function doThumb(temp)
var tempThmb = temp;
document.getElementById("selectedResult").innerHTML=tempThmb;
return tempThmb;
}
</script>
the returned value, im printing it in an empty div.
<div id="selectedResult" name="selectedResult"></div>';
Now my issue is, im getting the result in the empty div, but i have to pass the value of the div to $my_postid.
$my_postid = "Should pass the value here";//This is page id or post id
$content_post = get_post($my_postid);
How can i achieve this do i have to use ajax jquery, kindly help me....

This is not possible in the way you are doing. PHP is server side language and javascript is client side. One way to do this is to send an ajax request at onclick event of your image. And send the id in ajax request. The ajax will get the post on the base of that id and will return you. Then you can show that post content any where.
update after receiving code of questioner
You don't need to do initial operation in your function. Just change it as below.
function doThumb(temp) {
var $mainCats=temp;
alert ($mainCats);
$.ajax ( {
url:"<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",
type:'POST',
data:'action=my_special_ajax_callc&main_catidc=' + $mainCats,
onsuccess : function(data) {
$("#selectedResults").removeAttr("disabled");
$("#selectedResults").append(data);
}
} );
}

Related

Refresh form in Django without reloading page

Hi I'm new in Ajax and django and I want to refresh my form. I try some code but it didn't work. I'm sure what I want to do is very basic.
Here my html:
<div class="row" style="padding-top:20px;">
<div class="col-md-12" id="testAjax">
{% load crispy_forms_tags %}
{% crispy form %}
</div>
</div>
I want to refresh my form in the div testAjax.
Here my view:
def createPin(request):
error = False
if request.method == "POST":
form = CreatePinForm(request.POST)
if form.is_valid():
pin = form.save(commit=False)
pin.customer = request.user.customer
pin.save()
msg = "pin saved"
return redirect('/pin/CreatePin', {'form': form, 'msg': msg})
else:
error = True
else:
form = CreatePinForm()
return render(request, 'createPin.html', {'form': form, 'error': error,})
My Ajax:
function refresh()
{
$form=$('#createPin');
var datastring = $form.serialize();
$.ajax({
type: "POST",
url: '/pin/CreatePin/',
dataType: 'html',
data: datastring,
success: function(result)
{
/* The div contains now the updated form */
$('#testAjax').html(result);
}
});
}
Thanks alot for your help.
When I need to do some operations and I don't want to reload the page I use a JQuery call to Ajax, I make the pertinent operations in AJAX and then receive the AJAX response in the JQuery function without leaving or reloading the page. I'll make an easy example here for you to understand the basics of this:
JQuery function, placed in the template you need
function form_post(){
//You have to get in this code the values you need to work with, for example:
var datastring = $form.serialize();
$.ajax({ //Call ajax function sending the option loaded
url: "/ajax_url/", //This is the url of the ajax view where you make the search
type: 'POST',
data: datastring,
success: function(response) {
result = JSON.parse(response); // Get the results sended from ajax to here
if (result.error) { // If the function fails
// Error
alert(result.error_text);
} else { // Success
//Here do whatever you need with the result;
}
}
}
});
}
You have to realize that I cannot finish the code without knowing what kind of results you're getting or how do you want to display them, so you need to retouch this code on your needs.
AJAX function called by JQuery
Remember you need to add an url for this Ajax function in your urls.py something like:
url(r'^/ajax_url/?$', 'your_project.ajax.ajax_view', name='ajax_view'),
Then your AJAX function, it's like a normal Django View, but add this function into ajax.py from django.core.context_processors import csrf from django.views.decorators.csrf import csrf_exempt from django.utils import simplejson
#csrf_exempt
def ajax_view(request):
response = []
#Here you have to enter code here
#to receive the data (datastring) you send here by POST
#Do the operations you need with the form information
#Add the data you need to send back to a list/dictionary like response
#And return it to the JQuery function `enter code here`(simplejson.dumps is to convert to JSON)
return HttpResponse(simplejson.dumps(response))
So, without leaving the page you receive via javascript a list of items that you sended from ajax view.
So you can update the form, or any tag you need using JQuery
I know that this can be so confusing at the beginning but once you are used to AJAX this kind of operations without leaving or reloading the page are easy to do.
The basics for understanding is something like:
JQuery function called on click or any event you need
JQuery get some values on the template and send them to AJAX via
POST
Receive that information in AJAX via POST
Do whatever you need in AJAX like a normal DJango view
Convert your result to JSON and send back to the JQuery function
JQuery function receive the results from AJAX and you can do
whatever you need

Ajax send parameters through url

I'm new with ajax and thought i'd be a fun experiment to put into my project. I've created my own lightbox type feature to send a message on a website I'm creating. When the user clicks "Send Message", that's when the lightbox appears, and at the top I'm trying to get it to say "Send message to User", where User is the name of the user they're sending a message too. My lightbox html elements are actually on a seperate webpage, which is why I'm using ajax. this is what I have so far, and can't seem to figure out what the problem is:
user.php page
<div id = "pageMiddle"> // This div is where all the main content is.
<button onclick = "showMessageBox(UsersName)">Send Message</button>
</div>
Note: The username passes correctly into the javascript function, I have checked that much.
main.js page
function showMessageBox(user){
alert(user); // where i checked if username passes correctly
var ajaxObject = null;
if (window.XMLHttpRequest){
ajaxObject = new XMLHttpRequest();
}else if (window.ActiveXObject){
ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
}
if (ajaxObject != null){
ajaxObject.open("GET", "message_form.php", true);
ajaxObject.send("u="+user);
}else{
alert("You do not have a compatible browser");
}
ajaxObject.onreadystatechange = function(){
if (ajaxObject.readyState == 4 && ajaxObject.status == 200){
document.getElementById("ajaxResult").innerHTML = ajaxObject.responseText;
// use jquery to fade out the background and fade in the message box
$("#pageMiddle").fadeTo("slow", 0.2);
$("#messageFormFG").fadeIn("slow");
}
};
}
message_form.php page
<div id = "messageFormFG">
<div class = "messageFormTitle">Sending message to <?php echo $_GET['u']; ?></div>
</div>
Note: When accessing this page directly through the URL, giving it a parameter of u and a value, it displays correctly
Use jQuery.ajax();
http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "GET",
url: "message_form.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
freakish way to do it (old school) :)
anyway i think the problem may be that you are loading an entire html page to a div! meaning tags and stuff, a good way to understand what's wrong would be to use a debugger and see what comes in ajaxObject.responseText.
Hope this helps.
Btw convert to jQuery ajax!! saves you loads of time =)
I believe that you need to add a request header prior to sending your data. So you'd have this:
ajaxObject.open("GET", "message_form.php", true);
ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxObject.send("u="+encodeURIComponent(user));
Instead of what you have.
However, it may be a good idea to allow a library to do this for you. It looks like you already have jQuery loaded, so why not let it handle your AJAX requests instead?
I figured it out after watching some ajax tutorials from bucky :) aka thenewboston. If I'm using the GET method, i just had to add the parameter to the end of the url in the .open function, instead of passing it through the send function (like you would a post method).
if you want to send number of field values using ajax.you can use serilalize function.
Example:
jQuery.ajax({
url: 'filenamehere.php',
type: 'post',
data: $("#formidhere").serialize(),
success: function(data){
..//
}
});

Ajax html response to div

Hi I am printing the ajax html response to div element and giving radio input option to select the file. after selecting the specific file the another div should show the message. but the ajax html response is not working
Jquery script:
$(document).ready(function()
{
$('#upload').ajaxForm({
beforeSubmit: function() {
$('#Analysis').show();
$('#Content_column').hide();
$('#file_list').show();
$('#trait').show();
$('#trait').html('Submitting...');
},
success: function(data) {
var $out = $('#file_list');
$out.html('&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspFile list:');
$out.append('<div id="list">');
$('#list').html(data);
$out.append('</div>');
}
});
});
The output of this script is
<ul class="php-file-tree"><li class="pft-directory">Genotypic<ul><input id="Penotypic" type="radio" name="uploads/Genotypic/" value="uploads/Genotypic/jquery.txt" />jquery.txt<br><input id="Penotypic" type="radio" name="uploads/Genotypic/" value="uploads/Genotypic/marker.csv" />marker.csv<br></ul></li><li class="pft-directory">Other</li><li class="pft-directory">Penotypic<ul><input id="Penotypic" type="radio" name="uploads/Penotypic/" value="uploads/Penotypic/namPheno.csv" />namPheno.csv<br><input id="Penotypic" type="radio" name="uploads/Penotypic/" value="uploads/Penotypic/perl.pl" />perl.pl<br></ul></li></ul>
Jquery script:
$('#Penotypic').click(function() {
var $out1 = $('#trait');
$('#trait').show();
$out1.append('Submitted...');
});
this is not showing anything in the div trait. may be the html response is loading as a tesxt so the #Penotypic is not recognised. please help me to fix this.
Thanku
You have many inputs of id="Penotypic". Make every id unique or use classes as function trigger.
I wouldn't use "/" in the name attribute. See: http://www.w3.org/TR/html401/types.html#type-name
Then try if your ajax script does work. If it doesn't work, try if it works from static page (don't use your first jQuery script, but it's output as a static form). You probably need to bind your event trigger. Use jQuery's on().

How do I Get a URI segment from the CodeIgniter view where an Ajax request is made?

I'm using jQuery to call a method of my "volunteer" CodeIgniter controller from a view called "edit" that takes a single parameter, "id"
The URI of the view is:
volunteer/edit/3
I make the call of my update() method like so:
$.post('volunteer/update', function(data) {
console.log(data);
});
All the method does right now is echo a URI segment:
public function update(){
echo $this->uri->segment(2, 0);
}
What is want is a segment of the URI of the view where update() is called (the "edit" view). Instead, I get a segment of the URI of update(). How can I get a segment of the edit view's URI so that I can use it within the update() method?
You could fetch the referrer URL by using
$_SERVER['HTTP_REFERER']
and than parse it manually to get your segment.
It's not 100% secure, as it can be overriden (its set as an header by the server).
Se more details on this older post
You'll need to pass in the segment value in the POST data of the AJAX call.
Your options are:
1) You can parse the URL w/ JavaScript to determine what the value of the segment is, for example:
<script>
var postData;
// assign whatever other data you're passing in
postData.lastSegment = window.location.href.substr(window.location.href.lastIndexOf('/') + 1);
$.post('volunteer/update', postData, function(data) {
console.log(data);
});
</script>
2) You can use PHP to pre-populate a JavaScript variable in the view that you can then use in the POST
<script>
var postData;
// assign whatever other data you're passing in
postData.lastSegment = <?php echo $this->uri->segment(2, 0); ?>;
$.post('volunteer/update', postData, function(data) {
console.log(data);
});
</script>
And finally in the update() controller, you can pull out the data out of the POST with $this->input->post() or out of $_POST.

save ajax response to a element that was not on the DOM

I have some results on the page (firts 10), then with a "load more result" button, I send the "id" of the last report to a PHP page.
I'v read here that I have to use .on (because .live is depreciated) so click event on new elements added to the DOM (through AJAX) can work.
My question is ... can I display somehow the content that came through AJAX on a div that was not on the initial DOM ?
$("#jokesWrap").on('click', 'a.share', function(event) {
var joke_id = $(this).attr('name');
var msgbox = $("#success[name='" + joke_id + "']");
$("#post-to-wall[name='" + joke_id + "']").hide();
msgbox.html('<img src="includes/images/load.gif"> Loading...');
$.ajax(
{
type: "POST",
url: "includes/php/ajax.php",
data: "joke_id=" + joke_id,
success: function(msg)
{
if(msg == 'OK')
{
msgbox.html('<img src="includes/images/success.png" /> DONE!');
}
} // function(msg)
}); // ajax
event.preventDefault(); });
This is the HTML part:
<div id="jokesWrap">
<div class="joke" id="1">
<p class="txt">
some text
</p>
<div class="joke-options-bar">
Post to wall
<span id="success" name="1" class="share floatL"></span>
<br class="floatClear" />
</div>
</div>
// the above area comes through loop from the ajax call
PS: Everything is ok: the ajax call (The tetxt is posted to the wall) the #post-to-wall is hidden. The "loding..." and the success message it's not shown.
PS2: the "Loading..." text and success message it's shown when I click on link that was on the DOM before the AJAX call ( because the #success was there)
Any help it's apprecied!
As long as the element exists in the DOM when the success callback of the AJAX is executed, you can use jQuery to select and manipulate it in the same way as you would an element that did exist in the DOM when the page was initially loaded. Or you can use jQuery to create the element as part of the success callback, manipulate it using the response from the AJAX request, then append your newly created element to the DOM in the required position. Something like so:
var div = $('<div/>').attr('id', 'new-div-id').html(data);
$('body').append(div);
That creates a new div, gives it an id of new-div-id, then sets its innerHTML to be whatever data was (assuming data is the name of the variable that contains the response text from the AJAX), then finally appends it as a new child of the <body> tag of the page.
Looking at what seem to be edits to the question: Element IDs (specified with the id attribute) have to be unique throughout the entire document; that includes elements added later as part of an AJAX callback. You can't have multiple elements with an id of success - make them unique by doing away with the name attribute, and adding the value to the end of the id instead, so you'd have success1, success2, etc as your IDs.
Add it to the DOM before writing to it?

Resources