How to do a POST json request with jQuery? - php

How can I recreate a request with jquery which would work exactly as this PHP request?
$client = new Zend_Http_Client($uri);
$response = $client->setMethod(Zend_Http_Client::POST)
->setRawData(trim($json), 'application/json')
->request();
Thanks.

$.ajax({
cache:false,
type: 'POST',
url: "yoururl",
data:yourJsonData,
contentType: "application/json",
success: function(data) {
//do what you what with return data
}
});

Like this
$.postJSON("/application/json".
{
ID:5 // all parameters here for the method
},
function(data)
{
//data is what comes back from your function
});

Related

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

AJAX api request missing some data at controller $_GET

When i'm trying to send data(url) to API with ajax request, PHP CI controller not considering all parameters in $_GET. it just accepting up to &.
Is there any error in passing parameters? Please help. I tried passing direct url and encodeURI.
JQuery code
$.ajax({
type: "GET",
url: "<?= ROOT?>welcome/ajaxapiget",
data: encodeURI(http://localhost/webapi/list?categories[]=3&categories[]=12),
cache: false,
success: function (data) {
alert(data);
}
});
PHP
function ajaxapiget() {
$url = $_GET;`//its getting url as http://localhost/webapi/list?categories[]=3`
$curl = curl_init();
........
........
response $response;
}
also tried like this
$.ajax({
type: "GET",
url: "<?= ROOT?>welcome/ajaxapiget",
data: 'url=http://localhost/webapi/list?categories[]=3&categories[]=12)',
cache: false,
success: function (data) {
alert(data);
}
});
PHP
function ajaxapiget() {
$url = $_GET(url);`//its getting url as http://localhost/webapi/list?categories[]=3`
$curl = curl_init();
........
........
response $response;
}
When i alert
before sending request
url=http://localhost/webapi/courselist?categories[]=15&categories[]=17
response from controller (alert at ajax success)
$url = $_GET('url');
echo $url
alert response
http://localhost/webapi/courselist?categories[]=15
Try this
JQuery code
$.ajax({
type: "GET",
url: "<?= ROOT?>welcome/ajaxapiget",
data: {url:'http://localhost/webapi/list?categories[]=3&categories[]=12'},
cache: false,
success: function (data) {
alert(data);
}
});
PHP code
function ajaxapiget() {
$url = $this->input->get('url');//Getting $url as http://localhost/webapi/list?categories[]=3&categories[]=12
$curl = curl_init();
........
........
response $response;
}
Use $this->input->get() instead of $_GET[] in Codeingiter
Finally i solved this with encodeURIComponent
$.ajax({
type: "GET",
url: "<?= ROOT?>welcome/ajaxapiget",
data: 'url=http://localhost/webapi/list?' + encodeURIComponent('categories[]=15&categories[]=17'),
cache: false,
success: function (data) {
alert(data);
}
});
now the result is
http://localhost/webapi/courselist?categories[]=15&categories[]=17
encodeURIComponent will encode everything with special meaning, so you
use it for components of URIs
Source : https://stackoverflow.com/a/4540785

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

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'

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