Ajax Call inside JavaScripts using Yii Framework - javascript

I am trying to use ajax function inside javascript, but its not calling its goes to failure part,
JS code :
Yii::app()->clientScript->registerScript('my-event-listener',"
$('#dedup_id').change(function(data){
$.ajax({
type: 'POST',
url: '".$this->createUrl('CheckDedupField')."',
data: {crm_base_contact_id:1652},
success: function(msg){
alert('Sucess')
},
error: function(){
alert('failure');
}
});
});
");
My controller code :
public function actionCheckDedupField($id)
{
echo "Inside CheckDedup".var_dump($_POST);
}
Please anyone find out what mistake am doing here.

You have to call ajax url as
url: '".$this->createUrl('checkDedupField')."', // change C to c
In URL, controller function names will start with lower case.
as per the comment. you are calling controller function with wrong name.
Then For missing parameter, change as
data: {id:1652},

Related

Is there a way to save an ajax function/call so it can be reused?

I'm working on a web app using JavaScript and PHP and I'm finding myself re-coding the same ajax calls over and over again. Is there a way to save it as a function, with or without parameters, or even as a variable that can be used later?
Note: I'm still learning JavaScript as I go so I appreciate any tolerance for my ignorance.
For example, instead of this:
$("body").on("click", ".all-forms-link", function() {
$.ajax({
url: "forms.php",
type: "post",
data: {formsPage: 1},
success: function(data) {
stage.html(data)
}
});
});
//called several more times on different actions
Something like this:
function loadForms() {
$.ajax({
url: "forms.php",
type: "post",
data: {formsPage: 1},
success: function(data) {
stage.html(data)
}
});
}
body.on("click", ".all-forms-link", function() {
loadForms(); //or something similar
});
Sure. When you create a named function declaration, for example:
function foo(){
. . .
}
You may refer to that function by name anywhere a function is expected.
So, your code could be even simpler than what you showed with:
function loadForms() {
console.log("AJAX Call Initiated!");
$.ajax({
url: "forms.php",
type: "post",
data: {formsPage: 1},
success: function(data) {
stage.html(data)
}
});
}
// Just refer to your function's name (don't add parenthesis after
// the name though because we don't want to execute it with this line
// we only want to refer to it) where a function is expected.
$(document).on("click", ".all-forms-link", loadForms);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="all-forms-link">Click me</div>

How do I pass javascript variable to Ajax script?

In an html button I have this onclick event:
onclick='javascript:updateStatus(59)'
Then I have this function
function updateStatus(){
$.ajax({
type: 'post',
url: '/update-status.php',
success: function(data){
// callback function
}
});
return false;
}
And this is update-status.php
$sql = "UPDATE requests SET status='Closed' WHERE requestid=$requestid";
$updatestatus = mysqli_query($con, $sql);
if (!$updatestatus) {
die("Database query failed: " . mysqli_error($con));
} else {
return "success!";
}
Ultimately, I want the number from the original onclick event (in this example it's 59, but could be any number) to get passed into the $requestid variable in update-status.php.
What is the best/proper way to accomplish this?
Figured out to use "data" in the function after more googling, sorry.
Since you are using the JQuery AJAX function, just use another parameter in the configuration object, data. You're also missing an argument for the function.
function updateStatus(i){
$.ajax({
type: 'post',
data: 'requestid='+i,
url: '/update-status.php',
success: function(data){
// callback function
}
});
return false;
}
You could also create a map and send the map, like so
...
data: {"requestid" : i},
...
You're server side code should be updated though. You don't want to be using input from the client without first sanitizing it. This opens up the threat for SQL Injection attacks.
for example, what if the value of requestid is
1 or '1'='1' --
or
1; drop table requests
First, take the passed in argument in your javascript function and send it to your PHP script like this:
function updateStatus(id){
$.ajax({
type: 'post',
url: '/update-status.php',
data: {id: id},
success: function(data){
}
});
return false;
}
In your PHP access it through $_POST['id']. However, make sure you escape the value to prevent SQL injection attacks.
$requestid = $_POST['id'];

The name parametor does not exist in the current context in JQUERY method

I have button and when It clicked process event have been called and parameter passed to the event.
Here the code:
<input type="button" value="Accessing Layers" onclick="process('AccessingLayers');" />
function process(actionName) {
$.ajax({
url: '#Url.Action(actionName)',
type: 'POST',
data: {
sessionID: parent.parent.mapFrame.sessionId,
mapName: parent.parent.mapFrame.mapName
},
success: function (result) {
alert('Successfully passed data to controller');
}
});
}
But in this row:
url: '#Url.Action(actionName)'
I get this error:
The name 'actionName' does not exist in the current context
Any idea why I get error above?
And how to fix it?
Remember razor code executes on the server before the your client side code gets executed. So you cannot pass a javascript variable to a razor method like that.
If you still want to build the url using the Url.Action helper method and pass it to your process method, you should call the Url.Action method with correct arguments(the action method,controller name etc..) and generate the url and pass the url( generated by razor) to your javascript method as a string parameter value
<input type="button" value="Accessing Layers"
onclick="process('#Url.Action("AccessingLayers")')" />
and your js code
function process(actionUrl) {
$.ajax({
url: actionUrl,
// existing code
});
}
<input type="button" value="Accessing Layers" id="btnAccessingLayers" />
and in scripts section
$(document).ready(function () {
$('#btnAccessingLayers').on('click', function(){
process('#Url.Action("AccessingLayers")');
}
});
function process(actionUrl) {
$.ajax({
url: actionUrl,
// existing code
});
}
Everything typed between quotes is parsed as plain text, therefore no computation is performed on retrieving value of actionName.
You have to break your url like this:
url: '#Url.Action('+actionName+')'
so that actionName gets resolved as variable.

JS function/ajax only passing one parameter

I have searched multiple threads on here and cannot find the answer.
I have a JS function that is supposed to post 2 parameters via ajax to a php page. Here is the function:
function acceptbet(companyid, userid){
$.ajax({
type: "post",
url: "acceptbet.php",
data: "companyid="+companyid+"&userid="+userid,
success: function(msg){
alert( companyid+userid );
}
});
}
I have also tried it this way:
function acceptbet(companyid, userid){
$.ajax({
type: "post",
url: "acceptbet.php",
data: {companyid:companyid,userid:userid},
success: function(msg){
alert( companyid+userid );
}
});
}
No matter what I do, I can't get it to pass both parameters "userid" and "companyid" --- and the alert will only show the first one. I tried switching the two parameters, and still only the first one is returnd.
I apologize if I'm making a rookie mistake, but I can't figure out how to pass both parameters to acceptbet.php.
Help is greatly appreciated.
EDIT: here is the code for acceptbet.php:
$userid=$_POST['userid'];
$companyid=$_POST['companyid'];
$accepted=1;
$acceptbet = $connection->prepare("UPDATE user_bet set accepted=? where user_id=? and user_company_id=?");
$acceptbet->bind_param("iii",$accepted,$userid,$companyid);
$acceptbet->execute();
My syntax was correct all along. The comments that folks provided were VERY helpful for isolating the problem, which was in my SQL update - was expecting a record to update, but it was not - this was because my where clause was incorrect. For reference, the syntax below should always work for passing multiple parameters in "data:" over ajax:
function acceptbet(companyid, userid){
$.ajax({
type: "post",
url: "acceptbet.php",
data: {companyid:companyid,userid:userid},
success: function(msg){
alert( "success" );
}
});
}

jQuery pass parameters into function call from ajax success

I want to call a function when a jQuery Ajax request is successfull. I want to pass a parameter into a second function that apparently (it doesn't work) doesn't exist inside the jquery anonymous function.
Here is my Ajax function:
function core_get_title(url,id_of_link){
$.ajax({
type: "POST",
url: "url_handler.php",
data: {
url: url,
cmd: "get_title",
},
success: function(data) {
core_title_auto(data,id_of_link);
}
});
}
And when it calls core_title_auto, the id_of_link parameter is empty.
Any ideas?
check and see whats in id_of_link before ajax call by placing an alert function
function core_get_title(url,id_of_link){
alert("id_of_link"+id_of_link);
$.ajax({
/*...... your code */
});
}

Categories