Pass multiple php arrays in ajax request response - php

I'm trying to pass multiple arrays in Ajax request response(get), but unfortunately I'm not able to get it done.
This is my php code I'm willing to send into Ajax request response:
echo json_encode($catdata);
echo json_encode($productdata);
echo json_encode($data);
My js ajax call is:
$.ajax({
type: "post",
url: "../api/test.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
var j=0;
$.each(data,function(l,item){
var arrlength = data[l].countdest;
while(j<=arrlength)
{
(function(j)
{
$('#catbtn').click(function(){
if(j<=arrlength)
{
$('#resultdiv').append('<p name="destinationid">'+data[j].destinationid+' '+data[j].name+'</p>');
var a;
for(a=0;a<4;a++)
{
alert(a);
}
//$('#resultdiv').append('<input type="checkbox" name="destinationid" value="'+data[j].destinationid+'" '+data[j].name+'/>');
j++;
if(j==arrlength)
{
$('#catbtn').hide();
$('#submit').show();
}
}
});
}
(j));
i
}
});
//alert(arrlength);
},
});

var formData = {
array1 : yourArray1,
array2 : yourArray2,
array3 : yourArray3
};
$.ajax({
type:"POST",
url: "trial2.php",
data: formData,
success: function(result) {
console.debug(result);
},
Edited , now check

Try to send them all in one array:
echo json_encode(array($catdata, $productdata, $data));

Related

AJAX Post to another Not Working

I am trying to do a AJAX Post.
What i am trying to do is transfer the variable campos[i] to the test.php.
Script:
for (var i = 0; i <= <?php echo $count - 1 ?>; i++) {
note[i] = jQuery('.bool#A' + i),
note[i].text(bounds.contains(accounts[i]));
if (bounds.contains(accounts[i])) {
$.ajax({
data: {'campos': campos[i]},
type: 'POST',
url: "test",
success: function () {
alert("action performed successfully");
$("#campos").load("test");
}
});
}
}
test.php:
print_r($_POST);
Result:
Your url must be test.php (if you don't have a route for it).
Your success callback should have data as response parameter.
You should append ($("#campos").HTML(data.something)) instead of doing another XHR request $.load.
Hope it helps.
if you are doing a POST be sure to stringify your parameter.
$.ajax({
contentType: "application/json; charset=utf-8",
data: '{"campos": "'+ campos[i] '"}',
method: 'POST',
url: "your url here!",
success: function () {
alert("action performed successfully");
$("#campos").load("test");
}
});

Request response doesn't work

Here is my JSON function:
function createjson(){
var json='{"jsondata":[[';
$("#kup td").each(function(){
if($(this).html()!="")
{
json+= parseInt($(this).html())+",";
if($(this).index()%5==0 && $(this).index()!=0){
json=json.substring(0,json.length-1);
json+="],["
}
}
});
json=json.substring(0,json.length-3);
json+="]]}";
console.log(json); //-> works fine.
return json;
};
The AJAX part:
$("#button").click(function(){
$.ajax({
type:"POST",
url:"x.php",
data: createjson(),
contentType: "application/json",
dataType: "json",
success: function(result) {
alert("done"); //->works
}
});
});
The PHP part:
<?php
header('Content-type: application/json');
echo "<pre>";
echo $_POST['jsondata'];
echo "</pre>";
?>
So, the "alert" works but when check the response in console, it returns only "<pre></pre>"
any solution?
The data option can contain either a query string of the form
key1=value1&key2=value2, or an object of the form {key1: 'value1',
key2: 'value2'}. If the latter form is used, the data is converted
into a query string using jQuery.param() before it is sent. This
processing can be circumvented by setting processData to false
. from jquery API doc
I didn't tested it but should give the intense how to change structure, give it a try:
function createdata(){
var data;
$("#kup td").each(function(){
if($(this).html()!="")
{
data.push( parseInt( $(this).html() ) );
//...
}
});
console.log(data);
return data;
};
$("#button").click(function(){
var data = createdata();
$.ajax({
type:"POST",
url:"x.php",
data: {createjson:data},
contentType: "application/json",
dataType: "json",
success: function(result) {
alert("done"); //->works
}
});
});

ajax link json datatype call

I want to send the data via ajax to other page. I have isolated the problem. This is the code.
Thank you all for your help..But no effect..
updated code
It worked...
<script>
$(document).ready(function(){
$(".edit").click(function(event) {
event.preventDefault(); //<--- to prevent the default behaviour
var box = 1233;
var size=123;
var itemname=123;
var potency=123;
var quantity=12333;
var dataString ={
'box' :box,
'size':size ,
'itemname':itemname,
'potency':potency,
'quantity':quantity
};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
}
});
});
});
</script>
So I click the link,it navigates, to dd.php which has
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']));
echo $_POST['itemname'];
?>
I get Object Object as alert. What am doing wrong? Pls throw some light here..thanks you..
$(document).ready(function(){
$(".edit").click(function(event) {
event.preventDefault();
var data = {"box":1233,
"size":565,
"itemname":565,
"potency":876,
"quantity":234};
$.ajax({
url: "dd.php",
type: "post",
data: data,
dataType: "json",
success: function(data) {
if(console){
console.log(data);
}
},
error: function(data) {
if(console){
console.log(data);
}
}
});
});
});
few things to consider... you can post data as object..which is clean and easier to use
$(".edit").click(function(event) {
event.preventDefault(); //<--- to prevent the default behaviour
var box = 1233;
....
var dataString ={'box':box,'size':size,'itemname':itemname,'potency':potency,'quantity':quantity};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
dataType: "json", //<--- here this means the response is expected as JSON from the server
success: function(data) {
alert(data.itemcode); //<--here alert itemcode
},
error: function(data) {
alert(data);
}
});
so you need to send the response as json in PHP
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']))
?>
Here you are using querystring as sent in GET request.
If you want to send the data in same form, you can use this with GET request type:
$.ajax({
url: "dd.php"+dataString,
type: "get",
dataType: "json",
success: function(data) {
console.log(data);
alert(data.itemcode);
},
error: function(data) {
alert(data);
}
});
Or for POST request,you will have to put data in json object form, So you can use :
var dataString ={
'box' :box,
'size':size ,
'itemname':itemname,
'potency':potency,
'quantity':quantity
};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
dataType: "json",
success: function(data) {
console.log(data);
alert(data.itemcode);
},
error: function(data) {
alert(data);
}
});
});
And put echo in your php code :
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']))
?>
Javascript alert shows [Object object] for object. You can see response using console.log or can use that key with alert.
For more information, refer jQuery.ajax()

sending data through ajax to CI controller

I am new to ajax and CI .I want to send data and image through ajax . In my view i have 3 input fields and one image upload button .
var val1 = $("#val1"+id).val();
var val2 = $("#val2").val();
$.ajax({
type: "POST",
url: "page/save_data",
data: "{ val1 :'"+val1+"',val2:'"+val2+"}",
success: function(msg) {
alert(msg);
}
});
and in controller when i try this it shows me nothing
function save_data()
{
$val = $this->input->post('val1');
echo $val1;
}
In console it gives me nothing .
Try this :
$.ajax({
type: "POST",
url: "page/save_data",
data: { "val1 ":val1,"val2": val2},
success: function(msg) {
alert(msg);
}
});
Your ajax URL must be refer to your method name;
...
$.ajax({
type: "POST",
url: "page/save_data", //change this to your method;
...
should be like:
...
$.ajax({
type: "POST",
url: "page/save_iudata",//or whatever your method's name;
...
EDIT:
try this way:
function save_data(){
$val1 = $_REQUEST['val1'];
echo $val1;
}
Hello to send data via ajax is easy:
var data = {
val1: $('#val1').val(),
val2: $('#val2').val(),
};
$.ajax({
url: "<?php echo base_url().'page/save_data'; ?>",
dataType: 'json',
type: 'POST',
async : false,
data: data,
success: function(msg){
...
}
});
return false;
But to send an image you have to do some research...
here is a good tutorial

JS AJAX sending multiple data array

I am trying to send multiple data arrays in my ajax save function.
I can do each array individually like data:hardwarePayload and it will work. If I do {hardware: hardwarePayload, service:servicePayload} I get very weird JSON output. that looks like:
hardware=%5B%7B%22hardwareName%22%3A%221%22%2C%22hardwareQuantity%22%3A%22%22%2C%22hardwareBYOD%22%3A%22%22%7D%5D&service=%5B%7B%22serviceName%22%3A%223%22%2C%22serviceQuantity%22%3A%22%22%7D%5D
I really need two arrays one hardware and one service so I can grab each one individually.
My code looks like this..
self.save = function (form) {
var hardwareModel = [];
var serviceModel = [];
ko.utils.arrayForEach(self.services(), function (service) {
serviceModel.push(ko.toJS(service));
});
ko.utils.arrayForEach(self.hardwares(), function (hardware) {
hardwareModel.push(ko.toJS(hardware));
});
//allModel.push({accountId: ko.toJS(account)});
var hardwarePayload = JSON.stringify(hardwareModel);
var servicePayload = JSON.stringify(serviceModel);
//alert(JSON.stringify(serviceModel) +JSON.stringify(allModel));
$.ajax({
url: '/orders/add',
type: 'post',
data: {hardware: hardwarePayload, service:servicePayload}, // data:hardwarePayload,
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
};
You should try this
var hardwarePayload = hardwareModel;
var servicePayload = serviceModel;
var postData = {'hardware': hardwarePayload, 'service':servicePayload};
var postData = JSON.stringify(postData);
alert(postData);
$.ajax({
url: '/orders/add',
type: 'post',
data: postData,
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
I think you'll be better off if you do NOT stringify your data:
$.ajax({
url: '/orders/add',
type: 'post',
data: {hardware: hardwareModel, service:serviceModel}, // data:hardwarePayload,
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
(Note that I'm using the not stringified hardwareModel and serviceModel)
This way you can have jQuery handle the (json) data for the request.

Categories