JS AJAX sending multiple data array - php

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.

Related

when I send data with ajax php wont get anything

post and get works fine but json returns wrong value , or something is wrong with my php code.
$(function () {
$('#username').on('keypress',function () {
var input = $('#username').val();
if(input.length>=4){
$.ajax({
url:'registration_php.php',
type: 'POST',
data:{username:input},
success:function () {
$.getJSON('registration_php.php',function (text) {
alert(text.user);
});
}
});
}
});
});
success:function(result) {
var items = JSON.parse(result);
alert(items['user']);
}
pass the result directly to your reponse as an argument like this
you should specify a dataType: "json" in your ajax call
var postData = JSON.stringify({
username: 'value'
});
var request = $.ajax({
url: "registration_php.php",
method: "POST",
dataType: "json",
data: postData,
});
request.success(function( results ) {
console.log(results)
});

Array object to php using ajax

How can i send data like this to php using ajax
["{"title":"mr","fname":"john","lname":"Annah","oname":"Clement","staffid":"123"}"]
try json_encode
for more refer -
http://php.net/manual/en/function.json-encode.php
Do it like so, using jQuery(which you need to include in your script):
<script>
var data={};
data= {
"title":"mr",
"fname":"john",
"lname":"Annah",
"oname":"Clement",
"staffid":"123"};
$.ajax({
url:"somwhere.php",
type:"POST",
dataType:"JSON",
data:data,
async: true});
</script>
And on the page where you want to catch this data, do it like this:
<?php
$title=$_POST['title'];
$fname=$_POST['fname'];
?>
And so on.
stringify before sending
Eg :
var postData = [
{ "id":"1", "name":"bob"},
{ "id":"2", "name":"jonas"}]
this works,
$.ajax({
url: Url,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(postData) //stringify is important,
});
Try this
$(document).on("click", "#your element", function () {
$.ajax({
type: 'POST',
url: "your_url",
data : {"title":"mr","fname":"john","lname":"Annah","oname":"Clement","staffid":"123"},,
success: function (result) {
### your action after ajax
},
})
})
you can pass it in data like this,
$.ajax({
url: 'url',
type: 'GET',
data: { title:"mr",fname:"john",lname:"Annah",oname:"Clement",staffid:"123" } ,
contentType: 'application/json; charset=utf-8',
success: function (response) {
//your success code
}
});

Pass multiple php arrays in ajax request response

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));

jQuery Ajax posting not working

My jQuery ajax posting is not working. Here is the javascript
function SocialButtons() {
var $buttonWrapper = jQuery('.WrapperDiv');
if ($buttonWrapper.length){
var postData = $buttonWrapper.html();
jQuery.ajax({
type: 'POST',
url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
data: postData,
cache: false,
success: function(data) {
console.log(data);
},
contentType: "application/json",
dataType: 'json'
});
}
}
I am saving the data to be posted inside a hidden div like
<div class='WrapperDiv hidden'>{"post_id":392,"url":"http:\/\/www.wordpress-site\/post\/post-title\/","title":"SEO Friendly title"}</div>
All I am getting in return from the post.php page is an empty array. Here is my code for post.php
<?php
if(isset($_POST)){
print_r($_POST);
} else {
echo "0";
}
?>
Any Idea whats wrong?
EDIT : Its working after I removed
contentType: "application/json",
dataType: 'json'
What about something like this:
var postData = "data=" + encodeURCIComponent($buttonWrapper.html());
Than in PHP:
echo $_POST["data"];
Than parse it or something....
Couple of things to try,
Try to pass the data directly in to the data object first. If it
works then you can debug and see why it's not ready your hidden div.
instead of $buttonWrapper.html try $buttonWrapper.text();
function SocialButtons() {
var $buttonWrapper = jQuery('.WrapperDiv');
if ($buttonWrapper.length){
var postData = $buttonWrapper.**text**();
jQuery.ajax({
type: 'POST',
url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
data: **{'id':1}**,
cache: false,
success: function(data) {
console.log(data);
},
contentType: "application/json",
dataType: 'json'
});
}
}
Inside your jQuery ajax call, your data is not set to $_POST variable names. Hence why nothing is showing
Try changing your function to this:
function SocialButtons() {
var buttonWrapper = jQuery('.WrapperDiv');
if (buttonWrapper.length){
var postData = buttonWrapper.html();
jQuery.ajax({
type: 'POST',
url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
data: {postData: postData},
cache: false,
success: function(data) {
console.log(data);
},
contentType: "application/json",
dataType: 'json'
});
}
}
Then you should have a $_POST['postData'] variable on your print_r or var_dump of $_POST.
Its working after I removed
contentType: "application/json",
dataType: 'json'

Retrieving serialize data in a PHP file called using AJAX

Form sending AJAX code:
var str = $("form").serialize();
alert(str);
// var uns=#unserialize(str);
//alert(uns);
$.ajax({
type: "POST",
url: "update.php",
data: "box1="+str,
success: function(value)
{
$("#data").html(value);
}
HTML Form:
<form>
<input type=checkbox name=box[] value='1'/><input type=checkbox name=box[] value='2'/>
</form>
In my PHP:
$box=$_POST['box1'];
How can I access each of the box variable values in PHP side?
Your js should be like this:
var str = $("form").serializeArray();
$.ajax({
type: "POST",
url: "update.php",
data: str,
success: function(value) {
$("#data").html(value);
}
});
With php you should loop your result array.
$box = $_POST['box'];
foreach ($box as $x) {
echo $x;
}
Edit:
You have to use serializeArray function in jQuery. Then it will work with this code.
Provided that your server is receiving a string that looks something like this
$("form").serialize();
"param1=someVal&param2=someOtherVal"
...something like this is probably all you need:
$params = array();
parse_str($_GET, $params);
$params should then be an array modeled how you would expect. Note this works also with HTML arrays.
See the following for more information: http://www.php.net/manual/en/function.parse-str.php
Hope that's helpful. Good luck!
your JS should be like this -
var str = $( "form" ).serializeArray();
var postData = new FormData();
$.each(str, function(i, val) {
postData.append(val.name, val.value);
});
$.ajax({
type: "POST",
data: postData,
url: action,
cache: false,
contentType: false,
processData: false,
success: function(data){
alert(data);
}
});
Now do this in your php script -
print_r($_POST);
you will get all form data in alert box.
$data = array();
foreach(explode('&', $_POST[data]) as $value)
{
$value1 = explode('=', $value);
$data[$value1[0]] = validateInput($value1[1]);
}
var_dump($data['box']);
your data in php will contain a string like this
field1=value1&field2=value2&....
so you can get your value1 using $_POST['field1] , value2 with $_POST['field2']
Change
data: "box1="+str,
into
data: str,
serialize() will produce a string like: input1=value1&input2=value2. So in your php you can access each value with, for instance $value1 = $_PHP['input1'];
values=$("#edituser_form").serialize();//alert(values);
$.ajax({
url: 'ajax/ajax_call.php',
type: 'POST',
dataType:"json",
data: values,
success: function(){
alert("success");
},
error: function(){
alert("failure");
}
});
$box=$_POST['box'];
and $box is an array.

Categories