jQuery post not passing parameters - php

I have a problem with posting variable to php script and getting result back without refreshing page. php script koord.php is tested and it's working fine.
This is my js code (adresa, mjesto and coords are text input boxes):
$(document).ready(function () {
$('#coord_click').click(function () {
provjera();
});
});
function provjera() {
var adresa = $('#adresa').val();
var mjesto = $('#mjesto').val();
var puna_adresa = adresa + " " + mjesto;
$.post("koord.php", { puna_adresa: puna_adresa },function (result) {
$('#coords').val(result);
});
}
koord.php:
$puna_adresa = $_GET['puna_adresa'];
function getCoordinates($address){
$address = str_replace(" ", "+", $address);
$url = "maps.google.com/maps/api/geocode/…";
$response = file_get_contents($url);
$json = json_decode($response,TRUE);
return ($json['results'][0]['geometry']['location']['lat'].",".$json['results'][0]['geo‌​metry']['location']['lng']);
}
echo getCoordinates($puna_adresa);
Complete source code is here: http://pastebin.com/u/bradetic
Thank you!

The Jquery POST is not the problem.
Your are doing $.post(...) which means that you need to get the parameter in koord.php via $_POST, and you are using $_GET, you see the problem right?
Solution
Change $_GET['puna_adresa']; to $_POST['puna_adresa'];
or
change $.post(...) for $.get(...) in your client side.
You know the difference between POST and GET right?
When do you use POST and when do you use GET?
How should I choose between GET and POST methods in HTML forms?

You seriously need to use Jquery AJAX, here's an example:
<script>
function your_function()
{
// collect data like this
var formData = jQuery("#your_form_id").serializeArray();
jQuery.ajax({
type: "POST",
url:"your_php_page.php",
data:formData,
dataType:'json',
beforeSend: function()
{
},
success: function(resp)
{
alert(resp);
},
complete: function()
{
},
error: function(e)
{
alert('Error: ' + e);
}
});
}
</script>
And you PHP script should go like this:
$puna_adresa=$_POST['puna_adresa'];
function getCoordinates($address){
$address = str_replace(" ", "+", $address);
$url = "maps.google.com/maps/api/geocode/…;;
$response = file_get_contents($url);
return $response;
}
$response = getCoordinates($puna_adresa);
echo json_encode($response);

Can you try this,
$.post("koord.php", { puna_adresa: adresa, mjesto: mjesto }, function (result) {
$('#coords').val(result);
});
Another way:
$.post("koord.php", $( "#testform" ).serialize(), function (result) {
$('#coords').val(result);
});
Ref: http://api.jquery.com/jQuery.post/

you May try this
$.post( "koord.php", $( "#testform" ).serialize() );

Related

Ajax POST to Cakephp Controller always give array() result

i really struggle to get the POST value in the controller .i am really new to this..Please someone share me some light..being in the dark for long hours now.
i had a checkboxes and need to pass all the ids that had been checked to the controller and use that ids to update my database.i don't know what did i did wrong, tried everything and some examples too like here:
sending data via ajax in Cakephp
found some question about same problem too , but not much helping me( or maybe too dumb to understand) . i keep getting array();
please help me..with my codes or any link i can refer to .here my codes:
my view script :
<script type="text/javascript">
$(document).ready(function(){
$('.checkall:button').toggle(function(){
$('input:checkbox').attr('checked','checked');
$('#button').click( function (event) {
var memoData = [];
$.each($("input[name='memo']:checked"), function(){
memoData.push($(this).val());
});
var value = memoData.join(", ")
//alert("value are: " + value);
//start
$.ajax({
type:"POST",
traditional:true;
data:{value_to_send:data_to_send},
url:"../My/deleteAll/",
success : function(data) {
alert(value);// will alert "ok"
},
error : function() {
alert("false submission fail");
}
});
//end
} ); //end of button click
},function(){//uncheck
$('input:checkbox').removeAttr('checked');
});
});
my controller :
public function deleteAll(){
if( $this->request->is('POST') ) {
// echo $_POST['value_to_send'];
//echo $value = $this->request->data('value_to_send');
//or
debug($this->request->data);exit;
}
}
and result of this debug is:
\app\Controller\MyController.php (line 73)
array()
Please help me.Thank you so much
How about this:
Jquery:
$(document).ready(function() {
$('.checkall:button').toggle(function() {
$('input:checkbox').attr('checked','checked');
$('#button').click(function(event) {
var memoData = [];
$.each($("input[name='memo']:checked"), function(){
memoData.push($(this).val());
});
//start
$.ajax({
type: 'POST',
url: '../My/deleteAll/',
data: {value_to_send: memoData},
success : function(data) {
alert(data);// will alert "ok"
},
error : function() {
alert("false submission fail");
}
});//end ajax
}); //end of button click
},function(){//uncheck
$('input:checkbox').removeAttr('checked');
});
});
In controller:
public function deleteAll()
{
$this->autoRender = false;
if($this->request->is('Ajax')) { //<!-- Ajax Detection
$elements = explode(",", $_POST['value_to_send']);
foreach($elements as $element)
{
//find and delete
}
}
}
You need to set the data type as json in ajax call
JQUERY CODE:
$.ajax({
url: "../My/deleteAll/",
type: "POST",
dataType:'json',
data:{value_to_send:data_to_send},
success: function(data){
}
});

How to pass JSON object from Controller to view

There are many threads on the subject, but I cannot find any that use PHP. I want to pass the json object to the view, where I will later update an element with the returned json object.
Here is my code:
View:
<input type="submit" class="button" name="insert" value="load"/>
<script>
jQuery(document).ready(function() {
var $ = jQuery;
var baseUrl = [location.protocol, '//', location.host, location.pathname].join('');
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = baseUrl+"?action=load";
data = {'action': clickBtnValue};
$.post(ajaxurl, {}, function (result) {
alert(result);
});
});
});
</script>
And Controller is:
<?php
set_include_path(get_include_path().':../');
require_once('_inc/common.php');
$action = req('action');
if ($action == 'load') {
$result = parse_ini_file('test.ini');
$json = json_encode($result);
}
[UPDATE]
After the code to the answers provided, I now get an Json.parse error. So I edited my code again but the error still persists, I checked online to see if my Json is a valid json and no error on the validator.
$result = parse_ini_file($config_file);
$json = json_encode(array($result),JSON_HEX_QUOT);
var_dump($json);
header('Content-Type: application/json');
View
var request = $.ajax({
url: ajaxurl,
method: "POST",
data: {},
dataType: "json"
});
request.done(function( msg ) {console.log("d");});
request.fail(function( jqXHR, textStatus ) {console.log( "Request failed: " + textStatus );});
});
Like said above, you aren't outputting the JSON, and also you are not setting the content type. But I noticed something else, you did not assign the return type of the post request (JSON).
$.post(url, {}, function (data) {
alert(data);
}, 'JSON');
Be also sure that you encode an array and not a false value, parse_ini_file returns false when it fails.
Try this
<script>
jQuery(document).ready(function() {
var $ = jQuery;
var baseUrl = [location.protocol, '//', location.host, location.pathname].join('');
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = baseUrl+"?action=load";
data = {'action': clickBtnValue};
$.post(ajaxurl, {}, function (result) {
var json =JSON.parse(result);
console.log(json); //see in browser console
});
});
});
</script>
And Controller is:
<?php
set_include_path(get_include_path().':../');
require_once('_inc/common.php');
$action = req('action');
if ($action == 'load') {
$result = parse_ini_file('test.ini');
echo json_encode($result);
}

PHP doesn't get JQuery serialize() POST parameters

I want to send a form with JQuery $.ajax, but I have a problem. It's seems that PHP cannot get serialized $_POST. It's weird because the variable elementiPost is not empty, indeed if I do console.log(parametriPost) the console show me the right content.
The weirdest thing is that PHP get parameters that I append manually to parametriPost ($_POST['data_r']) but not those of $(this).serialize()!
If I put manually a number in $ore it works fine, so the problem is not the query.
Thank you.
Here's the code:
JQuery
$('form').submit(function(e) {
e.preventDefault();
var formId = $(this).attr('id');
var data = area_get_row_date(formId);
var parametriPost = $(this).serialize() + '&data_r=' + data;
$.ajax({
url: 'insert_db.php',
method: 'POST',
async: false,
data: parametriPost,
success: function() {
// Success code
},
error: function(xhr, status, error) {
alert("Errore!");
}
});
});
PHP (insert_db.php)
$data = str_replace('_', '.', $_POST['data_r']);
$ore = $_POST['orelavorateore_2_07_2015'];
$sql = "INSERT INTO ore_lav
VALUES (NULL, 134, 4,STR_TO_DATE('" . $data . "', '%d.%m.%Y'), " . $ore . ", 1, 1)";
$results = api_store_result(api_mysql_query($sql));
This is what parametriPost contains:
lavorati_prenotati=L&periodointegrazione_3_07_2015=on&orelavoratechf_3_07_2015=&orelavorateore_3_07_2015=a&extra_field1_orelavoratechf_3_07_2015=&extra_field1_orelavorateore_3_07_2015=&extra_field2_orelavoratechf_3_07_2015=&extra_field2_orelavorateore_3_07_2015=&orenonlavoratechf_3_07_2015=&orenonlavorateore_3_07_2015=&orenonlavoratetipologia_3_07_2015=L&extra_field1_orenonlavoratechf_3_07_2015=&extra_field1_orenonlavorateore_3_07_2015=&extra_field1_orenonlavoratetipologia_3_07_2015=L&extra_field2_orenonlavoratechf_3_07_2015=&extra_field2_orenonlavorateore_3_07_2015=&extra_field2_orenonlavoratetipologia_3_07_2015=L&orenonpagateore_3_07_2015=&orenonpagatetipologia_3_07_2015=L&extra_field1_orenonpagateore_3_07_2015=&extra_field1_orenonpagatetipologia_3_07_2015=L&extra_field2_orenonpagateore_3_07_2015=&extra_field2_orenonpagatetipologia_3_07_2015=L&orelavoratechf_3_07_2015=&orelavorateore_3_07_2015=&data_r=3_07_2015
You can use this snippet to convert your form data into JSON format :
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$("form").submit(function( event ) {
event.preventDefault();
//convert form data to JSON
var params = $(this).serializeObject();
//add a 'data_r' field with some data to our JSON
params.data_r = 'sample data';
$.ajax({
url: 'app.php',
type: 'POST',
data: JSON.stringify(params),
})
.done(function(data) {
console.log(data);
});
});
and on the PHP side :
<?php
$data = json_decode(file_get_contents('php://input'), false);
print_r($data->data_r);
?>
Now $data is an object and you can access to a specific field :
$data->data_r

ajax does not response

I try to take a response but I could not. I can't describe it why it does not work or what it is wrong.
var virmanYap = function(){
$("#loading").show();
$("#tblVirman").hide();
alert('Virman');
var data = $("#virman_filtre").serialize();
$.post("php/virman_yap.php", data).success(function(r){
alert(r);
});
}
my php code:
foreach ($_POST['virman'] as $evrakNo => $detay) {
print_r($_detay);
}
echo "asd";
Try $.ajax instead of $.post:
var virmanYap = function () {
$("#loading").show();
$("#tblVirman").hide();
alert('Virman');
var data = $("#virman_filtre").serialize();
$.ajax({
url: 'php/virman_yap.php',
type: 'POST',
data: data,
success: function (r) {
alert(r);
}
});
}
Check $.post documentation here: https://api.jquery.com/jQuery.post/
As you can see, success callback is one of the parameters, you don't need to chain it.
$.post("php/virman_yap.php", data, function(r){
alert(r);
});
Do something like this. Just remove the chained success function and you should be good.

Passing a Javascript Array through JQuery AJAX to PHP

$('#button').live('click', function () {
values_array = [];
$('.field').each(function () {
values_array.push = $(this).val();
});
$.ajax({
url: 'page.php',
data: {
array_a: values_array
},
type: 'POST',
success: function (data) {
$('#div').html(data);
}
});
});
//page.php
echo $_POST['array_a'] . "<br/>"; //The line break echos, but nothing else
A.) Do I need to iterate through each class with $.each in order to create a proper array, and
B.) Why doesn't php echo it?
Change:
values_array.push = $(this).val();
to:
values_array.push($(this).val());
That should do the trick :)
.push is a method which you have used like a property try instead
values_array = [];
$('.field').each(function() {
values_array.push($(this).val());
});
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push

Categories