Set the function itself to the url in AJAX? - javascript

I am new to AJAX. Recently, I read a block of code that set url to the function itself. In this case, it is get Path. Normally, we will set url to other pages to get data or something. I do not know what it means to set url to the calling function itself. Could you help answer my question?
<script type="text/javascript">
function getPath()
{
var startLat = $('#startLat').val();
var startLng = $('#startLng').val();
var desLat = $('#desLat').val();
var desLng = $('#desLng').val();
var departure = $('#departure').val();
$.ajax({
type: "POST",
url: "getPath",
dataType: "json",
data: { "startLat": startLat, "startLng": startLng, "desLat": desLat, "desLng": desLng, "departure": departure},
success: function (response) {
if(response.success) {
$('#result').val(response.data);
console.log('Reponse.success is true');
}
else {
console.log('Response.success is false');
}
},
error: function(e) {
}
});
}
</script>

function getPath() <-- function
url: "getPath", <-- string
They are not related. Only thing in common is the developer had the same name. The page will post to some location called getPath on the server.

It doesn't mean anything other than the fact that the url the POST request is being sent to happens to be "getPath". The function is probably named according to the route name on the server side, but renaming that function (and updating every place it is called accordingly) would have no effect, and you would have to leave the url: "getPath" as is. Changing that part would likely break something.
That getPath would be a relative url, so the request goes to something like: http://example.com/path/to/parent/of/current/page/getPath

suppose your HTML input URL
<input type="url" id="web_url" value=""></input>
Then you can get your URL
<script type="text/javascript">
function getPath()
{
var startLat = $('#startLat').val();
var startLng = $('#startLng').val();
var desLat = $('#desLat').val();
var desLng = $('#desLng').val();
var departure = $('#departure').val();
var url = $('#web_url').val(); // getting input URL by User
$.ajax({
type: "POST",
url:url ,
dataType: "json",
data: { "startLat": startLat, "startLng": startLng, "desLat": desLat, "desLng": desLng, "departure": departure},
success: function (response) {
if(response.success) {
$('#result').val(response.data);
console.log('Reponse.success is true');
}
else {
console.log('Response.success is false');
}
},
error: function(e) {
}
});
}
</script>

Related

Insert user in PeopleOrGroup Field using javascript SharePoint 2013

I have only email address of user.
How to insert user in PeopleOrGroup Field using javascript SharePoint 2013.
If I directly pass email address to filed like
var MyUserEmail = 'mymanger's email adress' \\email id is proper and checked
oListItem.set_item('MyFieldName',MyUserEmail);
Throwing error as invalid data.
The following code for your reference:
<script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var lists = web.get_lists();
var list = lists.getByTitle("CL");
var item = list.getItemById(1);
var assignedToVal = new SP.FieldUserValue();
var MyUserEmail = "app#xx.com";
var userId=GetUserId(MyUserEmail);
assignedToVal.set_lookupId(userId); //specify User Id
item.set_item("MyFieldName",assignedToVal);
item.update();
ctx.executeQueryAsync(
function() {
console.log('Updated');
},
function(sender,args) {
console.log('An error occurred:' + args.get_message());
}
);
});
function GetUserId(emailAddress){
var userId="";
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/siteusers?$select=Id&$filter=Email eq '"+emailAddress+"'";
//execute AJAX request
$.ajax({
url: requestUri,
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
async: false,
success: function (data) {
if(data.d.results.length>0){
userId=data.d.results[0].Id;
}
},
error: function () {
//alert("Failed to get details");
}
});
return userId;
}
</script>
My code which is working. Do the Rest call. you can keep Ajax call as Asynchronous false to get the item before Execution Asynchronous () for item save

Unexpected characters in image url in ajax response Javascript

In My Codeigniter web application I'm using an ajax function to get some data from the database inorder to show it in the view.The data from database contains an image url and other fields.
My problem is that when I get the data in ajax success function, the image url looks like this:
<button id='product-1301' type='button' value=1301 class='blue' ><i><img src='assets\/uploads\/thumbs\/default.png'></button>
Since the url contains these characters \ my view is not rendering properly. I tried using stripslash function to remove this. But didn't work. I didn't know where am going wrong.
my ajax function
$.ajax({
type: "get",
url: "index.php?module=pos&view=ajaxproducts1",
data: {category_id: cat_id, per_page: p_page},
dataType: "html",
success: function(data) {
var x= data;
alert(x);
if(data!=1)
{
$('#proajax').empty();
var newPrs = $('<div></div>');
newPrs.html(data);
newPrs.appendTo("#proajax");
//$('#gmail_loading').hide();
}
else
{
bootbox.alert('Product is Not Available in this Category!');
$('#gmail_loading').hide();
}
}
});
Controller
function ajaxproducts1()
{
$mn;$data1;
$img="assets/uploads/thumbs/default.png"; //this is my image path, when this comes in ajax success,\ character adds
$img=str_replace('\"', '', $img);
if($this->input->get('category_id')) { $category_id = $this->input->get('category_id'); }
if($this->input->get('per_page')) { $per_page = $this->input->get('per_page'); }
if($item = $this->pos_model->getProductsByCategory($category_id,$per_page))
{
foreach ($item as $i)
{
$button="<button id='product-".$i->id."' type='button' value=".$i->id." class='blue' ><i><img src='".$img."'><span><span>".$i->name;
$mn=$mn.$button;
}
$data1=$mn;
}
else
{
$data1=1;
}
echo json_encode($data1);
}
Can anyone help me with this ?
Try this:
// use an array to gather up all the values
// call encodeURIComponent() on the variables before adding them
// join them all together and pass them as "data"
var tempVars=['module=pos&view=ajaxproducts1'];
tempVars.push('category_id='+encodeURIComponent( cat_id ));
tempVars.push('userInfo='+encodeURIComponent( p_page ));
var sendVars=tempVars.join('&');
$.ajax({
type: "get",
url: "index.php",
data: sendVars,
dataType: "text",
success: function(data) {
var x = data;
alert(x);
if (data != 1) {
$('#proajax').empty();
var newPrs = $('<div></div>');
newPrs.html(data);
newPrs.appendTo("#proajax");
//$('#gmail_loading').hide();
} else {
bootbox.alert('Product is Not Available in this Category!');
$('#gmail_loading').hide();
}
}
});
My issue was solved by using jQuery.parseJSON function.

jQuery GET not succeeding

I'm trying to read from a list of threads as described in a file 'forum.xml'. I have come to realise that my GET request is not succeeding. Here is the XML file (which is not modifiable)
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE forum SYSTEM "forum.dtd">
<forum>
<thread>
<title>Tea Party</title>
<posts>teaParty.xml</posts>
</thread>
<thread>
<title>COMP212 Exam</title>
<posts>crypto.xml</posts>
</thread>
</forum>
and here is my js. I have tested that the element at target is being selected.
//threadReader.js
//Gets and display list of threads
var Threads = (function() {
var pub = {};
var target = $( ".thread");
var xmlSource = 'forum.xml';
function showThreads() {
console.log("showThreads called");
console.log(xmlSource);
$({
type: "GET",
url: xmlSource,
cache: false,
success: function(data) {
console.log(data);
parseThreads(data, target);
}
});
}
function parseThreads(data, target) {
console.log("parseThreads called");
console.log(target);
console.log(data);
target.append("<ul>");
$(data).find("title").each(function () {
$(target).append("<li>");
$(target).append($(this).text());
$(target).append("</li>");
});
}
pub.setup = function() {
showThreads();
}
return pub;
}());
$(document).ready(Threads.setup);
any insight is always appreciated
Change this
function showThreads() {
console.log("showThreads called");
console.log(xmlSource);
$({
to
function showThreads() {
console.log("showThreads called");
console.log(xmlSource);
$.ajax({
Also be aware that your call to $(".thread") may not match any elements at the time you're calling it. Best to do that in your document ready handler.
This may help in future. To get the correct Jquery Ajax syntax
http://api.jquery.com/jQuery.ajax/
In your case, I guess this should fire the call.
function showThreads() {
console.log("showThreads called");
console.log(xmlSource);
$.ajax({
type: "GET",
url: xmlSource,
cache: false,
success: function(data) {
console.log(data);
parseThreads(data, target);
}
});
}

I don't understand AJAX callbacks

I have a javascript function which executes on the change of a dropdown:
<script type="text/javascript">
$(function()
{
// Executes when the status dropdown changes value
$('select[name="status_dropdown"]').change(function(event)
{
var $this = $(event.target);
var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table
var result = null;
var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data)
{
result = data;
alert(result);
}
});
});
})
</script>
I am trying to get the alert call to show the return value of the following php code (which is true):
<?php
.
.
.
return true;
?>
The alert doesn't pop up. Anyone know why ???
I tried your code with another URL and it's working well.
There are three cases:
scriptUrl is not calculated properly and doesn't point to your PHP script
your server is down
you are accessing an URL not served under the same domain as the one of your script (same-origin policy)
You can see detail of your error if you add an error handler to ajax parameters :
error : function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
Return only returns a value within the php script - to output it to ajax you need to actually output the result to the page, in this case something like echo "true"; or print("true");
Try this
$(document).ready(function(){
$('select[name="status_dropdown"]').change(function(event)
{
var $this = $(event.target);
var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table
var result = null;
var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data)
{
result = data;
alert(result);
}
});
});
});

Ajax success function firing before java class responds

I am creating a login function with ajax and am having an issue where the success function (SuccessLogin) fires before getting an ajax response. I am running the code as google web app from eclipse and I can see when debugging the java class file, that the javascript is throwing an alert for the success response from the class being false before the debugger catches the break point in the class file. I have only been writing code for a couple months now so I am sure its a stupid little error on my part.
$(document).ready(function() {
sessionChecker()
// sign in
$('#signInForm').click(function () {
$().button('loading')
var email = $('#user_username').val();
sessionStorage.email = $('#user_username').val();
var password= $('#user_password').val();
var SignInRequest = {
type: "UserLoginRequest",
email: email,
password: password
}
var data= JSON.stringify(SignInRequest);
//disabled all the text fields
$('.text').attr('disabled','true');
//start the ajax
$.ajax({
url: "/resources/user/login",
type: "POST",
data: data,
cache: false,
success: successLogin(data)
});
});
//if submit button is clicked
$('#Register').click(function () {
$().button('loading')
var email = $('#email').val();
if ($('#InputPassword').val()== $('#ConfirmPassword').val()) {
var password= $('input[id=InputPassword]').val();
} else {alert("Passwords do not match");
return ;}
var UserRegistrationRequest = {
type: "UserRegistrationRequest",
email: email,
password: password
}
var data= JSON.stringify(UserRegistrationRequest);
//disabled all the text fields
$('.text').attr('disabled','true');
//start the ajax
$.ajax({
url: "/resources/user/register",
type: "POST",
data: data,
cache: false,
success: function (data) {
if (data.success==true) {
//hide the form
$('form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
} else alert('data.errorReason');
}
});
return false;
});
});
function successLogin (data){
if (data.success) {
sessionStorage.userID= data.userID
var userID = data.userID
sessionChecker(userID);
} else alert(data.errorReason);
}
//session check
function sessionChecker(uid) {
if (sessionStorage.userID!= null){
var userID = sessionStorage.userID
};
if (userID != null){
$('#user').append(userID)
$('#fat-menu_1').fadeOut('slow')
$('#fat-menu_2').append(sessionStorage.email).fadeIn('slow') };
}
success: successLogin(data)
There's a difference between a function call and a function definition:
A function definion uses the function keyword and contains a function body {...}
A function call appends parentheses (argument list) to the function name and actually calls the function to return a value
If you assign a function call to the property, it will return a value and that will be what is stored. To avoid this, if your function does not take any parameters you can use the function name, or if your function does take a parameter, embed your function call in another function's definition:
No parameter: success: successLogin
Has parameter: success: function() { successLogin(data); }
You need to wrap your success in an anonymous function in order for it to execute within the scope of the AJAX call instead of being executed inline (immediately):
success: function() { successLogin(data) }

Categories

Resources