How to pass array from ajax to php? - php

I'm trying to pass array from ajax to php (controller).
What is wrong with second code as var_dump($data) of first code returns appropriate content and second returns NULL?
FIRST. GOOD.
function myFunction() {
var elementy = document.getElementsByClassName('inputISBN');
var data = elementy[0].value;
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: { "data": data }
});
}
SECOND. BAD
function myFunction() {
var elementy = document.getElementsByClassName('inputISBN');
var data = [];
data[elementy[0].name] = elementy[0].value;
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: { "data": data }
});
}
THIRD. UGLY
var elementy = document.getElementsByClassName('inputISBN');
undefined
var data = [];
undefined
data[elementy[0].name] = elementy[0].value;
"667"
Third one is line by line from the socond code written in browser console. And it's return what it should.
edit
and data is pulled out from here:
<input type="number" class="inputISBN" size="2" name="exampleName"
value="666" onchange="myFunction()">

When passing an array to PHP, you want to include the array indicator: []. I thi8nk you need an Object: {}.
function myFunction() {
var elementy = $('.inputISBN');
var data = {};
$.each(elementy, function(){
data[$(this).attr('name')] = $(this).val();
})
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: { "data": data }
});
}
At this point, you may also want to serialize the data (as was mentioned in the other answer by #Adelphia):
'data': JSON.stringify(data)
jsFiddle: https://jsfiddle.net/Twisty/cw77ann7/
You can call it in PHP: print_r($_POST['data']);

You want to pass your data variable to PHP, which is an array, right? Why not data = JSON.stringify(data); and then on PHP's side, $data = json_decode($_POST['data'], true);
function myFunction() {
var elementy = document.getElementsByClassName('inputISBN');
i = elementy.length;
data = [];
while(i--) data[elementy[i].name] = elementy[i].value;
data = JSON.stringify(data);
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: { "data": data }
});
}

Related

Upate table with AJAX in Laravel 5.3 not working

I trying to use an AJAX PUT request to update a row in my database and I am trying to send the request to my controller. This is my AJAX call:
$('#edit-trucks').on('click',function(){
var truckNo = $('#XA').val();
var truckOwner = $('#truck-owner').val();
var vehicle_number = $('#vehicle-number').val();
var capacity = $('#capacity').val();
var end_of_insurance = $('#end-of-insurance').val();
var end_of_kteo = $('#end-of-KTEO').val();
var truckCode = $('#truck-code').val();
var leased = $('#leased').val();
var truckModel = $('#truck-model').val();
$.ajax({
url: 'editTruck',
type: 'put',
data: {
truckNo: truckNo,
truckOwner: truckOwner,
vehicle_number: vehicle_number,
capacity: capacity,
end_of_insurance: end_of_insurance,
end_of_kteo: end_of_kteo,
truckCode: truckCode,
leased: leased,
truckModel: truckModel
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
contentType: 'application/json',
dataType: 'JSON',
success: function(){
console.log('success');
},
error: function(){
console.log('something went wrong');
}
});
});
So far so good. If I console.log() my data is seems I can get them from the form. I am using Laravel Collective for the form:
{!!Form::open(array('action' => ['Trucks#editTruck'], 'method' => 'put')) !!}
and my route is the following:
Route::put('/editTruck', 'Trucks#editTruck',function(){ });
Now I am using Request $request in the parameters of the controller but somehow it looks like I cannot get the incoming values. For example the following var_dump will say NULL.
public function editTruck(Request $request)
{
$data = $request->input('truckNo');
var_dump($data);
}
Same happens if I use
$data = $request->truckNo;
instead. So I am wondering how can I get the values that are been sent to my controller with my AJAX call? Why am I getting NULL values?
What I was planning to do is:
public function editTruck(Request $request)
{
$singleTruck = Truck::find($request->truckNo);
$singleTruck->truckNo = $request->input('truckNo');
$singleTruck->truckOwner = $request->input('truckOwner');
........
$singleTruck->save();
}
You can find the answer here:
https://laravel.io/forum/02-13-2014-i-can-not-get-inputs-from-a-putpatch-request
You should change your form method and method inside your js code to "post", and add extra field "_method" = "PUT"
probably it can help.
OK I found it. Looks like the AJAX was malformed. So here is how it should be written:
$('#edit-trucks').on('click',function(){
var truckNo = $('#XA').val();
var truckOwner = $('#truck-owner').val();
var vehicle_number = $('#vehicle-number').val();
var capacity = $('#vehicle_capacity').val();
var end_of_insurance = $('#end-of-insurance').val();
var end_of_kteo = $('#end-of-KTEO').val();
var truckCode = $('#truck-code').val();
var leased = $('#leasing').val();
var truckModel = $('#truck-model').val();
var outGoingData = {
'truckNo': truckNo,
'truckOwner': truckOwner,
'vehicle_number': vehicle_number,
'capacity': capacity,
'end_of_insurance': end_of_insurance,
'end_of_kteo': end_of_kteo,
'truckCode': truckCode,
'leased': leased,
'truckModel': truckModel,
};
var data = JSON.stringify(outGoingData);
$.ajax({
url: 'editTruck',
type: 'POST',
data: data, <!-- The error was here. It was data: {data}-->
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
contentType: 'application/json',
dataType: 'JSON',
success: function(response){
alert("The data should be "+ response);
},
error: function(){
console.log('skata');
}
});
});

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.

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

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

send data through an array

I want to send data through an array
This transmitter code:
<script type="text/javascript">
$(function() {
$(".cat_button").click(function() {
var element = $(this);
var test = $("#cou").val();
var test2 = $("#category2").val();
var data = [
{data:test},
{data:test2}
];
if(test=='' || test2=='.....')
{
alert("fill data");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="http://tiggin.com/ajax-loader.gif" align="absmiddle"> <span class="loading">Loading...</span>');
$.ajax({
type: "POST",
url: "insert2.php",
data: {data: data},
cache: false,
success: function(response){
console.log(response);
}
});
}
return false;
});
});
</script>
This code reception:
print_r($_POST['data']); // dumps an array
$course = $_POST['data'][0]['data'];
$category = $_POST['data'][1]['data'];
$insert_new_cou = mysql_query("insert into course (name,cat_id) values ('$course','$category')") or die($insert_new_cou."<br/><br/>".mysql_error());
But show me the following error:
Cannot use string offset as an array
I think the solution using Jtgson but I do not know how to use it
It can be done by JSON encoding your array of objects. In the $.ajax call:
...
url: "insert2.php",
data: {data: JSON.stringify(data)},
...
On the PHP side use json_decode() to get an array of objects from the JSON string:
$data = json_decode($_POST['data']);
$course = $data[0]->data;
$category = $data[1]->data;

Categories