Ajax jQuery post troubles - php

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/

Related

How to set the ajax success result value to PHP variable in same page

function submitID(){
// some codes working in here....
var text="A_1";
var name="test";
$.ajax({
url: 'callmethod.php',
type: 'post',
data: {'action':'methodname', 'text': text, 'name':name},
success: function(data, status) {
var results = JSON.parse(data);
for(var i = 0; i < results.length; i++){
var id= results[i]['ID'];
alert(id); --- I got the value of ID in here -- example output value : Hello
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
});
}
What I would like to do in here, I got the value of var id but I want to set as the PHP variable $valuephp= >>> id <<< how can I do for that? please help me to advice.
In short, its not possible, like that to set ajax response to php variable because
PHP runs - Server Side before page load and builds the page
JS (and thus AJAX) runs - Client Side AFTER the server gave your browser the page
So what you can do ?
You post data to your server with your ajax call, so in server side, you can set php variable.You can store this in a session variable if you need it later, or in the database.
You can store ajax result in php variable by embedding ajax result div into php tag.
Assign ajax response variable to js variable and then just assign it to your html div containing php variable as:
$('#result').text('test');
<?php
$result='<div id="result"></div>';
// Here you embed div in php tag and store in php varible
?>
In your ajax call, after success or error
<?php $variablephp = "<script>document.write(111)</script>" ?>
Now you can access that variable, make sure that variable actually used after ajax call
<?php echo $variablephp; ?>

Send serialized form data as well as other data with jQuery post()

I am trying to send my form data as well as a page number (for pagination) in a single post(), unfortunately I can't get it working. Here is the code and it doesn't run with the {name : data} tag included. It runs fine with it removed but obviously the pagination doesn't work. Anybody know how I can send the serialized form data as well as some information from a variable?
$(document).ready(function(){
//set initial page to zero
var pageRequest = 0;
$('.datepicker').datepicker();
$('#search_text').keyup(function(){
$('#test_form').submit();
});
//assign current page number to variable and get a new page
$('#page-links').on('click', '.page-indv', function(){
var pageRequest = $(this).attr('id');
$('#test_form').submit();});
//Send form data and page number, recieve JSON results
$('#test_form').submit(function(){
$.post(
$(this).attr('action'),
{pgeNmbr : pageRequest}, //works fine with this line removed
$(this).serialize(),
function(data){
$('#results').html(data.html);
$('#page-links').html(data.page);
},
"json"
);
return false;
});
$('#test_form').submit();
});
use
..
$(this).serialize()+'&pgeNmbr='+pageRequest
..
serialize() returns param=value&param=value etc, so you just have to add the pageRequest at the end.
I realized the answer (if it still not working) : Change the line
var pageRequest = $(this).attr('id');
to
pageRequest = $(this).attr('id');
There is a scoping problem here, var pageRequest = 0; on the top, as a global variable, but you assign pageRequest as a new local variable inside the click-event by using var, which is not visible outside - and it is the "global" pageRequest you want to change for use in your submit().

jquery each json variable bug

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

Pass a variable from a get query in javascript

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);
});

jquery php issue

Hey everyone. This one is puzzling me. I'm using PHP and Jquery. I am making an ajax request to a PHP file containing a get url. Eg. Path/to/file/?ID=369
The request goes out fine, I've watched it in fire bug.
However in the PHP file, the ID variable doesn't exist. When I do
var_dump($_GET)
I can see that there are two arrays inside the GET array. These are JSON and action.
Can anyone explain to me what's going on here and how I can receive my ID variable?
here are my codes:
<?php
$program_price_id = $_GET['id'];
$programDepatures = getProgramDepaturesGreaterThanToday($program_price_id);
echo "[{optionValue: 0, optionDisplay: 'Select a date'}";
while ($programDepartureData = mysql_fetch_array($programDepatures)) {
echo ", {optionValue: ".
$programDepartureData['id'].", optionDisplay: '".
tidyDateEnglish($programDepartureData['departure_date'])."'}";
}
echo "]";
?>
Best wishes,
Mike
i think you need to specify the ajax method you are using.It might be a $.ajax, $.get or $.getJson.
but i use $.ajax and here is a snippet
$.ajax({
url:"event/service_ajax_handler.php",
type: "GET",
data: {action:"getTime"},
dataType : "json",
success: function(data) {
$("#cmbTimeRange").html("<option value='-1'>Please select time range</option>");
$.each(data, function(){
$("#cmbTimeRange").append("<option value='"+ this.id +"'>" + this.hours +"</option>")
});
},
error: function(){
alert("error");
}
});
pay attention to the data parameter. see also
getJSON
This may be obvious, but I noticed in the sample URL you have ID capitalized, but in your PHP code you have it lowercase. PHP is case sensitive, so it could be as simple as that.

Categories