php parsing jQuery form serialize wrong way - php

I have one problem...
These are names of some my html form elements:
name="password"
name="meta[naziv_firme]"
This is my jQuery
var data = {action: 'edit', form: $('input', 'form#edit-klijent-form').serialize()}
console.log(data);
$.get('/index.php/admin-ajax', data,
function(response){
// Success
$('div#edit-klijent-div,.tipsy').hide();
$('div#klijent-edit-success').show();
});
Console.log gives me result:
action edit
form userID=12&password=&password-match=&email=test15%5Bmeta%5Bnaziv_firme%5D=test15&meta%5Bkontakt_osoba%5D=test156&meta%5Bkontakt_telefon%5D=test157&meta%5Bkontakt_email%5D=test158
So everything look OK!
Now in PHP I have var_dump($_GET); and the result is:
string(165) "userID=12&password;=&password;-match=&email=test15&meta;[naziv_firme]=test15&meta;[kontakt_osoba]=test156&meta;[kontakt_telefon]=test157&meta;[kontakt_email]=test158"
Why does PHP put ; after password, in &meta;[... ??
And ideas? What am I doing wrong?
Thank you!

In your HTML form element, add:
<input type="hidden" name="action" value="edit">
And change this line:
var data = {action: 'edit', form: $('input', 'form#edit-klijent-form').serialize()}
Into this:
var data = $('input', 'form#edit-klijent-form').serialize();
Can't really test it since I don't have your HTML or server configuration, but I think it should work.
Update:
To clarify #AnthonyGrist's comment above, let's observe what serialize does:
<form>
<input type="text" name="input1" value="foo">
<input type="text" name="input2" value="bar">
</form>
<script>
var data = $('form input').serialize();
// data is now: 'input1=foo&input2=bar'
</script>
If you assign the value returned above to a query parameter (which PHP accesses using $_GET), you're basically telling PHP that $_GET['form'] equals the string above, which is not what you intended. PHP would not parse the contents of $_GET['form'] to give you $_GET['input1']... The value returned by serialize() should be used as the 2nd argument to $.get() directly.

Change your code from:
var data = {action: 'edit', form: $('input', 'form#edit-klijent-form').serialize()}
To:
var data = "action=edit&" + $('input', 'form#edit-klijent-form').serialize();
I think it is what you're trying to achieve.

Related

Send string to database with Ajax not working as intended

I'm trying to send a simple string to the database. In order to see if I'm half way there, I'm checking to see if $_POST has anything set -- but it doesn't.
Here is my simple form, on an index.php:
<form action="" method="POST">
<input type="text" name="add_item" id="add_item">
<input type="button" value="submit" id="button">
</form>
And here is the AJAX from that form, where the success is triggered:
var add_item;
$('#button').click(function(e){
e.preventDefault();
add_item = $('#add_item').val();
console.log(add_item);
$.ajax({
type: 'POST',
url: 'sendData.php',
data: 'send me!',
success: function(data){
alert('lol');
}
});
});
And on the sendData.php, but there is nothing in the $_POST global:
var_dump($_POST); // returns 0
if (isset($_POST['add_item'])):
$add_item = $_POST['add_item'];
$submit = new Connection();
$submit->connect_db();
$submit->add_to_DB($add_item);
endif;
As you can see, I'm trying to send it to the database; but before that I'm trying to see if anything is in the $_POST global -- but it returns 0.
Would anyone know why? I'm new to this and I can't find any concrete tutorials explaining simply.
Try setting data to something like "testvar=sendme" or simply use a PlainObject
PHP seems to be expecting key-value-pairs for $_POST to work.

Jquery UI Multi datepicker issue on retrieving dates

i am using this http://multidatespickr.sourceforge.net/#method-addDates to enable multiple date select. everything works fine but i am wondering how to get the selected dates to PHP.
below is the html code.
<input type="text" name="outgoing_call_dates" value="" id="outgoing_call_dates_id" class="hasDatepicker">
as you can see value tag is empty always when i add, its normally appending to the end but not value tag is doing the same. please check this image.
Original source : http://multidatespickr.sourceforge.net/#method-addDates (example : From input)
Please help me find a way
HTML
<input id="datePick" type="text"/>
<input id="get" type="button" value="Get" />
JS
$('#datePick').multiDatesPicker();
$('#get').on("click",function(){
var dates = $('#datePick').val();
if(dates !=''){
dataString = 'dates='+dates;
$.ajax({
type:"POST",
url : "URL_TO_PHP_FILE",
data : dataString,
dataType : 'json',
success : function(data) {
alert(data);
}
)};
}
});
PHP
$dates = ($_POST['dates']);
echo json_encode($dates);
value attribute defines default value. If you change the value of input element, it won't be inside source with value="YOUR_ENTERED_VALUE" .
To access value in client side, you can use JS or jQuery.
For example using jQuery:
var dates = $('#outgoing_call_dates_id').val();
In pure JS:
var dates = document.getElementById('outgoing_call_dates_id').value;
For PHP,
when you'll receive it on your action page.
On that page,
use this:
$dates = $_POST['outgoing_call_dates'];
or
$dates = $_GET['outgoing_call_dates'];
depending on the method you use.
Please have a look # this....!
Hope this will fix your issue :)
<no codes :|>
http://jsfiddle.net/3t4j9/23/

Dynamically added form elements are posted to PHP but cannot access them

I'm posting dynamically added form elements to PHP via AJAX.
I can see that the serialised form data is posted to the php, but when I try to access the data within it, some of the fields come up NULL i.e. var_dump in the PHP below shows NULL.
this is the Jquery that adds the dynamic elements:
$(function(){
var count=0;
$('#more_edu').click(function(){
count ++;
$('#education_add').append('<br><br><label>University/Institution: </label><input type="text" class="searchbox" id="edu_inst'+count+'" name="edu_inst[]" maxlength="200" value="">);
event.preventDefault();
});
});
and the Jquery posting to php:
function profileSub(){
var myform;
event.preventDefault();
myform = $('form').serialize();
$.ajax({
type: 'POST',
url: 'tutorprofileinput.php',
data: {"form": myform},
success:function(data, response, xhr){
console.log(response);
console.log(data);
console.log(xhr);
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
}
This is the original form:
<form id="tutor_profile_input" onsubmit="return false;">
<label>University/Institution: </label>
<input type="text" class="searchbox" id="edu_inst" name="edu_inst[]" maxlength="200" value=""> </br></br>
<label>Subject:</label>
<input type="text" class="searchbox" id="edu_subj" name="edu_subject[]" maxlength="200" value=""></br></br>
<label> Level </label>
<select id="edu_level" name="edu_level[]">
and the PHP itself:
<?php
if (isset($_POST['form'])){
$form = $_POST['form'];
var_dump($_POST["edu_inst"]);?>
This is the var dump of the whole $_POST:
location=&price=&tutorname=&edu_inst%5B%5D=Uni1&edu_subject%5B%5D=subje1&edu_level%5B%5D=BA&edu_inst%5B%5D=uni2&edu_subject%5B%5D=subj2&edu_level%5B%5D=BA&bio=%09&exper
The form you've posted has an ID of #tutor_profile_input, where as the one you're appending to in the jQuery function is #education_add - Unless I've misunderstood?
Otherwise I'd look at specifying a more specific target in the AJAX request - You're just targetting $('form') at the moment which could be any form on the page..
Have discovered the answer so thought I would share - The Jquery serialize() function encodes the data into a string, which is then posted to PHP as an array with the key of "form".
In order to deal with this in php I had to first use the urldecode function in PHP to convert the string encoded elements (%5B%5D) from the name attributes. This was because there might be multiple values in these so they were declared in the form as an array ("name="edu_insts[]"). Then use parse_str to split the string into an array.
<?php
$querystring = $_POST['form'];
$querystring = urldecode($querystring);
parse_str($querystring, $params);
$insts = $params['edu_inst'];
echo $insts[0]."<br>";
echo $insts[1]."<br>";
?>
This will create an array named $params with keys corresponding to the form name attributes.
Note that if you have multiple values within the same name, then each one will be placed within an array itself, so with the above text you will have $insts[0] = University 1
and $insts[1] = University 2 etc.
Hope this helps anyone with the same problem.

Pass an array by ajax to php page

I need to pass an array to a php page with AJAX. This array of input elements gets sent to the other page:
<input type="text" name="txtCoursesNamewith[]" id="txtCoursesNamewith" size="117" >
This is how I prepare it for sending:
var txtCoursesNamewith = $.serialize($('#txtCoursesNamewith').val());
But I get this error when running the script:
TypeError: $.serialize is not a function
How can I send an array with AJAX?
I am facing same problem and, i am just using code like this.
but first of all please insert one hidden field and set textbox id like this:
<input type="hidden" name="txt_count" id="txt_count" value="3" />
<input type="text" name="txtCoursesNamewith[]" id="txtCoursesNamewith1" size="117" >
<input type="text" name="txtCoursesNamewith[]" id="txtCoursesNamewith2" size="117" >
<input type="text" name="txtCoursesNamewith[]" id="txtCoursesNamewith3" size="117" >
<script type="text/javascript">
var txt_count= $('#txt_count').val();
for (i=1; i<=txt_count; i++){
queryString += "&txtCoursesNamewith%5B%5D=" + $('#txtCoursesNamewith'+i).val();
}
</script>
finally we can pass queryString variable to ajax, and you can print array.
<?php
echo "<pre>";
print_r($_GET); // or print_r($_POST);
?>
var textBoxes;
$('input[name="txtCoursesNamewith[]"]').each(function() {
textBoxes+=$(this).val()+"|||";
});
Now the textBoxes have all the values of text field with ||| separated and pass to php script and use explode() function to split each input value . may it helps u
You don't need to use .val() because .serialize() works on a the field itself, not on the value. (because it needs to get the name and the value from the field)
You can also call serialize() directly on a jQuery object, rather than using the jquery object as a parameter. Do it like this:
var txtCoursesNamewith = $('#txtCoursesNamewith').serialize();
Hope that helps.
Because $.serialize($('#txtCoursesNamewith').val()) is a string and not a jQuery object, it doesn't have the serialize function.
If you want to serialize the input (with its value), use $('#txtCoursesNamewith').serialize();
$.ajax({
type: 'POST',
url: your url,
data: $('#'+form_id).serialize(),
success: function(data) {
$('#debug').html(data);
}
});
Then in php
<?php
print_r($_POST);
?>

how to get values from generated text inputs?

i am creating a few input fields in a foreach loop:
<?php foreach($this->results as $value){?>
<td>View Detail
<input name="processor" id="processor" type="text" value="<?php echo $value['processor']; ?>">
<input name="auth_code" class="auth_code" type="hidden" value="<?php echo $value['auth_code']; ?>"></td>
<? } ?>
is will give me something like:
<td>
View Detail
<input name="processor" class="processor" type="text" value="19">
<input name="auth_code" class="auth_code" type="text" value="4">
</td>
<td>
View Detail
<input name="processor" class="processor" type="text" value="9">
<input name="auth_code" class="auth_code" type="text" value="11">
</td>
...
then i try to get the values:
$('.buttonDetails').live("click", function (){
var processor = $('.processor').val();
alert(processor);
$.ajax({
type: 'POST',
dataType: 'json',
url: '/decline/list',
async: false,
data: {
processor: processor,
processor: auth_code
},
success: function(json) {
$('#details').html(json.processor);
}
});
return false;
});
the problem i have is that my alert gets the same number (usually the first value from the first input) when i click on any link.
any ideas ho to fix this? i've tried replacin classes with id's and 'click' with 'live' but still nothing
edit:
i believe i need to differentiate the classes so he links will know what value to pull..??
edit: what if i want to get the 'auth_code ' also?
Try:
$('.buttonDetails').live("click", function (){
var processor = $(this).next(".processor").val();
alert(processor);
/* snip */
});
Use next to get the input next to the link that was clicked.
Update (due to comment).
You could find auth_code similarly using nextAll instead:
var auth_code = $(this).nextAll(".auth_code").val();
Also, are you sure you're supplying the correct values to your AJAX call? It looks like you're specifying processor twice. The first value specified for processor will be overwritten.
If you just want the next item you can use jquery next()
$('.buttonDetails').live("click", function (){
var processor = $(this).next().val();
alert(processor);
return false;
});
here is a fiddle
http://jsfiddle.net/znge4/1/
data: {
processor: processor,
processor: auth_code
},
the 'auth_code' line will overwrite the 'processor' line, effectively making it
data: {
processor: auth_code
},
only. You can't have a single key with two different values in a associate array/object. For submitting same-name fields to PHP, use its fieldname[] notation, which tells PHP to treat that particular form field as an array.
<input name="processor[]" ...>
<input name="processor[]" ...>
and pass the data to JQuery via
data : $(this).serialize()
use Jquery .next() which should give you the next element
You get the same value no matter which anchor tag was clicked because of this line:
var processor = $('.processor').val();
You're searching the entire DOM for all elements with class 'processor', which returns every input, and then .val() will return the value of the FIRST match (the first input).
Try this instead:
var processor = $(this).next('.processor').val();
All you need to do is get the value from the element they clicked. Using Jquery's 'this' keyword should solve your problem.
$('.buttonDetails').live("click", function (){
var processor = $(this).next().val();
alert(processor);
The 'this' will select the 'a' they clicked on, then next will iterate to the next sibling, in this case your input, and the val retrieves that value as before.

Categories