Calling method in PHP file from separate JavaScript file - javascript

I have a javascript file from which I am trying to make a ajax call to execute method of a different php file.
Javascript file - a.js
function update() {
$.ajax({
url:"abcd.php",
type: "POST",
dataType: 'json',
data: {"updateMethod()"}
success:function(result){
console.log(result);
}
});
}
PHP file - abcd.php
<?php
class abcd {
public function updateMethod() {
//execute this part of the code
}
public function insertMethod() {
}
public function deleteMethod() {
}
}
I am not able to make a call to the PHP method. What is wrong with my AJAX query or what do I need to do in PHP file side to call the method.

I don't know what you try to do, but you can do it this way:
function update() {
$.ajax({
url:"abcd.php",
type: "POST",
dataType: 'json',
data: {methodName: "updateMethod"},
success:function(result){
console.log(result);
}
});
}
On server side:
<?php
class abcd {
public function updateMethod() {
//execute this part of the code
}
public function insertMethod() {
}
public function deleteMethod() {
}
}
$abcd = new abcd();
$method = $_POST['methodName'];
$result = $abcd->$method();

Remove this line
dataType: 'json',
and send data without json
If you sending json in php must be:
$data = file_get_contents('php://input');
PHP "php://input" vs $_POST
Or beter jquery:
var methodName = "YourMethodName";
var y = "Cymbal";
$.post( "test.php", { methodName: methodName, lastname: y })
.done(function( data ) {
alert( "Data Loaded: " + data );
});

Maybe something like this is more secure and I think you also need function arguments for CRUD actions(Not tested):
backend:
class CRUD
{
public function update($args)
{
$input = $args['exampleInput'];
// sanitize input
// prepared query
// $stmt->execute($input);
}
}
function access($class, $method, $args)
{
if (method_exists($class, $method)) {
return call_user_func_array([$class, $method], [$args]);
}
}
$data = file_get_contents('php://input');
access('CRUD', $data->method, json_decode($data->args));
js:
function handleAction(methodName, arguments) {
$.ajax({
url: "crudFile.php";
type: "POST",
data: { method: methodName, args: arguments },
dataType: 'json',
success: function (result) {
console.log(result);
}
});
}
var inputs = {
exampleInput: function () {
return document.getElementById('your-div-id').textContent();
},
};
// usage
handleAction('update', inputs);

Related

Resource can not be found in Asp.NET although path is correct?

I am passing values to the action method using the ajax call. My action method name is TagTargets and this method has three parameters. I am also giving the exact path also but getting the error The resource cannot be found.
//Ajax Call to get targets Data
function TargetsData() {
var realTags = $('#Raw_Tag_List').val();
var calculatedTags = $('#Calculated_Tag_List').val();
var manulTags = $('#Manual_Tag_List').val();
$.ajax({
url: 'TagTargets',
type: 'Post',
contentType: 'application/json',
dataType: 'json',
data: { 'RealTags': realTags, 'CalculatedTags': calculatedTags, 'ManulTags':manulTags},
success: function (data) {
if (data.success) {
alert('Ok')
}
else {
alert('Not ok');
}
}
});
debugger;
}
//Action Method
[HttpPost]
public JsonResult TagTargets(List<string> RealTags, List<string> CalculatedTags, List<string> ManulTags)
{
return Json(true);
}
change your url to a valid url.
url: "#Url.Action("TagTargets","ControllerName");",

JSON Object always return undefined with AJAX

The JSON Object always return undefined in spite of the object contains data, i check it by using breakpoints in debugging
This is Action method in Controller:
public JsonResult GetMoreComments(int CommsCount, int ArticleID)
{
List<ComViewModel> comms = articleService.GetMoreComments(ArticleID, CommsCount);
return Json( comms );
}
and I also replaced the code in Action method to simple code like that but not work too:
public JsonResult GetMoreComments(int CommsCount, int ArticleID)
{
ComViewModel com = new ComViewModel
{
CommentContent = "cooooooooooontent",
CommentID = 99,
SpamCount = 22
};
return Json( com );
}
This is jQuery code for AJAX:
function GetMoreComments() {
$.ajax({
type: 'GET',
data: { CommsCount: #Model.Comments.Count, ArticleID: #Model.ArticleID },
url: '#Url.Action("GetMoreComments", "Comment")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var JsonParseData = JSON.parse(result);
alert(JsonParseData[0].CommentID)
alert(result[0].CommentID);
alert(result[0]["CommentID"]);
}
});
}
Usually you would have to parse your data if you need to alert it the way you have it. alert(result) should show data. If you need to access array of objects you must parse it first. Here is my example....
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
//PARSE data if you need to access objects
var resultstring = response.replace(',]',']');
var JsonParseData = JSON.parse(resultstring);
alert(JsonParseData[0].address)
});
That is wordpress ajax but its the same concept

How to call a codeigniter function in ajax?

In controller I have a _remap() for routing.
My controller is as follows:
public function _remap($id)
{
$this->index();
}
public function index()
{
$this->accesscontrol->can_or_redirect('view', 'translation');
$this->output->view('translation/language');
}
function process(Request $request){
// if(Response::ajax()) return "OK";
return json_encode(array('ok'));
}
My view is as follows:
$('#lang_choice1').each(function() {
$('#src_trans_lang').val($("#lang_choice1 option:selected").val());
var msg = $(this).val();
$.ajax({
type: "POST",
url: '<?=site_url('translation/language/process')?>',
data: msg,
success: function(data){ }
});
return false;
});
I am trying to call the function process in ajax and its not getting called. How do I need to modify the _remap function to call ajax calls as well?
Try This
Script part
$('#lang_choice1').each(function () {
$('#src_trans_lang').val($("#lang_choice1 option:selected").val());
var msg = $(this).val();
$.ajax({
type: "POST",
url: '<?= site_url('language/process') ?>',
data: {"msg":msg},
dataType:"json",
success: function (data) {
console.log(data);
}
});
return false;
});
Controller process function
function process() {
$data = $this->input->post();
$result['status'] = "ok";
$result['response'] = $data;
echo json_encode(array($result));
exit(0);
}
Check response in console

Ajax jquery sending Null value to Mvc4 controller

I have a problem related the ajax call request searched for it on stack overflow tried all the related help that i got but can't solve the problem. the problem is that i request to a controller from my view using this code.
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var dataJson = {"contactNumber": number};
$.ajax({
type: "POST",
url: "../contactWeb/messages",
data: JSON.stringify(dataJson),
//data: dataJson,
//contentType: "application/json",
contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>
and the controller that receives the call is
[HttpPost]
public JsonResult messages(string dataJson)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , dataJson);
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
but it passes NULL value to the controller
There are couple of issues need to be fixed
whats the need of
JsonRequestBehavior.AllowGet
when your action type is post.
If you are using asp.net mvc4 use Url.Action to specify url i.e
url:"#Url.Action("ActionName","ControllerName")"
Now Talking about your issue.
Your parameter names must match, change dataJson to contactNumber.Though its ok to use there isnt any need to use JSON.stringify as you are passing single string parameter.
[HttpPost]
public JsonResult messages(string contactNumber)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
Hi could you change the name of your parameters string dataJson in your action to contactNumber in respect to the object you pass via your Ajax call
[HttpPost]
public JsonResult messages(string contactNumber) //here
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , contactNumber); //and here
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
If you want to get JSON in messages() try this:
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var data = {"contactNumber": number};
var dataJson = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../contactWeb/messages",
dataType: 'text',
data: "dataJson=" + dataJson,
//data: dataJson,
//contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>

Receiving json via ajax asp.net

My variable data in function ShowFavorits is undefined even do that my ajax call do return a json string.
<script type="text/javascript">
$(document).ready(function () {
ShowFavorits();
function AjaxGet() {
var param = "{'_userID': '1337'}";
$.ajax({
type: "POST",
url: "/webservices/MinSide.asmx/GetFavorits",
data: param,
contentType: "application/json;",
dataType: "json",
success: function (data) {
if (data.hasOwnProperty("d")) {
return (data.d);
}
},
error: function (data) {
//error
}
});
}
function ShowFavorits() {
var data = AjaxGet();
$("#addedList").html(
$("#addedTemplate").render(data)
);
}
});
[WebMethod]
public string GetFavorits(string _userID)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.MaxJsonLength = int.MaxValue;
string JsonData = string.Empty;
var db = new ModelDataContext();
var list = db.table.Where(x => x.userID == _userID).OrderBy(x=> x.TimePin).ToList();
JsonData = jss.Serialize(list);
return (JsonData);
}
Why cant i return the result from my ajax?
Hope someone can help me, have been stuck for hours now debugging this.
Thanks in advance.
The call to $.ajax in AjaxGet is asynchronous: the function returns undefined because the ajax call hasn't finished.
You should move the call to ShowFavourits into the ajax success function so that it executes once the ajax call is complete/successful
<script type="text/javascript">
$(document).ready(function () {
// Kick-off the ajax request
AjaxGet();
function AjaxGet() {
var param = {_userID: '1337'};
$.ajax({
type: "POST",
url: "/webservices/MinSide.asmx/GetFavorits",
data: param,
dataType: "json",
success: function (data) {
if (data.hasOwnProperty("d")) {
ShowFavorits(data.d); // Pass the data to the template
}
}
});
}
function ShowFavorits(data) {
$("#addedList").html(
$("#addedTemplate").render(data)
);
}
});

Categories