PHP and JQuery Post communication errors - php

Ok, so i tried multiple of solutions but nothing seems to work for me, (or i'm just too stupid to get it).
I have such jquery code:
Jquery:
var current_id = $(this).attr("id");
var dataString = {"id" : current_id};
$.post("popup.php" , {"id" : $(this).attr("id")}, function(msg) { alert(msg);} );
I know few lines are useless here but i tried all options,
PHP:
$tmp = $_POST['id'];
if($tmp == "kontakt"){
echo '<p>UDANE PRZESŁANIE</p>';}
else{
echo '<p>NIEUDANE PRZESŁANIE</p>';
}
When i click on id=kontakt php returns error :
Notice: Undefined index: id in D:\***\popup.php on line 2
but alert sends back
<p>UDANE PRZESŁANIE</p>
Edit:
Ok, Maybe i haven't make my question clear. I don't care if php error is shown or not, I just want to know why it shows up in the first place.

It's just a PHP warning - it's basically saying that $_POST has no index called 'id'.
You can get rid of it in several ways...
A shorted version of Austin Allover's answer:
if(!isset($_POST['id')) $tmp = '';
Turn of warnings in your script or your php config file, see: http://php.net/manual/en/function.error-reporting.php (Look for E_WARNING)
You might also want try $.post("popup.php" , {"id" : "BLAHBLAHBLAH"}, function(msg) { alert(msg);} ); - just in case $(this).attr("id") doesn't contain anything...

Declare $tmp var this way:
$tmp = (isset($_POST['id'])) ? $_POST['id'] : "";
Or ...
if(isset($_POST['id'])) { $tmp = $_POST['id']; } else { $tmp = ""; }
If you don't understand what this code does...
if post id is set, then declare $tmp as the post id, else set $tmp as "". This will take away the PHP notice.

Related

Undefined Index error when trying to pass Jquery variable to PHP

This is my Jquery:
var data = '[sh][co][img]';
$.post('../php/forms/postdata.php?type=imgadder&c='+code+'&part=partone', 'partone=' + data, function (response) {
$('#body-text').insertAtCaret(response);
});
var datatwo = ''+linko+'[s][/s][/img][ctr][/ctr][/co][/sh]';
$.post('../php/forms/postdata.php?type=imgadder&c='+code+'&part=parttwo', 'parttwo=' + datatwo, function (response) {
$('#body-text').insertAtCaret(response);
});
I get an error "Undefined Index Error" but the index exists, because it prints correctly!
Why is this error message showing when the variable exists?
$partone = e($_POST['parto']);
$parttwo = e($_POST['partt']);
You are trying with wrong index. It should be
$partone = e($_POST['partone']);
$parttwo = e($_POST['parttwo']);
Note : Also, I think you are trying to get both at the same time, where you have two different requests for each one. When you are sending partone, you are not sending parttwo, and vice versa. So you need to handle it differently.

GET via Ajax, exists but undefined

I'm struggling so hard with a very silly bug. I send a form via Ajax with POST but since I also wanted a GET variable, I put it in the url.
I have something like:
var xhr = getXHR();
var id = <?php echo $id ?>;
var xhrUrl = 'request_performupdate?id='+id;
Then, in the performupdate function I have :
if($_GET)
{
$a = fopen('get.txt','w');
$test=$_GET['id'];
fwrite($a,'idlol:'.$test);
}
$id=$test;
But here, the file get.txt is well written with the correct value, but I get a notice error saying $test (the second one) doesn't exist... That's unbelievable ! Hope you will have an idea, thanks very much.

What's wrong with this database call?

-Issue Still Unresolved-
I'm trying to call a database, put all the rows of a table in an array, pass that table to my JS as json data, and then use that data as parameters for a function.
When I run the script nothing happens. I don't get any errors in the console, the rest of the script loads normally. I'm pretty new to mySQL and PHP, what am I doing wrong here? I suspect that I goofed up the php somehow.
XAMPP server, being tested on my desktop
all linked files are in the same directory
There are no visible errors displayed anywhere. As far as I can tell, the script doesn't even try to load the PHP to begin with, but also doesn't display an error in firebug's console
Attempted:
Renaming the table without spaces
placing the for loop inside the callback function
amending php errors
Here's the updated JS I'm using:
this.taskMenu = function()
{
var table = [];
$.getJSON("taskMaster.php", {"table" : "firstlist"},
function(data)
{
table.push(data);
for(i=0; i<table.length; i++)
{
var taskId = table[i].taskName.replace(/\s+/g,"") + i;
formatTask("interface",taskId,table[i].taskName,table[i].taskDescription,table[i].taskComplete);
}
});
}
and here's the updated PHP:
error_reporting(E_ALL); ini_set('display_errors','On');
$con = mysql_connect("localhost", "root", "m3648y73");
if (!$con){die('Could not connect: ' . mysql_error());};
mysql_select_db("tasklistdb", $con);
$table = $_GET['table'];
$sql = mysql_query("SELECT taskName, taskId, taskDescription, taskComplete FROM `".$table."`");
$listTasks = array();
while ($row_user = mysql_fetch_assoc($sql))
$listTasks[] = $row_user;
echo json_encode($listTasks);
mysql_close($con);
Am I linking to the DB correctly?
getJSON is asynchronous call. So before it could fetch values from PHP and execute the callback function, it moves to the for loop and here table is empty.
Solution: shift your for loop inside the callback function
You are missing a semi colon on the line $listTasks = array() in the php file
This happens because js-code after async request executed earlier than request itself is over. Try this:
this.taskMenu = function()
{
var table = [];
$.getJSON("taskMaster.php", {table : "first list"},
function(data)
{
table.push(data);
for(i=0; i<table.length; i++)
{
var taskId = table[i].taskName.replace(/\s+/g,"") + i;
formatTask("interface",taskId,table[i].taskName,table[i].taskDescription,table[i].taskComplete);
}
});
}
Your table name can't be 'first list'
You can't have a space in a MySQL table name.
Also you should put put table in the JSON value in double-quotes like {"table":"table_name"}

Undefined index when posting to php

thisBtn = $(this);
parent = $(this).parent();
num = parent.data('num');
var id = parent.attr('id');
if(typeof num != 'number'){
num = 0;
}
$(this).attr('disabled', true);
$.post('javas.php', {num: (num+1), id: id}, function(data) { console.log('Ajax success');
parent.next('.status').html(data);
thisBtn.attr('disabled', false); // reset });
console.log('Ajax success');
parent.data('num', ++num);
parent.next('.status').html(data);
thisBtn.attr('disabled', false); // reset
I am trying to send the variable id to a php page (javas.php). However I am receiving an undefined index error but I am not sure why, I am retrieving the I on javas.php with the $_POST method and num is being sent correctly with no error, any help is appreciated. Thanks.
validate that
var id = parent.attr('id');
returns something other then undefined, as if it is undefined it wont get sent.
Use Firebug to check what data is being sent over. Without being able to see the code, it's hard to be sure, but it looks like a scope issue - parent is global whereas id is local.
The error is because you are trying to access an element of an array that doesn't exist... Presumably the $_POST array.
The reason for the element not existing is likely either a typo in your php code (double check that you have typed the key correctly), or your post parameters in the JavaScript are incorrect (again, likely a typo).

JQuery .post method problem with comma in php

This Works fine and count returns 2:
$request_ids="166409183417843,1913616994605";
$sent = explode(',',$request_ids);
$count = count($sent);
But when using Jquery to post to another page sent var returns only the last id and count returns 1.
Page of origion:
$(function(){
$.post("process_ids.php", { request_ids: response.request_ids } );})
process_ids.php file:
$sent = explode(',', $_POST['request_ids']);
$count = count($sent);
I also checked with alert() the value of response.request_ids value and it's the same.
Something is totally screwed here, what's wrong?
I hate answering my own question but it's better than no answer.
The problem was like some mentioned above - the data type of the variable.
I simply cast the string to it before sending:
$(function(){
$.post("process_ids.php", { request_ids: String(response.request_ids) } );
return false;
});

Categories