how to send $(this).atta('id') using cake php js helper - javascript

HIi Folks i am having one issue please help me i want to send some data to my controller using ajax call i have written all code but for data field
<?php echo $this->Js->get('.menu')->event('click',$this->Js->request(array('controller' => 'restaurants', 'action' => 'getItem'),array('async' => true,'method'=>'POST','update' => '#HFNames','data'=>'$(this).attr(id)')),false); ?>
when ajax call hits it take "$(this).attr(id)" as a params but i need the value of cureent click
js helper genrate this
if we remove that double quote from this genrated script then its working
data: "$(this).attr(id)",
why this get quoted
<script type="text/javascript">
$(".menu").bind("click", function (event) {
$.ajax({
async: true,
data: "$(this).attr(id)",
dataType: "html",
success: function (data, textStatus) {
$("#HFNames").html(data);
},
type: "POST",
url: "\/foodkingkong\/restaurants\/getItem"
});
return false;
});

try this instead.
echo $this->Js->buffer('$(".menu").bind("click", function (event) {
$.ajax({
async: true,
data: $(this).attr(id),
dataType: "html",
success: function (data, textStatus) {
$("#HFNames").html(data);
},
type: "POST",
url: "/foodkingkong/restaurants/getItem"
});
return false;
});'
);

Hi Himanshu we had planned to do the same directly using jquery but wanted to do the same via cakephp bind function only.
What will be the difference if we pass the js in buffer.

Related

How to intercept POST data with Javascript

I am using this javascript function to send data to my php script (via POST) I am then using this information to retrieve data from my database and I would like to reuse the information retrieved in my JavaScript code.
Here is my code :
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function() {
// HERE I would like to inctercept the data that my php script put in myFunctions.php produces and use it to generate content;
}
});
});
So basically, when clicking on the button #validerChoixDeCours, my code sends some data to myFunctions.php which generates a response stored in a php variable and I want to use that response in my JS code.
Thank you in advance for your help :)
Its actually quite easy!
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function(e) {
e contains the response from the php script
}
});
});
The first parameter of success contains the response from the request. so, in this case, the 'e' variable contains the output which you can use.
Add data variable
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function(data) {
alert(data);
}
});
});
make sure your server side code look like this
<?php
$output = "Any String or Array";
echo json_encode($output);
?>

Get data from a different php file using JQuery

I have an JQuery function which submits data from a php form to a different php file(submitForm.php). The submission works fine and there isn't any problem whatsoever, below is the handler:
submitHandler : function(){
$.ajax({
type: "POST",
cache:false,
url: "submitForm.php",
data: $('#form').serialize(),
success: function(data) {
}
});
}
Now, I want to be able get data from the submit form (submitForm.php), and load it into a different page.
This is my submitForm.php
<?php
$name="Amanda";
$age="23";
$data = array("name"=>"$name","age"=>"$age");
header("Content-Type: application/json");
echo json_encode($data);
?>
This is how my new submitHandler looks like
submitHandler : function(){
$.ajax({
type: "POST",
cache:false,
url: "submitForm.php",
data: $('#form').serialize(),
success: function(data) {
var name= html(name);
var age=html(age);
$("#message").load("newpage.php",{name:name,age:age});
}
});
}
I think I am doing it wrong, I would be grateful if somebody could correct me or give an idea as to how to do this. Thanks
It should be like this. If you want to take your returner data you should use formal parameter of success function.
submitHandler : function(){
$.ajax({
type: "POST",
cache:false,
url: "submitForm.php",
data: $('#form').serialize(),
dataType : 'json',
success: function(data) {
var name= data.name;
var age=data.age;
$("#message").load("newpage.php",{name:name,age:age});
}
});
}
Edit: Also you need dataType: 'json' line.

Send data from a javascript ajax function to a jsp

This is what I am trying to do. On a home page.. say /home.jsp, a user clicks on a link. I read value of the link and on the basis of which I call a RESTful resource which in turn manipulates database and returns a response. Interaction with REST as expected happens with use of JavaScript. I have been able to get information from REST resource but now I want to send that data to another JSP.. say /info.jsp. I am unable to do this.
I was trying to make another ajax call within success function of parent Ajax call but nothing is happening. For example:
function dealInfo(aparameter){
var requestData = {
"dataType": "json",
"type" : "GET",
"url" : REST resource URL+aparameter,
};
var request = $.ajax(requestData);
request.success(function(data){
alert(something from data); //this is a success
//I cannot get into the below AJAX call
$.ajax({
"type": "post",
"url": "info.jsp"
success: function(data){
alert("here");
("#someDiv").html(data[0].deviceModel);
}
});
How do I go about achieving this? Should I use some other approach rather than two Ajax calls? Any help is appreciated. Thank You.
You can use the following function:
function dealInfo(aparameter) {
$.ajax({
url: 'thePage.jsp',
type: "GET",
cache: false,
dataType: 'json',
data: {'aparameter': aparameter},
success: function (data) {
alert(data); //or you can use console.log(data);
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': data},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
});
}
Or make the AJAX call synchronous:
function dealInfo(aparameter) {
var request = $.ajax({
async: false, //It's very important
cache: false,
url: 'thePage.jsp',
type: "GET",
dataType: 'json',
data: {'aparameter': aparameter}
}).responseText;
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': request},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
In this way I'm using.
"type": "post" instead of type: 'post'
Maybe it will help. Try it please. For Example;
$.ajax({
url: "yourURL",
type: 'GET',
data: form_data,
success: function (data) {
...
}
});

$.ajax method not calling the controller action method

I am calling javascript function on #Html.ActionLink clicked event. The Javascript function calls the jquery function in which I have written the $.ajax method for calling the json controller method. But it is not calling the controller method.......
Here is my code:
View
#Html.ActionLink("Submit", "AdminEvaluate", "Application", new { onclick = "Show('" + Model.applicationList.ApplicationId + "','statusList')" })|
Here, ApplicationId is coming from database and statusList is Radio Button group name from where I need to find the selected radio button.
Javascipt and jQuery code
function Show(appId, appStatus) {
$.fn.gotof(appId,appStatus);
}
Getting parameter from view and passing to jQuery function
jQuery function
$(document).ready(function () {
$.fn.gotof = function (appId, appStatus) {
var selectedItem = $("input[name='" + appStatus + "']:checked").val();
$.ajax({
url: '/Application/UpdateApplicantStatus',
data: { id: appId , status: selectedItem},
traditional: true,
dataType: "json",
contentType: "application/json",
success: function (data) {
alert(data);
}
});
});
Controller Method
public JsonResult UpdateApplicantStatus(int id, string status){
return Json("Correct", JsonRequestBehavior.AllowGet);
}
I have put break point on controller method but it is not coming at a break point.
Thanks in Advance.
May be this sample help you :) let me know
ajax call with type :
$.ajax({
type: "GET",
url: '#Url.Action("UpdateApplicantStatus", "Application")',
contentType: "application/json; charset=utf-8",
data: { id: appId , status: selectedItem },
dataType: "json",
success: function() { alert('Success'); }
});
controller :
public ActionResult UpdateApplicantStatus(int id, string status){
return Json(// blah blah blah ...
}
This should work else let me know
Your ajax call is wrong.
If your controller method signature is
public JsonResult UpdateApplicantStatus(int id, string appStatus)
Then you MUST have parameter names matching with your parameters of your ajax call.
So, instead of
data: { id: appId , status: selectedItem}
Just write
data: { id: appId , appStatus: selectedItem}
If you have any other problem, just post the error(s) you should have in your browser's console.
Maybe parameter names of controller function and ajax calling function should match.
you can try this
data: { id: appId , appStatus: selectedItem},
Do that way actually 3 mistakes 1 was notify by #Mr Code the type is missing 2nd your parameters not match as your function takes one you send the data in wrong format..
$(document).ready(function () {
$.fn.gotof = function (appId, appStatus) {
var selectedItem = $("input[name='" + appStatus + "']:checked").val();
$.ajax({
url: '/ApplicationController/UpdateApplicantStatus',
data:"{'id':'" + appId + "', 'appStatus': '" + selectedItem+ "'}",//here you format is wrong i correct it
traditional: true,
dataType: "json",
contentType: "application/json",
success: function (data) {
alert(data);
}
});
});
sat on this for hours:
When using ajax - json in a js.script file:
the url is written with its real path e.g. - url: '/contoller/Action',
$.ajax({
url: '/NextPage/GetSpDropDown',
data: {'segInputVal': segInputVal},
cache: false,
type: "GET",
dataType: "json",
success: function (result) {
if (result.Success) {
var resultArray = result.Result;.....
If the script is written in your HTML page then you must use
#(Url.Action(Action,controller))
$.ajax({
url: "#(Url.Action("GetSpDropDown", "NextPage"))",
data: { 'segInputVal': segInputVal },
cache: false,
type: "GET",
dataType: "json",
success: function (result) {
if (result.Success) {
var resultArray = result.Result;....
And dont forget not to include the word controller in your controller name.
I have had SO MUCH help from stackoverflow- hope to pay a little back

jquery and page reload

I have this code in my asp.net webform, I call a webmethod to load data from database:
function Inicializar() {
$("#wait").show();
$.ajax({ type: "POST",
url: "index.aspx/Iniciar",
data: JSON.stringify({}),
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (response) {
$("#wait").hide();
var result = response.d;
cargardatos(result );
}
});
}
I call this function in ready event:
$(document).ready(function () {
Inicializar();
});
the first time it works, the problem is that when I press F5 and reload the page data is not loaded, and if I press back working again.
I do not know if I'm doing something wrong.
Sorry for my English..Xd
Thank you. Greetings!
JavaScript is CaSe SenSitIve. So change your code to:
$(document).ready(function () {
Inicializar();
});
But this way, it doesn't even work on the first time. And do check what is wrong with your output using the Network or Console.
Disable Caching if Needed
$.ajax({ type: "POST",
url : "index.aspx/Iniciar",
cache : false,
datatype : 'json'
})
Turn off caching
function Inicializar() {
$("#wait").show();
$.ajax({ type: "POST",
url : "index.aspx/Iniciar",
cache : false,
datatype : 'json'
}).done(function (response) {
$("#wait").hide();
cargardatos(response.d);
});
}
$(document).ready(function () {
Inicializar();
});

Categories

Resources