Data not getting saved using JQuery.ajax - json

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.

Related

ASP.NET jQuery reload element on submit (Ajax POST/GET)

Using ASP.NET I'm trying to reload only a part of my webpage using jQuery instead of using "location.reload();". It's a single page application. As the user submits a form the user credits change and the new value should be updated without a full page reload. The value for credits is retrieved through an Ajax Get Call and should be updated after an Ajax Post Call. I tried using "$("#userCredits").load(?);" within the Ajax Post but can't get it right. Do I need to make a partial view to achieve this? Thanks for helping.
HTML _Layout.cshtml
<ul class="nav masthead-nav">
<li id="userCredits">
//Paragraph retrived from Ajax Get Call: "#reloadUserCredits".
</li>
<li>
<p class="user">#User.Identity.GetUserName()</p>
</li>
</ul>
JS
//Ajax POST user pack (buy pack)
$("#postform").submit(function (e) {
e.preventDefault();
var data = {
applicationUserId: $("#userId").val().trim(),
packId: $("input.activeImg").val().trim(),
}
$.ajax({
url: '/api/buypack',
type: 'POST',
dataType: 'json',
data: data,
success: function () {
document.getElementById("postform").reset();
location.reload();
},
error: function () {
}
});
});
// Ajax GET user credits (navbar userCredits)
var $credits = $('#userCredits')
$.ajax({
type: 'GET',
url: '/api/user',
success: function (credits) {
$.each(credits, function (i, user) {
$credits.append('<p id="reloadUserCredits" class="credits">Credits: ' + user.credits + '</p>');
});
}
});
As I understand... You already are getting the user credits via Ajax on page load. So you only need to do it again after he bought some more.
Have the Ajax request to /api/user in a named function. Below, I called it get_credits(). Run it on page load AND on success of the Ajax request to /api/buypack.
//Ajax POST user pack (buy pack)
$("#postform").submit(function (e) {
e.preventDefault();
var data = {
applicationUserId: $("#userId").val().trim(),
packId: $("input.activeImg").val().trim(),
}
$.ajax({
url: '/api/buypack',
type: 'POST',
dataType: 'json',
data: data,
success: function () {
document.getElementById("postform").reset();
//location.reload();
// Refresh the credits displayed on the page
get_credits();
},
error: function () {
}
});
});
// Ajax GET user credits (navbar userCredits)
var $credits = $('#userCredits')
function get_credits(){
$.ajax({
type: 'GET',
url: '/api/user',
success: function (credits) {
$.each(credits, function (i, user) {
$credits.html('<p id="reloadUserCredits" class="credits">Credits: ' + user.credits + '</p>');
});
}
});
}
// Run on page load
get_credits();

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.

Posting object using ajax to PHP

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.

Ajax get request succeds on localhost but fails online

I'm try to get data via an ajax get request in Wordpress and I wrote a script in javascript and another in php to handle it.
The code for javascript is the following:
window.loadServices = function loadServices(){
var data = {
action: 'get_services',
perpage: '6',
};
$.ajax({
type: 'GET',
url: sendbooking.ajaxurl,
data: data,
dataType: 'json',
success: function (response) {
post = response.data;
console.log(response);
$.each(post, function(){
elem = $(this)[0];
media = elem._links['wp:featuredmedia']
var media_href;
$.each(media, function(){
media_href = $(this)[0].href;
})
// console.log(elem);
var image;
$.ajax({
type: 'GET',
url: media_href,
dataType: 'JSON',
success: function(data){
image = data.source_url;
},
async: false,
})
$('.services .elements .elements-container').append(
$('<div />', {
class: 'loader',
}).append(
$('<img />', {
src: '/wp-content/themes/farmhouse/assets/images/loader.gif'
})
)
)
setTimeout(function(){
$('.loader').fadeOut();
}, 2000);
$('.services .elements .elements-container').append(
$('<div />', {
class: 'element '+elem.type,
}).append(
$('<a />', {
href: elem.link
}).append(
$('<div />', {
class: 'element-image',
}).append(
$('<img />', {
src: image,
})
)
)
).append(
$('<h5 />', {
class: 'element-title',
}).append(
$('<a />', {
href: elem.link,
text: elem.title.rendered
})
)
)
)
setTimeout(function(){
$('.loader').remove();
}, 2000);
})
},
});
}
This is instead the code for php:
if(!function_exists('get_services')):
function get_services(){
$data = $_GET;
$json_feed = get_site_url() . '/wp-json/wp/v2/service?per_page='.$data['perpage'];
$json = file_get_contents($json_feed);
$json_decoded = json_decode($json);
wp_send_json_success($json_decoded);
}
add_action('wp_ajax_get_services', 'get_services');
add_action('wp_ajax_nopriv_get_services', 'get_services');
endif;
The problem I'm having is that on localhost, this works fine, I get the content I need, without any problem. When I'm going to deploy the site on line, the ajax doesn't retrieve anything. Throwing console.logs, I noticed that the scripts fail when getting data from the api url (file_get_contents), but if you go there directly via browser's address bar, or through postman, data are served correctly. (You can test: http://www.dsoftwarelab.it/ilpiastrino/wp-json/wp/v2/service?per_page=6).
I really don't know how to solve it, since I've really tried everything.
Case 1 : You don't have access rights on server.
If you have root access, edit php.ini, usually located at /etc/php.ini.
If you dont have root access, try to add ini_set('allow_url_fopen', 'On'); or ini_set('allow_url_fopen', '1');.
If you can't see php.ini, try using phpinfo() in a PHP script to find the php.ini location.
Case 2 : You have miss the SSL parameter in .
$url= 'https://example.com';
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$response = file_get_contents($url, false, stream_context_create($arrContextOptions));
Case 3 : 403 FORBIDDEN
The server responds with an "403 FORBIDDEN" status code. So file_get_contents() works fine, but the server you are trying to access (or a proxy or something in between) dont allow it.
Do not convert json to array. comment this line $json_decoded = json_decode($json);
if(!function_exists('get_services')):
function get_services(){
$data = $_GET;
$json_feed = get_site_url() . '/wp-json/wp/v2/service?per_page='.$data['perpage'];
$json = file_get_contents($json_feed);
//dont need this line
//$json_decoded = json_decode($json);
wp_send_json_success($json);
}
add_action('wp_ajax_get_services', 'get_services');
add_action('wp_ajax_nopriv_get_services', 'get_services');
endif;

Append additional HTML result in calling MVC action by Ajax in DNN8

I'm new in DNN development.
I have created a very simple module in Visual studio--- A textbox and a button.
I just want to call the action in a controller by click the button, then show the return result in the textbox.
The code call the action success, but not sure why append lots of HTML inforation in the result.
Here is the action in the controller:
public ActionResult test1()
{
return Content("Return something");
}
Here is the Ajax code from the View:
$(document).ready(function () {
$("#btnSub").click(function () {
//alert(this.action);
$.ajax({
type:"GET",
contentType:"application/text",
url: "#Url.Action("test1", "Sky")",
data:"",
dataType: "text",
success: function (data) { $("#txtResult").val(data); alert("Success!") },
error:function(){alert("Failed!")}
});
});
});
And here is the result show in the textbox:
Anyone can let me know why the HTML information returned? Actually, I don't need it.
Thanks
Unfortunately, as described in DNN8 MVC unsupported features, it's not yet possible to return a JsonResult. So the solution I used is to return an ActionResult (although the function returns Json):
public ActionResult Test()
{
return Json(new { success = true });
}
On jquery side, I setup ajax call to receive result as html. This avoid the browser to display a parsing error. Finally, just need to remove the html part and manually parse the response. It's not very clean, but the only solution I found until DNN support JsonResult.
$.ajax({
url: '#Url.Action("Index", "Contact")',
type: 'POST',
dataType: 'html',
data: $('#contact-form input').serialize(),
success: function (response) {
jsonPart = response.substring(0, response.indexOf("<!DOCTYPE html>"));
var data = JSON.parse(jsonPart);
if (data.success) {
alert("Great");
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error!");
}
});
EDIT : Improved solution
DNN8 now support IMvcRouteMapper. You can then register a route in RouteConfig.cs. Once done, you can call the function using following URL :
/DesktopModules/MVC/ModuleName/Controller/Action
The action can return a JsonResult. But pay attention, if you just call that function, it will fail with a null exception on ModuleContext. You have to include in the ajax call the following header :
headers: {
"ModuleId": #Dnn.ModuleContext.ModuleId,
"TabId": #Dnn.ModuleContext.TabId,
"RequestVerificationToken": $("input[name='__RequestVerificationToken']").val()
}
You can find the module complete code here.
This is a working ajax call in DNN 9. You dont have to use #urlaction it will give whole html as well as data. dnn.getVar("sf_siteRoot", "/") +
"DesktopModules/MVC/ModuleName/Controller/Action", this does the trick and don't forget to add the header otherwise it will throw 500 error.
$.ajax({
url: dnn.getVar("sf_siteRoot", "/") +
"DesktopModules/MVC/ModuleName/Controller/Action",
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: "{ 'id':" + JSON.stringify(3543)+" }",
headers: {
"ModuleId": #Dnn.ModuleContext.ModuleId,
"TabId": #Dnn.ModuleCon`enter code here`text.TabId,
"RequestVerificationToken":
$("input[name='__RequestVerificationToken']").val()
},
success: function (response) {
debugger;
},
error: function (errmsg) {
alert("Error!");
}
});
Your controller should be
[HttpPost]
public ActionResult ActionName(int id)
{
var data = id;
return BuidJsonResult(true,data);
}
Happy Coding :)