I am trying to pass the value of a parameter outside a $.get jQuery in javascript. I read that I should somehow do that in synchronous mode but I couldn't find a solution.
Here is my code:
var flag;
var t = $.get("mutalyzer.php?id="+variation.value, function(data) {
flag=data;
});
document.write(flag);
where I get undefined as a result.
Thanks!
write it inside the callback function
try this
var t = $.get("mutalyzer.php?id="+variation.value, function(data) {
//this is the callback function and runs when get gets completed
flag=data;
document.write(flag);
});
Related
I am having trouble with a bit of code that uses the ajax $.post function to send a name to a php file which then does some stuff with it. I believe the issue to be in the ajax code, because I have found that the posted value never makes it to the $_POST array (i.e. the $_POST array is not set). However, I do not think that there are any syntactical mistakes on either end, so I am confused as to why it does not work.
Here's the jQuery.
if ($(e.target).hasClass('shootNames')) {
var shootName = $(e.target).attr('id');
var par = $('#' + shootName).parent().attr("id");
$.post("displayImages.php", {shoot: shootName}); //the information I would like to send
$('#' + par).load("displayImages.php").off('click', $('#' + par));
}//end if hasClass
And the relevant bit of php.
if (isset($_POST['shoot'])) {
$shootname = $_POST['shoot'][0]; //pick out just the first member of the $_POST array
$filepath = "images/u/$foo/$shootname";
$f->FilesAsImages($filepath);
}//end if
Thanks for any help.
You're hitting displayImages.php once in your $.post call and there it should return your image, but you don't have a success handler in there, so it does nothing with the result. You're then hitting displayImages.php again with .load and not passing it anything, so it does nothing as expected. Adding a success handler to your $.post call and doing the work in there, will do what you want.
See the $.post documentation for more: http://api.jquery.com/jquery.post/
Sample code:
if ($(e.target).hasClass('shootNames')) {
var shootName = $(e.target).attr('id');
var par = $('#' + shootName).parent().attr("id");
$.post("displayImages.php", {
shoot: shootName
}, function(data, textStatus, jqXHR) {
// this is the success function and the 3 arguments it gives you, remove the 2nd/3rd if you don't use them
$('#' + par).html(data).off('click', $('#' + par));
});
}
Try change from this
$.post("displayImages.php", {shoot: shootName}); //the information I would like to send
to this
$.post("displayImages.php", {'shoot[]': shootName}); //the information I would like to send
Source :
http://api.jquery.com/jquery.post/
I have a strange bug. When I try to run my code:
var firstJson;
$.getJSON(site_url+"/more/sector_by_city/"+id+"?"+Math.random(), function( json ) {
$.each(json, function(key, value) {
firstJson = 9;
});
});
alert(firstJson);
The alert I get is: "undefined".
Why did I get this instead of getting 9?
What am I missing here?
(the each loop runs without issue and there are values in the JSON)
At the end, 9 changes to some other value.
Thanks
Async functions my friend. Your alert is being called before your .getJSON request has been finished. You'll need to use a callback function to get the correct alert.
Because when you call alert(firstJson) the asynchronous $.getJSON call has not yet completed, so firstJson has no value associated with it. If you move your alert into the $.each function or after the $.each, and at the end of $.getJSON, it will have a value.
The variable doesnt have a value when alert is called. You'll have to wait getJSON is over, using done().
var firstJson;
$.getJSON(site_url+"/more/sector_by_city/"+id+"?"+Math.random(), function( json ) {
$.each(json, function(key, value) {
firstJson = 9;
});
}).done(function() {
alert(firstJson);
});
References:
done()
$.getJSON
I have a PHP page that uses a jQuery ajax call.
After I execute my AJAX and return a value on success, I need to use this value to pull an item from a PHP array, stored in session and update my SPAN with the new set.
Here's what I've got so far. I tested and I do return correct data value. I guess my syntax in jQuery is off, because my original span fades out, but nothing comes back.
JS:
$.ajax({
...
},
success: function(data){
var nextItem = <?php echo $_SESSION['items'][data]->desc; ?>
$('.x').fadeOut();
$('.x').attr(id, data);
$('.x').text(nextItem).fadeIn();
});
HTML:
<span id="'.$_SESSION['items'][0]->id.'" class="x">'.$_SESSION['items'][0]->desc.'</span>
You should return the session variable in the AJAX call. Execute the PHP code to get the session variable on the URL your AJAX call is hitting. The response of the AJAX call (in this case the 'data' variable in your success function) will be the result of:
<?php echo $_SESSION['items'][data]->desc; ?>
So no PHP code will be in your JS.
If you need to return multiple values, then you might consider using JSON. Your AJAX processing page might be like:
$result = array('id' => $id, 'session' => $_SESSION['items'][$id]->desc);
echo json_encode($result);
Your JS might look like this:
$("#getJSON").click(function() {
$.ajax({
...
success: function(data) {
$obj = $.parseJSON(data);
console.log($obj[0].id, $obj[0].session);
}
});
});
I want to pass the id of the INPUT field to the PHP file providing options. Here's my HTML & jQuery code. But the PHP program gets the id as undefined. Thanks for helping.
jQuery :
$('.classfield').autocomplete({
//define callback to format results
source: function(req, add){
//pass request to server
$.getJSON("ajax/ajax_suggestions.php?id="+$(this).attr('id')+"&callback=?", req, function(data) {
//create array for response objects
var suggestions = [];
//process response
$.each(data, function(i, val){
suggestions.push(val.name);
});
//pass array to callback
add(suggestions);
});
},
//define select handler
change: function(e) {
$("#spill").html("change "+$(this).val()+e.type);
}
}); // autocomplete
HTML:
<input type="text" class="classfield" id="hello" value="there"></input><br>
the value of $(this).attr('id') is undefined because this is the object that is put in the parameter of autocomplete (the parameter of autocomplete accepts an object, so if you use $(this).attr('id'), you are referencing the object that was passed in the parameter on the autocomplete)
therefore you cannot use $(this).attr('id').
You have to store the id of the text field, may be as a global variable... Hope this helps a little bit
Try getting the id from this.element:
//pass request to server
$.getJSON("ajax/ajax_suggestions.php?id="+this.element.attr('id')+"&callback=?", req, function(data) {
Also see this example.
I'm a stuck with the following function:
<script type="text/javascript">
function removeElement($parentDiv, $childDiv){
if (document.getElementById($childDiv)) {
var child = document.getElementById($childDiv);
var parent = document.getElementById($parentDiv);
parent.removeChild($child);
}
}
</script>
x
This function deletes a child element, and its content, which works great client-side! But I am wanting to pass a value to the server, in the same instance, so the content of the element can be deleted from the mysql database too. I have no idea how to do this, so any suggestions will be very appreciated!
Notes: $child, and $parent are strings generated within the php file, that I use to give each element a unique ID.
To make your life easier, use jQuery or similar framework. Here's how you would do it in jQuery:
$(function() {
$('.delete').click(function() {
var link = $(this);
var id = link.attr('id').replace('element_', '');
$.ajax({
url: 'handler.php',
data: {
element: id
},
type: 'post',
success: function() {
link.remove();
// Or link.closest('tr').remove() if you want to remove a table row where this link is
}
});
return false;
});
});
The HTML:
Remove
And handler.php:
mysql_query("DELETE FROM `table` WHERE id = '".mysql_real_escape_string($_POST['element'])."'");
Always remember to escape database input!
If you're a total noob as you said, you probably won't understand all of this so I suggest you read something about jQuery's AJAX capabilities and about overall development using jQuery or similar JavaScript framework.
Lets say I want to delete an entity using a ID
JQUERY - $.post()
This is an easy way to send a simple POST request to a server without having to use the more complex $.ajax function. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code). Jquery post docs
On the server assuming you have an open database connection.
mysql_query("DELETE FROM TABLE WHERE ID = ".$_POST['ID']);
more on mysql_query found here
EDIT:
So the following will only remove the element when the ajax post is complete. Note the first arg is the url to the script that will take the action , second is the data to be sent, in this case the ID post value will be {child.id} and the third is a anon inline callback function that will take action to remove the element client side.
<script type="text/javascript">
function removeElement($parentDiv, $childDiv){
if (document.getElementById($childDiv)) {
var child = document.getElementById($childDiv);
var parent = document.getElementById($parentDiv);
$.post('{URLTOSCRIPT}', 'ID=$child.id',function () { parent.removeChild($child); });
}}
</script>
When you call the function, you'd want to put your PHP variables in tags like so:
<?php echo $parent; ?>
and
<?php echo $child; ?>
In the function definition, you will want to get rid of the PHP style variables and use something like:
function removeElement(parentDiv, childDiv) {
//CODE
}