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.
Related
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)
}
})
}
});
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);
});
First of all i am new to php and javascript
I have a web form where users can add multiple contacts ans send to ther server.
Due to some reasons i cant use the normal html elements to store the values ,so i am using an array to store values.
//init array
var contacts = new Array(); //contact array
var tempArray = new Array(); //temp array to store current contacts
//getting the contact info and setting to a temp array
tempArray = {
name:"username",
age:12,
sex:false
};
//push the content to the `contacts` array
contacts.push(tempArray);
I added many contacts to the contacts array and now i need to submit the array to server.
Problem
I am using Codeignitor and Malsup FORM plugin.
as per malsup i can configure the data option like this
var options = {
dataType:'json', //type of data
data:[contactArray:contacts], //additional parm
};
and on ajaxSubmit option i can give this option as a parm.
when i do this i am getting the following error
uncaught exception: [Exception... "Component returned failure code: 0x80460001 (NS_ERROR_CANNOT_CONVERT_DATA) [nsIDOMFormData.append]" nsresult: "0x80460001 (NS_ERROR_CANNOT_CONVERT_DATA)" location: "JS frame :: /js/form.js :: fileUploadXhr :: line 224" data: no]
temp/jquery.min.js
Line 4
IT WORKS with $.POST in jQuery.
so i tried the JSON.stingify() to convert the data to string.
but on server i am getting like this
'contactArray' => string '[{"name":"username","sex":"12","sex":"false"}]'
If i used the json_decode then i cant use the form validation.
I want to use the FORM VALIDATION LIBRARY IN CODEIGNITOR.
CI supports validation of array of elements.
so
if i get something like name[],age[],sex[] then i can validate easily.
Please help me to solve the problems or give me suggestions.
Thank you.
This code does not create an array:
tempArray = {
name:"username",
age:12,
sex:false
};
It creates an object (completely overwriting the blank array you assigned to tempArray earlier).
if i get something like name[],age[],sex[] then i can validate easily.
If you want, you can create post data that would look like that, as a prep step prior to sending in your data. It's fairly easy::
function prepContacts(contacts) {
var result = []; // Build up string in array, we'll join at the end
var nameKey, ageKey, sexKey;
// I've put [] in these because you use PHP
nameKey = encodeURIComponent("name[]");
ageKey = encodeURIComponent("age[]");
sexKey = encodeURIComponent("sex[]");
for (index = 0; index < contacts.length; ++index) {
contact = contacts[index];
result.push(nameKey + "=" + encodeURIComponent(contact.name));
result.push(ageKey + "=" + encodeURIComponent(contact.age));
result.push(sexKey + "=" + encodeURIComponent(contact.sex));
}
return result.join("&");
}
Then post that via $.ajax:
$.ajax({
url: "/path/to/resource",
type: "POST",
data: prepContacts(contacts),
success: function(response) {
// POST worked, but you have to check response for whether
// it worked at the logic level
},
error: function() {
// POST failed
}
});
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.
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).