So this stems from a problem yesterday that quickly spiraled out of control as the errors were unusual. This problem still exists but the question was put on hold, here, and I was asked to reform a new question that now relates to the current problem. So here we go.
The problem is basic in nature. If you were helping yesterday I have switched from a $.post to an $.ajax post to deliver a variable to my PHP file. However my PHP file seems to never receive this variable stating that the index is 'undefined'.
Now this would normally mean that the variable holds no value, is named incorrectly, or was sent incorrectly. Well after a full day of messing with this (kill me) I still see no reason my PHP file should not be receiving this data. As I'm fairly new to this I'm really hoping someone can spot an obvious error or reccommend another possible solution.
Here's the code
jQuery
$('#projects').click(function (e) {
alert(aid);
$.ajax({
url:'core/functions/projects.php',
type: 'post',
data: {'aid' : aid},
done: function(data) {
// this is for testing
}
}).fail (function() {
alert('error');
}).always(function(data) {
alert(data);
$('#home_div').hide();
$('#pcd').fadeIn(1000);
$('#project_table').html(data);
});
});
PHP
<?php
include "$_SERVER[DOCUMENT_ROOT]/TrakFlex/core/init.php";
if(isset($_POST['aid'])) {
$aid = $_POST['aid'];
try {
$query_projectInfo = $db->prepare("
SELECT projects.account_id,
projects.project_name,
projects.pm,
//..irrelevant code
FROM projects
WHERE account_id = ?
");
$query_projectInfo->bindValue(1, $aid, PDO::PARAM_STR);
$query_projectInfo->execute();
$count = $query_projectInfo->rowCount();
if ($count > 0) {
echo "<table class='contentTable'>";
echo "<th class='content_th'>" . "Job #" . "</th>";
echo "<th class='content_th'>" . "Project Name" . "</th>";
//..irrelevant code
while ($row = $query_projectInfo->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
echo "<td class='content_td'>" . "<a href='#'>" . $row['account_id'] . "</a>" . "</td>";
echo "<td class='content_td'>" . $row['project_name'] . "</td>";
//..irrelevant code
echo "</tr>";
}
echo "</table>";
}
} catch(PDOException $e) {
die($e->getMessage());
}
} else {
echo 'could not load projects table';
}
?>
When I run this code by pressing '#projects' I get 2 alerts. This first alert says '6', which is the value of the variable 'aid' and is expected. The second alert is blank.
Now here is where I get confused. If the post is being sent with a value of 6. Isn't the $_POST['aid'] set? Also if that's true shouldn't my code execute the if portion of my conditional statement rather than my else?. Either way this strikes me as odd. Shouldn't I receive something back from my PHP file?
So in Firebug we trust, right? If I open up Firebug and go through like this
Firebug -> POST projects.php -> XHR -> POST(tab) ->
I see 6 in the 'Parameter' window and '6' in the 'Source' window. Then if I click the 'Response' and 'HTML' tabs they both hold no value.
So anyways, that wall of text is my problem. Again, I'm really hoping someone can help me out here. I would hate to waste anymore time on what should be a simple solution.
EDIT
If I change my php file to look like this
<?php
if(isset($_POST['aid'])) {
$aid = $_POST['aid'];
echo $aid;
} else {
echo 'fail';
}
The response is now '6'! Hooray! We made a breakthrough! Now why won't it load my table that results from my query?
side note
This should of been noted originally if I take away the
if(isset($_POST['aid'])){
//all my code
} else {
//response
}
and just hard code the variable $aid like this
$aid = '6';
Then run the PHP file directly the query is successful and the page loads the table its dynamically creating.
Also in response to one of the answers asking me to use
$('#projects').click(function (e) {
alert(aid);
$.ajax({
url:'core/functions/projects.php',
type: 'post',
data: aid,
success: function(data) {
// this is for testing
}
}).error (function() {
alert('error');
}).complete (function(data) {
alert(data);
$('#home_div').hide();
$('#pcd').fadeIn(1000);
$('#project_table').html(data);
});
});
I was using that, but I'm using jQuery v1.10.2 and according to this those methods are or will be deprecated. Either way it made 0 difference in the outcome.
Anyways the question is now. Why is it if I used the simple version I get echo'd back my $aid variable of '6'. However when I try and run my query with it I get nothing. Also please try to remember if I hard code the 6, the table creates.
I think this may be the error:
data: aid,
it should be
data: {'aid':aid},
That will provide the $_POST['aid'] label and value you're looking for in your php page.
EDIT:
If you're having trouble with this, I'd simplify it for testing, the main reasons for things like this not working in my experience are:
it's not reaching the file
it's reaching the file but the file's expecting something different than it's receiving and due to control structures it's not returning anything
it's reaching the file with the correct data, but there are other errors in the php file that are preventing it from ever returning it.
You can easily rule out each of these in your case.
The jQuery data parameter to the ajax method should be an object, such as {'aid': aid}. I think that's your problem. I also noticed your always method is missing a parameter for data.
If you're now posting the data correctly could the problem be in your PHP page?
The init.php include couldn't be changing the value of $_POST['aid'] could it?
I'm not sure done is suppose to behave like that, normally you use done like this:
$.ajax({
//...
})
.done(function(data){
//...
});
Just do it like this:
var fetch = true;
var url = 'someurl.php';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'aid' : aid
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
}
},
complete : function(data)
{
// do something, not critical.
}
});
You can add the failure part in if you want. This is, anyway, guaranteed to work. I'm just not familiar enough with done to make more comments about it.
Try
include "{$_SERVER['DOCUMENT_ROOT']}/TrakFlex/core/init.php";
instead cause $_SERVER[DOCUMENT_ROOT] witout bracket won't work. When you are using an array in a string, you need those brackets.
Since some browsers caches the ajax requests, it doesn't responds as expected. So explicitly disabling the cache for the particular ajax request helped to make it work. Refer below:
$.ajax({
type: 'POST',
data: {'data': postValue},
cache: false,
url: 'postAjaxHandling.php'
}).done(function(response){
});
Related
I have tried searching through SO for an answer to my issue, but all the posts I find still aren't helping me resolve my issue. I don't know if I am overlooking something or if it's just my lack of knowledge that is preventing my code from working.
I have two JS prompts that ask for an ID and then an amount to adjust my stock level. I want it to pass that along to my php file to run a mysql update query.
My script:
<script type="text/javascript">
function sendArray()
{
var ourObj = {};
ourObj.itemId = prompt("Scan ID:");
ourObj.adjAmt = prompt("Enter amount:");
alert(ourObj.itemId);
alert(ourObj.adjAmt);
$.ajax({
url: "save.php",
type: "POST",
data: { invAdj : JSON.stringify(ourObj)},
success: function(response)
{
alert("data sent response is "+response);
},
error: function(e)
{
alert("data not sent"+e);
}
});
}
</script>
<button onclick="sendArray();">Send Array</button>
My php:
if(isset($_POST['invAdj'])) {
$invAdj = json_decode($_POST['invAdj']);
$itemId = $invAdj->itemId;
$amtAdj = $invAdj->amtAdj;
}
mysqli_query($link, "UPDATE stock_levels SET stocklevel = stocklevel + " . $amtAdj . " WHERE id = " . $itemId);
?>
Presently, I get a successful alert, but the level does not change in the db. I know that the db info works and the sql query works because if comment out the post block an add solid variables, it runs perfectly. I have something screwed up in the POST block.
Any help would be greatly appreciated! Again, sorry if this has been answered, but I couldn't find a post that worked...
Also, I know that I shouldn't put the SQL directly into my query. I am just trying to get this working first.
Thanks
This is the first time I am working with CI+AJAX+JSON.
I have a controller Admin.php inside controllers directory of Codeigniter. The controller code is as under:
public function getmylist()
{
$users_arr[] = array("sno" => "1", "myname" => "hello");
echo json_encode($users_arr);
}
Then, in views, I have a view with the following code:
<select class="form-control" name="mod_countries" id="mod_countries">
<?php
if(isset($countrylist))
foreach($countrylist as $c)
echo "<option value=" . $c->cname . ">".$c->cname;
?>
</select>
Then my target select which i need to populate from ajax is
<select class="form-control" name="mod_newlist" id="mod_newlist">
</select>
My ajax is as under:
$(document).ready(function() {
$('#mod_countries').change(function(event) {
var cname = $("select#mod_countries").val();
alert(cname);
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>" + "Admin/getmylist",
dataType: "json",
data: {mcname: cname},
success: function(res){
if(res) {
var len=res.length;
$("#mod_newlist").empty();
for(var i=0; i<len; i++)
{
var sno=res[i]['sno'];
var myname=res[i]['myname'];
$("#mod_newlist").append("<option value='" + sno + "'>"+myname+"</option>");
}
}
else
{
console.log('hitting');
}
},
error: function(res, status, error) {
var err = res.responseText;
alert(res.Message);
alert(status);
alert(error);
}
});
});
});
When I select an item from the first dropdown list, I get the selected item. Now I expect the second drop downlist to get an item from the controller's code. but, my code goes into error block and alert shows following error messages for each alert line of code:
undefined
parsererror
SyntaxError: Unexpected token I in JSON at position 0
Please tell me where I am making a mistake?
Also, please help with regards to how should I return the sno->name pair from model because at lat, i want to populate the new select from database.
Remove debug/garbage data from response, like I am called. If still not work then parse JSON in success as following
var res = $.parseJOSN(res);
if(res) {
.....
You are not passing data correctly.
it should be like
data:{
"key" : value
//use " " to encapsulate string values, only in case of variable You pass value without ""
}
I am using CodeIgniter for last two months now. And earlier I had a lot of trouble working with ajax. But my friend suggested me to use AngularJs. It took me just one day to learn Angular and it turned out to be extremely helpful.
It will save a lot of time. And make your work so easy. At first, it may sound difficult but if u spend some time coding then it is going to make your life a lot better. I learned it from JavaTpoint.com and it was very well explained.
Do not try to understand everything at once and practice as you learn.
I'm building a search function to retrieve XML data for a google map.
In addition to that, I want to display how many results were actually found.
I thought about doing an echo inside the actual document, however that might mess with my marker data. How would I take a PHP variable and retrieve it in Jquery after a success call?
If my PHP looked like this:
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$num_rows = mysql_num_rows($result);
And Jquery like this:
$.ajax({
type: "POST",
url: "MapSearchxml.php",
data: {
dataFromDate: FromDate,
//lalala
dataHasPatio: HasPatio
},
beforeSend: function (html) { // this happens before actual call
$("#results").html('Please Wait');
$("#searchresults").show();
$(".phpFromDate").html(FromDate);
},
success: function (data, status, jqXHR) {
//Success?
},
dataType: 'xml'
});
Might find it easier to create array in php and send JSON. At client is easy to loop over response object/array
$output=array('status'=>'', 'results'=>array());
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$num_rows = mysql_num_rows($result);
if( $num_rows){
$output['status']='ok';
/* push row data to $output['results'][]; in while loop*/
}else{
$output['status']= 'No results';
}
echo json_encode( $output);
Then in jQuery:
success:function( data){
if (data.status != 'No results' ){
/* count array length*/
var count= data.results.length;
/* loop over data.results array*/
}
}
/* change dataType to "json"*/
I forgot about count and added it in jQuery...can also add a count property to the $output php array and use $num_rows to populate
Just trying out a JSON example for you, this has echo but you can do complex things with it?
Not sure if that is what your after? I get that you don't want to do echo on each variable, and you wont if using JSON.
<?php
$simple = 'simple string';
$complex = array('more', 'complex', 'object', array('foo', 'bar'));
?>
<script type="text/javascript">
var simple = '<?php echo $simple; ?>';
var complex = <?php echo json_encode($complex); ?>;
</script>
You see, what AJAX gets on success is an html code. If you AJAX a complete html page you will get it back, starting with <html> and ending with </html>. You can just make a special markap on your return html data, like [sepcial_info : 'INFO'] or somthing and then just to filter it.
Okay, I needed a bit to decipher your question, probably I'm still wrong, let's try:
What you try to do is not technically possible with what you have in mind. In short: If you do one Ajax request, you return one response. The moment the success function is called, your PHP script is already gone. So you can only pass one return value.
However what you can do is, that you make that return value a nested one, e.g. containing two parts:
The XML document you already returned
The count
That is probably your solution. If you ask how, I would add the count as a namespaced value to the XML and then process it with javascript.
As you have not shown any code here, I can not give a quick example (and I leave that as a pointer for your future questions) for your case. Add a namespace element, like an attribute is pretty simple with DOMDocument in PHP.
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.
I hope you'll able to help me. I'm fed up of trying things without any solution and php it's just driving me crazy. I'm looking for help because I have a html document where I use ajax thanks to jquery api. Inside this file, in a js function I have:
$.ajax({
type: "GET",
url: "c.php",
data: "dia="+matriz[0]+"&mes="+matriz[1]+"&ano="+matriz[2]+"&diaa="+matriz2[0]+"&mess="+matriz2[1]+"&anoo="+matriz2[2]+"&modo=0&semana=0",
success: Mundo,
error: function(e){
alert('Error: ' + e);
}
});
This code allows me to send the information that I want to the file c.php where I have:
include('funciones.php');
include('config.php');
$mierda = array();
$mierda[0] = $_GET['modo'];
$mierda[1] = $_GET['dia'];
$mierda[2] = $_GET['mes'];
$mierda[3] = $_GET['ano'];
$mierda[4] = $_GET['diaa'];
$mierda[5] = $_GET['mess'];
$mierda[6] = $_GET['anoo'];
$mierda[7] = $_GET['semana'];
As you see it's very simple. My crazy problem is that with firebug I've seen that the data is sent well but for some reason I can't use it. I have tried with $_Get, $_post and $_request and always is the same problem. But this can be stranger... If I put:
echo json_encode($mierda);
then miraculously, the php returns the data that I have passed so in conclusion I have:
I can send the data to the php file well
I can print all the data that I have sent well just accessing yo $_GET, $_POST, $_REQUEST
I can't use any value separatly like $_GET['dia']
What's going wrong there?
PS. The include php files are functions that access to my database so there's no interaction with them.
Your data is not URL-encoded. Try do something like this,
$.ajax({ type: "GET",
url: "c.php",
data: {"dia":matriz[0], "mes":matriz[1] ....},
success: Mundo,
error: function(e){ alert('Error: ' + e); }
});
If you are returning a json value use json to read that.
See
http://api.jquery.com/jQuery.getJSON/
http://pinoytech.org/blog/post/How-to-Use-JSON-with-jQuery-AJAX
Here is an example to read json value
$('document').ready(function(){
$('#submit).click(function(){
$.post('your_php_page.php', {employee_id: '456'},
function(data){
console.log(data.first_name);
console.log(data.last_name);
}, 'json');
})
});
Hope it helps
You have a crazy problem. According to your question:
$mierda = array();
$mierda[0] = $_GET['dia']; //... and so on
echo json_encode($mierda);
works while:
echo $_GET['dia'];
doesnt. Try:
$mierda = array();
$mierda[0] = $_GET['dia'];
echo $mierda[0];
echo $_GET['dia'];
It will show you whether the problem is in the PHP, or the javascript.
I have encoded the data as ZZColer said and the error is still.
Starx, it's not a question of the returning.
digitalFresh, in fact the error is from PHP because I can copy $_POST, $_GET array to a new array and print all this information but if I put after all things like:
If( mierda[0] == 0) {... The element is empty! and if I try directly $_GET['dia'] it says that this element doesn't exist in the array. Also I have tried $_GET[dia] or $_GET[0] without a solution.
PD:
I don't know how but PROBLEM SOLUTIONED!
Thanks to all!