Request response doesn't work - php

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

Related

How do I send files(images) in an array in PHP via ajax?

$('.result').click(function(event) {
var st = JSON.stringify(fileList);
$.ajax({
url: 'mailer.php',
type: 'POST',
data: st,
})
.done(function(data) {
console.log(st);
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
Mistake
https://i.stack.imgur.com/mtsAP.png
However, if you enter just:
console.log(fileList);
It shows everything correctly
https://i.stack.imgur.com/kNptA.png
PHP
<?php
$data = json_decode($_POST['fileList']);
echo $data;
From the console output in the second image it appears that fileList is an array of File objects. As such you should append them to a FormData object and set that as the data of your $.ajax() call. Try this:
$('.result').click(function(event) {
var fd = new FormData();
fileList.forEach(file => fd.append(file.name, file));
$.ajax({
url: 'mailer.php',
type: 'POST',
data: fd,
contentType: false, // required when sending FormData
processData: false // required when sending FormData
}).done(function(data) {
console.log(data);
}).fail(function() {
console.log("error");
}).always(function() {
console.log("complete");
});
});
From there you will need to use the $_FILES collection in PHP to access the files sent in the request, not $_POST.
https://i.stack.imgur.com/fYbhv.png
108 line
fileList.forEach(file => fd.append(file));

$.ajax $_POST to php returns empty array [duplicate]

I would like to post Json to a web service on the same server. But I don't know how to post Json using JQuery. I have tried with this code:
$.ajax({
type: 'POST',
url: '/form/',
data: {"name":"jonas"},
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
But using this JQuery code the data is not received as Json on the server. This is the expected data at the server: {"name":"jonas"} but using JQuery the server receive name=jonas. Or in other words, it's "urlencoded" data and not Json.
Is there any way to post the data in Json format instead of urlencoded data using JQuery? Or do I have to use a manual ajax request?
You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param to serialize the object into name-value pairs.
If you pass the data as a string, it won't be serialized:
$.ajax({
type: 'POST',
url: '/form/',
data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Base on lonesomeday's answer, I create a jpost that wraps certain parameters.
$.extend({
jpost: function(url, body) {
return $.ajax({
type: 'POST',
url: url,
data: JSON.stringify(body),
contentType: "application/json",
dataType: 'json'
});
}
});
Usage:
$.jpost('/form/', { name: 'Jonh' }).then(res => {
console.log(res);
});
you can post data using ajax as :
$.ajax({
url: "url",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: 'value1', email: 'value2' }),
success: function (result) {
// when call is sucessfull
},
error: function (err) {
// check the err for error details
}
}); // ajax call closing
I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data
$.fn.postJSON = function(url, data) {
return $.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json'
});
The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.
var Data = {
"name":"jonsa",
"e-mail":"qwerty#gmail.com",
"phone":1223456789
};
$.ajax({
type: 'POST',
url: '/form/',
data: Data,
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Using Promise and checking if the body object is a valid JSON. If not a Promise reject will be returned.
var DoPost = function(url, body) {
try {
body = JSON.stringify(body);
} catch (error) {
return reject(error);
}
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: url,
data: body,
contentType: "application/json",
dataType: 'json'
})
.done(function(data) {
return resolve(data);
})
.fail(function(error) {
console.error(error);
return reject(error);
})
.always(function() {
// called after done or fail
});
});
}

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

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

How to get JSON vars from PHP script

I have a problem:
I have a JS function which sending data to php script, then PHP script returning JSON data from database QUERY and I want to get values returned from PHP script.
<script type="text/javascript">
<!--
jQuery('#wysz2').submit(function() {
var myData = {
"rodzaj_konta": jQuery('#rodzaj_konta').val(),
"miejscowosc": jQuery('#miejscowosc').val()
};
jQuery.ajax({
url: 'http://somescript.php?action=results',
type: 'GET',
data: myData,
dataType: 'json',
beforeSend: function() {
jQuery('#loading').html('<p>loading...</p><img src="loading.gif" />'); //Loading image during the Ajax Request
},
error: function(xhr, textStatus, errorThrown) {
alert("Error: " + (errorThrown ? errorThrown : xhr.status));
},
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
}
});
return false;
});
//-->​
</script>
The PHP script returning data in proper format using:
header('Content-Type: application/json');
echo json_encode($data);
When I'm trying to alert(data), I get always a null.
How to get this returned JSON data ?
EDITED:
It's strange, because I have changed sending method to POST.
PHP returning JSON:
[{"nazwa":"Test","nazwa_firmy":"Testowa","ulica":null,"numer_domy":"2A","numer_mieszkania":"11","kod_pocztowy":"00-189","miejscowosc":"Warszawa","telefon":"213-123-132","nip":"112-312-31-31","regon":"231232133","adres_www":"http:\/\/www.gogl.epl","rodzaj_uzytkownika":"serwis"}]
But my JQUERY AJAX Script still returning null.
So my script now looks like this:
<script type="text/javascript">
<!--
jQuery('#wysz2').submit(function() {
var myData = {
rodzaj_konta: jQuery('#rodzaj_konta').val(),
miejscowosc: jQuery('#miejscowosc').val()
};
jQuery.ajax({
url: 'http://somedomain.com/skrypt.php?action=wyniki_wyszukiwania',
type: 'GET',
data: myData,
dataType: 'json',
contentType: "application/json; charset=utf-8",
jsonp: "jsoncallback",
beforeSend: function() {
jQuery('#loading').html('<p>ładowanie...</p><img src="loading.gif" />');//Loading image during the Ajax Request
},
error: function (xhr, textStatus, errorThrown) {
alert("Error: " + (errorThrown ? errorThrown : xhr.status));
},
success: function (data) {
alert(JSON.stringify(data));
console.log(data);
}
});
return false;
});
//-->
</script>
Any ideas ?
you are constructing your variables while sending in a wrong way semicoluns for object names is not there according to definitions
try this
var myData = {
rodzaj_konta: jQuery('#rodzaj_konta').val(),
miejscowosc: jQuery('#miejscowosc').val()
};
and while alerting your json data try
alert(JSON.stringify(your_json_obj));
Try to alert the object of the result...
Means if json in the format {"responseCode":"001","responseMsg":"success"}
Then alert data.responseCode
In success of your ajax function try something like this
var objParams1 = $.parseJSON(data);
console.log(objParams1);
alert(objParams1.Testowa)

Categories