Undefined index when posting to php - 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).

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.

Ajax jQuery post troubles

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/

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().

$.ajax()function with json data from javascript array to a php processing file

i trying to use json for the first time with $.ajax() i got the values of checkboxes and other needed data to a php file for processing and posting to mysqldb through an array for the data section of $.ajax() function but would get an empty array[] on my php file. When i try using javascript debugging tool from my browser i got the reprot
**Uncaught SyntaxError: Unexpected end of input jquery-1.9.0.min.js:1
st.extend.parseJSON jquery-1.9.0.min.js:1
(anonymous function) index.php?url=account/registration/:297
st.event.dispatch jquery-1.9.0.min.js:2
y.handle**
the array i produced looks like this at the console log
[checkbox1: "COM 101", semester: "1st Semester", mid: "7", checkbox2: "COM 112", checkbox3: "STA 111"…]
checkbox1: "COM 101"
checkbox2: "COM 112"
checkbox3: "STA 111"
checkbox4: "STA 112"
checkbox5: "MTH 111"
length: 0
mid: "7"
semester: "1st Semester"
on my php processing file i did print_r on the json data but got an Array[] as a result
this is my javascript code block "myDataArray is a global variable"
$('#mytable2').on('change',function(e){
var rel = e.target.getAttribute('rel');
console.log(e.target.value+ " "+ e.target.checked)
if(rel === globals.payment_target && e.target.checked===true){
myDataArray[e.target.getAttribute("name")]= e.target.value;
myDataArray["semester"] = $("#semester").val()
myDataArray["mid"] = $("#mid").val()
}
if(rel === globals.payment_target && e.target.checked ===false){
delete myDataArray[e.target.getAttribute("name")]
console.log(myDataArray)
}
});
$('#mytable2').on('click',function(e){
var rel = e.target.getAttribute('rel');
console.log(e.target.value+ " "+ e.target.getAttribute('name'))
if(rel === globals.payment_target && e.target.value =="Register"){
console.log(myDataArray)
var jsonstring = $.parseJSON(myDataArray);
var myglob =JSON.stringify(globals)
console.log(myglob)
$.ajax({url:'courseregistration.php', type:'POST',data:{data:jsonstring},success: function(result){
$('#putmehere').html("<h4 style='text-align:center'>"+result+"</h4>")
alert(result)
}
})
}
});
and this what the php file looks like
$data = json_decode($_POST['data']);
print_r($data);
i just can't figure out what the problem is. can someone please tell me what is wrong with the way i'm doing it or suggest a better way
Try to set data type property json
$.ajax({
url:'courseregistration.php',
type:'POST',data:{data:jsonstring},
datatype:"json",
success: function(result){
$('#putmehere').html("<h4 style='text-align:center'>"+result+"</h4>")
alert(result)
}
});
Also set content type in php script.
header('Content-Type: application/json');
The reason that your page is not working is the critical error (your first listing). You need to clear up this error before you can do anything else because your form is not being submitted as you want it to.
The reason for the error: maybe a corrupt file - download another copy of jQuery and try again.
i removed this --- $.parseJSON(myDataArray) --- and the error did not come again i used JSON.stringify(myDataArray) instead. also i declared myDataArray as an object instead of as an array and things went fine, it solved the Uncaught SyntaxError: issue
Initially, i declared myDataArray as an array
var myDataArray = new array();
but when i changed myDataArray to Object
var myDataArray = new Object;
i effect it as below and things went fine
$('#mytable2').on('click',function(e){
var rel = e.target.getAttribute('rel');
console.log(e.target.value+ " "+ e.target.getAttribute('name'))
if(rel === globals.payment_target && e.target.value =="Register"){
console.log(myDataArray)
console.log(globals)
var jsonstring = JSON.stringify(myDataArray);
console.log(myglob)
$.ajax({url:'courseregistration.php',dataType:"json", type:'POST',data:{data:jsonstring},success: function(result){
$('#putmehere').html("<h4 style='text-align:center'>"+result+"</h4>")
alert(result)
}
})
}
});

The most strange error in the world (PHP $_GET, $_POST, $_REQUEST and ajax)

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!

Categories