How to pass a nested PHP-Array via AJAX-Post? - php

I have a PHP-Script that expects:
$_REQUEST['asdf']['bsdf']['csdf']
to be set when it is called, and I cannot change this.
I want to call this PHP-Script via ajax:
myurl = 'example-url.com';
myid = $(this.$element).attr('id'); //gets the id of a textfield: csdf
value = 'somevalue';
$.ajax({type: 'POST',
url: myurl,
data: {'asdf[bsdf][myid]': value},
success: function (data) {
/* blabla */
}
});
It does not work though, because the var "myid" is not filled with the supposed value "csdf".
Can someone help me how to do this?
PS: I cannot access the PHP-File, so no changes in structure possible...

Try something like this:
var myurl = 'example-url.com';
var myid = $(this.$element).attr('id'); //gets the id of a textfield: csdf
var value = 'somevalue';
var param = {};
param[myid] = value;
$.ajax({type: 'POST',
url: myurl,
data: {'asdf[bsdf]' : param},
success: function (data) {
}
});
You can build the param object outside the data you pass via the ajax call to keep the correct key in place.

in JS
... {
...
data: {[['first', 'array', 'nested'], 'other', 'in', 'parent', 'array']},
...
}
In PHP getting the POST vars is with other sentence
http://php.net/manual/en/reserved.variables.post.php

Related

Ajax send data with string name

I apologise if this was already answered, but I haven't found an answer in 70k+ results..
I want to send data like this:
function _post(params) {
var func = params['func']; // -> 'getUserDetails'
$.ajax({
url: "crossroad.php",
type: "post",
data: { func : params },
cash: false,
complete: function(respond){
console.log(respond);
}
});
}
m = {};
m['func'] = 'getUserDetails';
m['id'] = '123456';
_post(m);
But with this code, php gets
$_POST['func']
I want string that I am sending to be named as params['func'] and in this case I want to receive in php
$_POST['getUserDetails']
How can I achieve this ?
You need to create object
var requestParams = {};
And then setup it property like
requestParams[params['func']] = '';// your data to send
//or
requestParams[params['func']] = params['id'];// your data to send
And then put into ajax data property
data: requestParams,
The problem here is that func is a valid key identifier, so although you are expecting func to be substituted for the parameter you passed in, you are actually declaring a property of your data object called func.
To get around this issue, create a new object, and pass it in like this:
function _post(params) {
var func = params['func']; // -> 'getUserDetails'
var obj = {};
obj[func] = params;
$.ajax({
url: "crossroad.php",
type: "post",
data: obj,
cash: false,
complete: function(respond){
console.log(respond);
}
});
}
function _post(params) {
var func = params['func']; // -> 'getUserDetails'
var obj = {};
obj[func] = params['id'];
$.ajax({
url: "crossroad.php",
type: "post",
data: obj,
cash: false,
complete: function(respond){
console.log(respond);
}
});
}
m = {};
m['func'] = 'getUserDetails';
m['id'] = '123456';
_post(m);

jQuery+PHP. Request/Response

I would search for the solution, but I don't know what exactly do I have to search.
The task is to grab texts with ID's (#ftext_1,..._2,..._3,..._4) in html file and send them to php file. After some manipulation with texts in php file I have to insert them back into their ID's in html file.
Here is the code:
var text_1_Replace = $('#ftext_1').text();
var text_2_Replace = $('#ftext_2').text();
var text_3_Replace = $('#ftext_3').text();
var text_4_Replace = $('#ftext_4').text();
$('#ID').on('click', function(){
var text= {
ftext_1: text_1_Replace,
ftext_2: text_2_Replace,
ftext_3: text_3_Replace,
ftext_4: text_4_Replace
}
var targetFile = 'ajax/file.php';
$.ajax({
method: 'post',
url: targetFile ,
data: JSON.stringify(text),
contentType: 'application/JSON'
}).done(function(data) {
console.log(data);
});
});
How do I edit .done function to place new texts in their old ID's(#ftext_1,..._2,..._3,..._4)? The variable with texts array is $result.
so the answer is :
}).done(function(data) {
var text = JSON.parse(data);
var text1 = text.ftext_1;
var text2 = text.ftext_2;
var text3 = text.ftext_3;
var text4 = text.ftext_4;
$('#ftext_1').text(text1);
$('#ftext_2').text(text2);
$('#ftext_3').text(text3);
$('#ftext_4').text(text4);
So, the last update for the topic: The real and nice answer is:
.done(function(data) {
var text = JSON.parse(data);
$.each(text, function(i, val){
$("#" + i).text(val);
});
This code is the solution to my question in this topic. Thank you all, who responded!
The best for you would be send named property that looks like this
$.ajax({
method: 'post',
url: targetFile ,
data: {data: text},
dataType: "json",
success: function(response){
$.each(response, function(element){
$("#"+element.name).text(element.text);
});
}
});
Then in your php you could easily iterate data from post
<?php
$data = $_POST['data'];
$response = [
];
foreach($data as $elementName => $text){
// some text management
$response[] = ['name' => $elementName, 'text' => $text];
}
return json_encode($response);
When you change your received values in php you put them in an array so that you
can call it later easily
PHP
$values = array("one"=>5,
"two"=>"something",
"three"=>$something);
echo json_encode($values);
You need to add
dataType:'json'
in Jquery since you're returning json
JQuery
$.ajax({
method: 'post',
url: targetFile ,
data: JSON.stringify(text), # or data: {"value1":value,"value2":value2},
contentType: 'application/JSON',
dataType:'json',
success: function(response){
console.log(response.one); #Will console 5
console.log(response.two); #Will console "something"
console.log(response.three); #Will console whatever $something holds in php
}
});
You can call it however you want it (response) or (mydata)...
And then you just type response.yourdata (that you declared in php)

Use JS variables and serialize for AJAX request

I'd like to have the following code in my AJAX request:
function ajax_post( form_info ){
var request = $.ajax({
url: "ajax_handler.php",
type: "POST",
data: {data : form_info},
});
};
I'd like to serialize all of the elements in my clicked event to pass directly to the AJAX function because I'm doing processing on the PHP side. Say I have the following on click function:
$('.open-popup').on("click", function() {
var clicked_id = $(this).attr('id');
var contest_id = $('#contest-id').val();
var contest_type = $('#contest_type').val();
//serialize everything to a data_to_pass variable
ajax_post( data_to_pass );
});
How could I serialize the clicked_id, contest_id and contest_type into a single variable to pass to my AJAX processing function as a single string of data?
This is how you can do it:
var data_to_pass = {
clicked_id: clicked_id,
contest_id: contest_id,
contest_type: contest_type
}
JS:
$('.open-popup').on("click", function() {
var clicked_id = $(this).attr('id');
var contest_id = $('#contest-id').val();
var contest_type = $('#contest_type').val();
var data_to_pass = {
clicked_id: clicked_id,
contest_id: contest_id,
contest_type: contest_type
};
ajax_post( data_to_pass );
});
AJAX:
function ajax_post( form_info ){
var data = JSON.stringify(form_info);
var request = $.ajax({
url: "ajax_handler.php",
type: "POST",
data: {data : data},
});
};
You can create FormData for that and append all the required values with .append() function.
Like this,
$('.open-popup').on("click", function() {
var clicked_id = $(this).attr('id');
var contest_id = $('#contest-id').val();
var contest_type = $('#contest_type').val();
//serialize everything to a data_to_pass variable
var fd = new FormData();
fd.append( 'clicked_id', clicked_id);
fd.append( 'contest_id', contest_id);
fd.append( 'contest_type', contest_type);
ajax_post(fd);
});
And AJAX function would look something like this,
function ajax_post( form_data ){
var request = $.ajax({
url: "ajax_handler.php",
type: "POST",
data: form_data,
});
};
And access the data in PHP using $_POST['clicked_id'] and so on...
jQuery's ajax accepts objects as data; it takes care of the serialization for you. So you can simply do
ajax_post({
clicked_id:$(this).attr('id'),
contest_id:$('#contest-id').val(),
contest_type: $('#contest_type').val()
});
If you want to do so, try using a form element and inputs (it can be hidden fields if it isn't a user submitted form) in your HTML code, and serialize it, so you can transmit the whole 'block of information' at one time with Ajax.
Look at rfunduk's answer at this question.

$_GET the variable of javascript to php

my ajax is:
add = 'request';
full_val = 'barrack obama';
$.ajax({
url: 'plugins/add_friend.php',
data: full_val+'='+add,
success: function(data)
{
}
});
if the javascript variable value changes depending on the conditions, then how will i $_GET[] the variable full_val? I want it to be something like:
$_GET[full_val]
is there a way to pass the variables of javascript to php?
If you want the literal index full_val, then use it in the query string:
data: 'full_val='+add,
So that in PHP, you'd be able to use $_GET['full_val']
Alternatively, you could also put an object in that field:
data: {full_val: full_val, add: add},
Here is the description:
data
Type: PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests.
Your data just has the values and does not have the keys. See below for how to pass the keys and values.
add = 'request';
full_val = 'barrack obama';
$.ajax({
url: 'plugins/add_friend.php',
data: {full_val:full_val,add:add},
success: function(data)
{
}
});
In your PHP use $_GET['full_val'];
send your values with data parameter correctly and add type:get to define GET method
add = 'request';
full_val = 'barrack obama';
$.ajax({
type: "get",
url: 'plugins/add_friend.php',
data: {'full_val':full_val,'add':add},
success: function(data) {
}
});
Then you will get values on php :-
use $_GET['full_val'] rather $_GET[full_val]
Try Using this
add = 'request';
full_val = 'barrack obama';
$.ajax({
url: 'add.php',
data: 'full_val='+add,
success: function(data)
{
alert(data);
}
});
You can use the .get() method. The variables you can set using an object literal. For example:
$.get("/plugins/add_friend.php", {
add: "request",
full: "Barrack Obama"
}).done(function(data) {
console.log("Status:", data.status);
console.log("Received:", data.received);
});
And the PHP could be done something like this:
$add = filter_input(INPUT_GET, 'add', FILTER_SANITIZE_STRING);
$full = filter_input(INPUT_GET, 'full', FILTER_SANITIZE_STRING);
echo json_encode(array(
'status': 'OK',
'received': "{$add} and {$full}",
));

Pass input value to ajax get Laravel

I am fairly new to Laravel and ajax in general, what I am trying to implement is to pass the value of an input field through an ajax get request.
My request looks like this:
function getInfo() {
$.ajax({
url: "info",
dataType: "json"
}).success(function(data){
$('#result').append(JSON.stringify(data));
}).fail(function(){alert('Unable to fetch data!');;
});
}
$('#infoSubmit').click(getInfo);
I have setup a route for my function in laravel that works like this
public/info/Variable <--
When I add a variable after info/
I get the data for that variable (e.g profile name)
I need to pass this variable from an inputfield to ajax request to something like this:
url: "info/+$inputfieldVariable"
Change:
url: "info",
TO:
url: "info/" + $('input-field-selector').val(),
Not sure about the correctness of your JS code: Shouldn't you be using done instead of success?
JavaScript:
function getInfo() {
var myFieldsValue = {};
var $inputs = $("#myForm :input");
$inputs.each(function() {
myFieldsValue[this.name] = $(this).val();
});
$.ajax({
url: "info",
dataType: "json",
data: myFieldsValue,
type: "GET" // Even if its the default value... looks clearer
success: function(data){
$('#result').append(JSON.stringify(data));
},
error: function(){
alert('Unable to fetch data!');
}
});
return false;
}
$('#infoSubmit').click(getInfo);
Untested but should be something like that

Categories