I use Jquery quite a bit and I must be missing something simple here. I am trying to access this in the success block of this ajax call, but I get a Reference Error: that is not defined inside the success block. Here is the code:
$('body').on('click', '.row', function() {
var $row = $(this);
var id = $row.parent().data().scout;
var requirement_id = $row.data().req;
var req = $.ajax({
url: '/scouts/' + id + '/reqs',
data: {requirement_id: requirement_id },
type: 'PUT'
});
var success = function() {
// that not defined
$row;
};
req.done(success);
});
What am I missing here?
Related
I have an AJAX function which gets called every time the enter key is pressed. I have a set of javascript variables that get passed into the data of the AJAX function. Previously, these JS variables were equal to elements in the HTML (the contents of a text area). Now I want these JS variables to be equal to the values of JS variables outside the function.
function stream()
{
var line_Number = $('#lineNumber').val();
var post_code = '#lineText';
var post_id = $('#Streamid').val();
if (post_code != ''){
$.ajax({
url: "post-code.php",
method: "POST",
data: {lineText: post_code, lineNumber: line_Number},
dataType: "text",
success: function(data){
if(data != ''){
$('#Streamid').val(data);
}
$('#autoStream').text("Sending data");
setInterval(function(){
$('#autoStream').text('');
}, 100);
}
});
}
}
Another function then calls the AJAX function
And here are the JS variables which I want to access and pass into the AJAX function
var text;
var lineNumber;
var lineText;
var numOfSpaces;
function update(e) {
text = //code
lineNumber = //code
lineText = //code
I didn't show the code for each variable as I felt it might unneccesarily complicate this.
If I understand your question, you have these options:
1- Use a hidden HTML element:
<input type="hidden" id="someVariable">
where yout want to initialize in your script (JQuery):
$('#someVariable').val(myVar)
and in script in ajax function (JQuery):
var myVar = $('#someVariable').val()
2- You know var scope if it is declared outside a function in javascript, is hole document (window).
3- Pass the arguments to your ajax functio. e.g:
function stream(firstVariable, secondOne, ...)
Hi you can create a json array and pass it as parameter of your ajax function,
this way you avoid to write unnecessary code, example:
let params = {
"line_number": $('#lineNumber').val(),
"post_code" : '#lineText',
"post_id" : $('#Streamid').val()
};
function stream(params)
{
if (params.post_code != ''){
$.ajax({
url: "post-code.php",
method: "POST",
data: data,
dataType: "text",
success: function(data){
if(data != ''){
$('#Streamid').val(data);
}
$('#autoStream').text("Sending data");
setInterval(function(){
$('#autoStream').text('');
}, 100);
}
});
}
}
Hope it helps
I'm trying to call an AJAX query and have had lots of trouble recently.
Im trying to call a api that I have custom made myself, it displays this when the url api/reverse/test - tset (is just uses a php function to reverse the text given in the slug3.
That function works fine, just wanted to give some back on what gets requested.
reverse.php - HTML File
<textarea id="input"></textarea>
<div id="output">
</div>
index.js - All of my jQuery and AJAX
$(document).ready(function(){
var $input = $('#input');
var $output = $('#output');
$input.on('keyup', function(){
var text = $input.val();
var url = 'http://coder.jekoder.com/api/?area=reverse&text='+text;
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) { var output = data; },
error: alert('fail')
}) // End of AJAX
$output.html = output;
});
});
api.php - PHP file being called
<?php
$area = $_GET['area'];
if ($area == 'reverse') {
if (isset($_GET['text']) ) $text = $_GET['text'];
else $text = 'Hello';
echo strrev($text);
}
It's then supposed to take the output variable and display that in a div but that's not the main thing that matters.
error removed - was trying to see if it fixed it
There are several issue I found:
Jquery:
var text = $('#input').val(); // if you are getting value from any inputbox - get value using .val() function
var url = 'http://localhost/test.php?data='+text; // pass data like this ?data='+text
// AJAX START
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
async: true,
success: function(data) { var output = data; alert(output)},
error: function(data) { alert('fail') }
});
In php you ca get data like this:
echo $_GET['data'];
exit;
Try this. Scope of variable output is within the success call and you are using it outside the ajax call.
$(document).ready(function()
{
var $input = $('#input');
var $output = $('#output');
$input.on('keyup', function()
{
var text = $input.val();
var url = 'http://coder.jekoder.com/api/?area=reverse&text='+text;
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) { var output = data; $output.html = output;},
error: alert('fail')
}) // End of AJAX
});
});
I have the following code:
<script type="text/javascript">
$(document).on("click", "#leftconversation", function(){
var self = this;
var cid = $(this).attr('class'); // getting the user id here
var request = $.ajax({
url: "conversation.php",
type: "POST",
data: { cid: cid },
beforeSend: function(){
self.html("Loading please wait...");
}
});
//WHEN SUCCESS
request.success(function( data ) {
$("#right").html(data); // replace the right div with echoed content from php file
});
});
</script>
However, my console keeps giving me the error: “SyntaxError: Function statements must have a name.”
I can't seem to fix the issue and that’s why the AJAX code isn’t running. Where’s this error coming from?
As per what Todd said, i changed the code to following:
<script type="text/javascript">
$(document).on("click", "#leftconversation", function(){
var self = this;
var cid = $(this).attr('class'); //you are getting the user id here
var request = $.ajax({
url: "conversation.php",
type: "POST",
data: { cid: cid },
beforeSend: function(){
self.html("Loading please wait...");
},
success: function(data) {
$("#right").html(data);
},
error: function(request, err){ console.log('An Error Occured' + err); }
});
});
</script>
It fixed the first error, but now its telling me TypeError: undefined is not a function (evaluating 'self.html("Loading please wait...")')
This is fixed, should have used var self = $(this); instead
as per my comment
$(document).on("click", "#leftconversation", function(){
var $self = $(this);
var cid = $(this).attr('class'); // getting the user id here
var request = $.ajax({
url: "conversation.php",
type: "POST",
data: { cid: cid },
beforeSend: function(){
$self.html("Loading please wait...");
}
});
//WHEN SUCCESS
request.success(function( data ) {
$("#right").html(data); // replace the right div with echoed content from php file
});
});
You can fix your issue without having to use a variable. Just set the context: property of the $.ajax call.
var request = $.ajax({
url: "conversation.php",
type: "POST",
data: { cid: this.className }, // Quicker way to get the class.
context: $(this), // The context in the callback will be the jQuery object.
beforeSend: function() {
// v-- This is now a jQuery object.
this.html("Loading please wait...");
}
});
Your code, as you have posted it, is correct. The error must be coming from elsewhere. That said, wherever the error is, here’s what to look for:
As you likely know, functions can be defined like this:
function greet(name) { /* ... */ }
This works in a statement context. Functions can also be used in an expression context:
[1, 2, 3].forEach(function(item) { alert(item); });
In an expression context, we can omit the name, as we did above, or we can include a name:
[1, 2, 3].forEach(function foo(item) { alert(item); });
However, what we cannot do is have a standalone function declaration without a name. This is an error:
function(name) { /* ... */ }
That is what your (now first) problem was.
“undefined is not a function”
Your updated code has a different problem. When you set self = this, this is a DOM element, not a jQuery object. You later try to use self.html, but DOM elements do not have a html property. If you wish to use jQuery methods, you must convert the element into a jQuery object, either at the point of assignment (self = $(this)) or at the point of use $(self).html.
I'm developing a small application in javascript using jquery but i've a small problem.
i've this function
function cercahq(urlvalue) {
$.ajax({
type: "POST",
url: "data.php",
data: "do=urlget&url=" + urlvalue,
dataType: "html",
success: function(msg) {
var data = eval('(' + msg + ')');
$("#searchbar").css({'background-color': '#C33'});
// creates element
var insertform = document.createElement('form');
insertform.id = "insertform";
var insertbutton = document.createElement('button');
var insertbuttonlabel = document.createTextNode('Insert');
insertbutton.appendChild(insertbuttonlabel);
insertform.appendChild(insertbutton);
$("#searchbar").append(insertform);
$(insertbutton).click(function(event, data) {
event.preventDefault();
alert(data.title);
});
stampa(msg)
},
error: function()
{
alert("Error");
}
});
}
This function gets json data from a php script and pass it to a function (stampa) that evals it and print it in the page, but i need to create a button outside the stampa function that tells me a value from the json...
So inside the success event i've insered another eval to grab the ajax msg and create the variable data that should be passed to a button element that i've created inside a form called insertform.
The point is: how to pass the "data" variable to the click function from an element created inside an ajax request success function?
The 'data' variable should be accesible inside click function through closure, no need to pass it there. By passing it as parameter you override it as closure with 'undefined' value. So just remove it from parameters:
$(insertbutton).click(function(event) {
event.preventDefault();
alert(data.title);
});
I tried to create a jquery plugIn that load multiple feed rss (they are flexible can be 1 or 2 or 3 ect...), for create an html that show the news feed loaded. My target is having the possibility to load multiple rss feed (xml) and display them by html. When I tried seem that the callback is overwrite,I received 2 results but equal.
Example:
(function($){
$.fn.getFeed = function(Obj){
var
arrOpt = Obj.arrayOptions,
arrOptLng = arrOpt.length;
for(var i = 0; i < arrOptLng; i++){
var
index = i,
Opt = arrOpt[i],
feedUrl = Opt.feed,
sucFnc = Opt.callback,
$cnt = this;
console.log(index);
// here:
// 0
// 1
$.ajax({
url:feedUrl,
dataType: "jsonp",
success:function(data){
sucFnc(data,$cnt,Opt,index);
},
error:function(){
$cnt.html('error');
}
});
}
}
})(jQuery);
function feedManipulation(){
console.log(index)
// here:
// 1
// 1
}
/* DOM LOADED */
$(function(){
$('.news').getFeed({ // Activation getFeed
arrayOptions:[{
feed:'http://feed',
callback:feedManipulation,
imgDefault:'http://img',
nArtc:1
},{
feed:'http://feed',
callback:feedManipulation,
imgDefault:'http://img',
nArtc:1
}]
});
});
Ciao, I wrote this question and I created the solution so I would explain.
In this code I removed the cyclo for and I create a function that contain the ajax call.
The first time that I trigger the ajax function I pass an argument to the ajax function with inside an object that I used to set the plugIn (lock on the bottom) whereas my ajax function is itself calls, before sending the same object to the ajax function I change some information like "Opt.index" creating in this way a ajax cyclo. Is it really usefull ;) use it.
(function($){
$.fn.getFeed = function(Obj){
// Options object
Opt = new Object();
Opt.index = 0;
Opt.$cnt = this;
Opt.arrOpts = Obj.arrayOptions;
Opt.arrOptLng = Opt.arrOpts.length;
Opt.arrOpt = Opt.arrOpts[Opt.index];
Opt.feedUrl = Opt.arrOpts[Opt.index].feedUrl;
// ajax call
cycloAjax(Opt);
}
/* ajax cyclo */
function cycloAjax(Obj){
$.ajax({
url: Obj.feedUrl,
dataType: "jsonp",
success:function(data){
feedManipulation(data,Obj.$cnt,Obj);
if(Obj.index < Obj.arrOptLng - 1){
Obj.index++;
Obj.arrOpt = Obj.arrOpts[Obj.index];
Obj.feedUrl = Obj.arrOpts[Obj.index].feedUrl;
cycloAjax(Obj);
}
else{
completeLoadFeeds(Obj.$cnt,Obj);
}
},
error:function(){
Obj.$cnt.html('<p>error</p>');
}
});
}
.
.
.
})(jQuery);
/* DOM LOADED */
$(function(){
$('.news').getFeed({ // Activation getFeed
arrayOptions:[{
feed:'http://feed',
callback:feedManipulation,
imgDefault:'http://img',
nArtc:1
},{
feed:'http://feed',
callback:feedManipulation,
imgDefault:'http://img',
nArtc:1
}]
});
});