Posting object using ajax to PHP - json

I'm trying to post to php using ajax.
I can't seem to figure why the data isn't been posted.
The console.log shows 'success'.
var obj shown is for check only.
the code:
var obj = {'age':'32'};
obj = JSON.stringify(obj);
$.ajax({
type: 'post',
data: {'phpobj': obj},
dataType: 'json',
success: function(data){
//do whatever.
console.log('success');
}
});
and the php (in the same url):
if (isset($_POST['phpobj'])) {
echo 'phpobj is POSTED:</br></br>';
$php_obj = $_POST['phpobj'];
$decoded = json_decode($php_obj, true);
var_dump($decoded);
} else {
echo 'phpobj Wasnt POSTED';
}
Thanks for helpers.

Please try replacing your code like this
JQUERY
$.ajax({
type: 'post',
data: {'age': 32},
dataType: 'json',
success: function(data){
//do whatever.
console.log('success');
}
});
PHP
if ($_SERVER['REQUEST_METHOD'] == "POST") {
echo 'REQUEST is POSTED:</br></br>';
$age= $_POST['age'];
var_dump($_POST);exit;
} else {
echo 'phpobj Wasnt POSTED';
}
Change the rest according to your requirements. Thanks

i encounterd the same problem before, i gave up using ajax to post.
you can use the jquery to create a form then let the user submit it to php.

Related

Problem with php handling ajax in the same file

I have a serious problem, I can't receive data sent by ajax in php. I've read many tutorial about that but it still not resolved. So if you guys have the magic solution, it'll make my day.
Here is the code, note that it is in the same file problem.php.
assocStored is an array or object, and it have the right data if I check it on jvascript
window.onload = function(e){
var assocStored = JSON.parse(localStorage.getItem("associes"));
$.ajax({
type : "POST",
data : {"problem" : assocStored},
success : function(res){
console.log("action performed successfully");
}
})
}
<div>
<h3>php</h3>
<?php
var_dump ($_POST);
if( isset($_POST['problem']) ){
foreach ($_POST['problem'] as $associe) {
echo($associe["sex"]." ".$associe["firstname"]." ".$associe["lastname"]);
}
exit;
}
?>
</div>
As my comment above, I guess your request send a GET method.
In your code, you are using type is POST but type is an alias for method. You should use type if you are using versions of jQuery prior to 1.9.0.
So you can modify your ajax to here:
$.ajax({
method: "POST",
data : { "problem" : JSON.stringify(assocStored) }, // convert to json
dataType: "json", // add type
success : function(res){
console.log("action performed successfully");
}
})
If it continues not working, add this code to ajax:
$.ajax({
method: "POST",
data : { "problem" : JSON.stringify(assocStored) }, // convert to json
dataType: "json", // add type
beforeSend: function(req) {
if (req && req.overrideMimeType) {
req.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success : function(res){
console.log("action performed successfully");
}
})
I hope it works.

CKEDITOR load data from database AJAX

Hi guys I need to load data from my database into CKEditor. I searched it allready on google but I could not find recent solutions, and I tried some of them but they did not work. I tried this : var data = CKEDITOR.ajax.load( data.data[0].name );
this is my json
{"result":true,"message":"Post data success","data":[{"url":"sales","naam":"Sales\/B2B","id":"80","koppelid":"80","omschrijving":"
Sales\/B2B<\/p>\r\n"}]}
and here is my AJAX
$(document).on('focusout','#select-afdeling',function(){
$.ajax({
url: 'admin/afdeling/afdeling',
type: 'POST',
dataType: 'json',
data: $(' #select-afdeling').serialize(),
success: function(data){
if (data.result !== true) {
}else{
$("#afdeling-naam").val();
$("#afdeling-naam").attr("value",data.data[0].naam);
$("#afdeling-naam").val();
}
}
});
});
You can use SetData().
Example:
CKEDITOR.instances.editor1.setData('<p>This is the editor data.</p>');

Country autosuggest is working but failsed in webproxy?

I am building a codeigniter site which is almost done. In my site country autosuggest is working fine. But when I am trying to acces the site with webproxy hidedoor.com, country auto suggest is not working. I really dont know whow to tackle it. I had tried unsuccesssful attempt of jsonp as well. So can you guy's help me?
my json handling code is,
$(function() {
$("#ville").autocomplete({
source: function(request, response) {
$.ajax({ url: "<?php echo base_url().'autocomplete/suggestcity'; ?>",
data: { term: $("#ville").val()},
crossDomain: true,
dataType: "json",
//jsonp: 'callback',
//dataType: "html",
type: "POST",
success: function(data){
var citydetails = new Array();
for(i=0; i<data.lang.length; i++)
{
citydetails[i]=data.lang[i]+', '+data.countryname[i];
}
response(citydetails);
$(".ui-menu-item a").click(function(){
set_value($(this).html());
for(i=0; i<=citydetails.length; i++)
{
if(citydetails[i] == $(this).html()){
$("#co_num").val(data.co_num[i]);
$("#geoname_id").val(data.geoname_id[i]);
}
}
});
}
});
},
minLength: 2
});
});

Data not getting saved using JQuery.ajax

I want to save data from Textbox on Button click. I am using JQuery AJAX for this task like below. Please note that I made this tags inside theme function.
function theme_user_post_block($vars)
{
$themeUserCommentInput ='';
$themeUserCommentInput .= '<textarea id="txt_1"rows="1" cols="50"></textarea>';
$themeUserCommentInput .= '<input type="submit" value="Post Comment" align="center"
class="btnPostComment" id="btn_1" />'
return $themeUserCommentInput;
}
This able to show me Textbox and Button inside the page. Now here is my JS code:-
(function($)
{
Drupal.behaviors.PostComment= {
attach: function (context, settings) {
$('.btnPostComment', context).click(function (event) {
var post = "&newcomment=Comment1&logid=log1";
jQuery.ajax({
url: 'postcomment',
type: 'POST',
dataType: 'json',
data: post,
success: function (data) { alert(data); },
error: function(jqXHR, textStatus, errorThrown){alert(textStatus +
errorThrown);}
});
});
}
}
})(jQuery);
Next I create a Menu Page with URL Name as follows:-
function postcomment_menu(){
$items=array();
$items['postcomment']=array(
'title'=>t(''),
'type'=> MENU_CALLBACK,
'page callback' => 'user_comment_post',
'access arguments' => array('access content'),
);
return $items;
}
function user_comment_post(){
global $user;
$cid = db_insert('user_comment')
->fields(array(
'comment_user_id' => $user->uid,
'reference_id' => $_POST['logid'],
'comment_desc'=>$_POST['newcomment'],
'createdon'=>REQUEST_TIME,
))
->execute();
if($cid!=0)
{
//GetUserComments($i);
drupal_json_output("success");
}
}
So I have done all things that is required for jQuery+Ajax Submit functionality. When I press "Post Comment" button it gives me error in alert says "errorundefined". The alert shows as a result of error inside the jQuery.AJAX function. Also the custom menu callback is also not getting called.
post the data as object...and make sure your post url is correct.. the url doesn't looks correct
var post = {newcomment: 'Comment1',logid:'log1'};
I came to end of this problem. I dont know what might be the resolution or root cause but I end up solving this problem. I meagre add one line(async: false) in my jQuery.ajax function and everything works perfectly. Please see the code below:
jQuery.ajax({
url: 'postcomment',
type: 'POST',
dataType: 'json',
async: false,
data: post,
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + errorThrown);
}
});
If anyone have any knowledge as what this line will do then please share with us.

Calling service from Html

i want to call asp.net web service from java script and pass the parameters to it .is there any code sample or demostration that will help me to acheive that??
thanks in advance
JQuery:
function AddLocation(ParentID) {
$.ajax({
type: "POST",
url: "../server.asmx/Save",
data: "{'ID':'0','ParentID':'" + ParentID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var item = document.createElement('option');
item.value = data.d.split("$")[0];
item.text = name;
//do stuff
}
});
}
jQuery supports this behavior. you can use jQuery to do the ajax call as show below. this method has two call back functions for success and for failure.
function loadData()
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: 'methodurl',
success: methodSuccedded,
error: methodFailure
});
}
function methodSuccedded()
{
//do your logic.
}
function methodFailure()
{
//do your logic.
}
You can do so, using AJAX, and get the response from the server as an JSON object.
var xmlHttp = new ActiveXObject("Microsoft.XmlHttp");
var url = "Service1.svc/ajaxEndpoint/";
url = url + "Sum2Integers";
var body = '{"n1":';
body = body + document.getElementById("num1").value + ',"n2":';
body = body + document.getElementById("num2").value + '}';
// Send the HTTP request
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send(body);
// Create result handler
xmlHttp.onreadystatechange= function X()
{
if(xmlHttp.readyState == 4)
{
result.innerText = xmlHttp.responseText;
}
}
Getting the response as JSON would help you evualte it asn object and u can act on it through JavaScript.
See these links for reference:
http://blogs.msdn.com/b/alikl/archive/2008/02/18/how-to-consume-wcf-using-ajax-without-asp-net.aspx
http://dotnetslackers.com/articles/ajax/JSON-EnabledWCFServicesInASPNET35.aspx
The below link is a pretty decent method from my experience.
http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/