Call to $.post() Jquery not passing parameters successfully - javascript

/**
* Created by quantumveil on 2/10/15.
*/
$(document).ready(function(){
$('a').on('click',function(){
//$href=$(this).attr('href');
//console.log($href);
var $convoid=$(this).attr('id');
console.log($convoid);
//$('#convoarea').load($href);
$.get('inbox.php',{convoid:$convoid},function(data){$('#convoarea').html(data);//the callback sets whati t had to
//now add the on click handler to send button
$('#send').on('click',function(){
var $msgbody=$('#sendbody').val();
console.log($msgbody);
///now what i have to do is sent this $msgbody to the inbox.php thru get k
$.post('inbox.php',{sendbody:$msgbody,convoid:$convoid},function(data){
$('#sendbody').before(data);
console.log('here'+$msgbody);
});//the callback function will append it to other messages :3
return false;
});
}//callback ends hre
);
return false;
});
//for send button
});
Hi. I'm trying to code a social networking site and I want the inbox to be responsive and dynamic. I've recently started learning Jquery for the purpose being. I've googled this before and found no help and so it brings me here on this community. The above Javascript/Jquery code is supposed to pass some post parameters when the SEND button is clicked. Another file, inbox.php, is to receive those and work appropriately. Now here's what bugs me. The callback function to $.post() is executed, so I'm assuming the parameters are being passed to inbox.php. But when I try accessing them in inbox.php using following line
if($msgbody=get_post('sendbody')&&$convoid=get_post('convoid'))
I only receive a value of 1 and not the message's actual body. Here's how the function get_post is defined
function get_post($var1){
if(isset($_POST[$var1])){$var=$_POST[$var1];
return filter($var);}
else return 0;
}
I've tried accessing them directly through $_POST['sendbody'] but an error of undefined index is being generated. Any help will be highly appreciated. (PS the other call to .get() in the beginning of this js file is passing the parameters so there's nothing wrong with file paths)
EDIT: It's fixed but I want an explanation. All I did was in the inbox.php changed the first line which was
if($msgbody=get_post('sendbody')
to
if(isset($_POST['sendbody'])$msgbody=$_POST['sendbody']
Now all I can wonder is if it has something to do with filter() function in the definition of my get_post() function. Anybody?

Related

Can doPost() run itself?

function doPost(e) {
var msg= JSON.parse(e.postData.contents);
var shitText = msg.messaging[0].message.text;
var senderId = msg.messaging[0].sender_id;
Logger.log(e)
.
.
.
(do something)
}
I use doPost() smoothly.
But when I create the (e) objects to pass to it and try to run itself,
the syntax errors tells that
"It cannot load the contents properties of undefined".
Like picture show below.
Can't the doPost() run itself?
Or just to need post the data to it to do functions?
Thank you.
doPost() can run by itself without initializing the e variable in the parameter. I think the problem comes from the contents property in the JSON string, so you should look at it. It has a 's'.
Also you need to post the e variable here (which should be a nested JSON string), or we don't know what is wrong with the codes.
You can try and run this code, this will work. The example below showcases that you can initialize e variable inside a parameter to ensure that the function still work even when you call doPost() without any parameter.
function abc(e = '{\"sample\": {\"someitem\": {\"thesearecool\": [{\"neat\": \"wow\"},{\"neat\": \"tubular\"}]}}}'){
var msg= JSON.parse(e);
console.log(msg.sample.someitem.thesearecool[0].neat)
}
abc();
Edit: if you are using JS, don't use e as varriable, you will mistake it sometimes with (e) as event.
e in the Apps Script function doPost(e) stands for an event object which will only be initialized when the event takes place.
e.postData.contents are the contents of data obtained from a post request.
if you run the function manually, without a trigger event taking place - there are no post data contents linked to an event and this gives you the error.
If you just want to test your function manually, you need to use doPost() without the e and assign a value to your post data contents manually.

DotNetBrowser calling a JS function and returning a value from C#

I see the option where you can initiate the function call in .NET and return a value, but I don't see an option where you are able to initiate a function call in javascript calling a .NET function and then return a value to javascript, similar to what would happen if I was using ASP.NET or hitting a Web API.
So basically here is what I am doing. I have a modal that pops up when the user clicks to save game. They enter the name of the Save Game file, click OK and it calls a .NET function to check the DB to see if it's a duplicate save game file or not. If it is, it should return "Error! Duplicate file name! Please choose a unique file name." If it is unique it saves the information to a DB and returns a "Successfully saved game!" message, waits 2 seconds and then redirects to the main dashboard page.
I have everything working fine up until the point .NET is supposed to return the value. Currently the modal window just sits there and nothing returns to JS.
I have it set up like I normally would through calling the .Net function and using .then(function (response) to get the response value, but it is coming back as undefined.
I'm sure there has to be a way to do this, I just don't see how in the documentation as that only shows how to do it when initiating the function call from .NET...
EDIT: OMG...I just realized this was such a dumb question...I'm already doing that returning lookups from the database...the answer was to set it equal to a variable instead of trying to chain the function onto the end.
THIS:
var value = window.CRUD.Save(fileName, model);
if(value === "Duplicate!") ....
INSTEAD OF:
window.CRUD.Save(fileName, model).then(function(response) {
});
The article by the following link explains how to call .NET from JavaScript:
https://dotnetbrowser.support.teamdev.com/support/solutions/articles/9000109869-calling-net-from-javascript
Thank you for adding your answer to the question as an update.

Call a PHP Link with Onclick

This isn't a duplicate question by any means and I have tried a lot finding solutions.So, please read it before down voting.
Background:
This application is like a note-taking web app where you can post/delete your notes.
Each item in the list has an id which is needed when making a delete call.
In my application, I have to delete individual items from a list which is generated by looping over a JSON response (by a REST API) using PHP.The JSON response can be obtained after successful login.
Question:
To implement delete functionality I have to send id of each of the items as a parameter to the rest api delete call.
So, for this I have to generate dynamic links of the form :
http://localhost/myfolder/api/notes/:id
which should be passed to the delete.php function (Which I have implemented in CURL).
I searched for possible ways :
Using a PHP function: It seems to be complex, however if there is some way to invoke a PHP function (the delete code using CURL) on click of a link (Which I found not possible as per some answers ?) this could be a great solution.
Using Javascript: I have to call a function upon click of link that sets a variable $_SESSION["id"] to the current item["id"] and then goes to delete.php where I use the $_SESSION variable to first set up the link and then use the CURL code.
I tried basic implementation using the second approach but I have hit a roadblock in this issue. It would be great if you could tell with a bit of code which approach should be followed or any other way to do this ?
This functionality is present in twitter/facebook and almost every such service, how do they implement this, the basic approach should be the same, right: Generate dynamic links and pass them to a php script on click ?
Basic Javasript approach :
<script>
<script>
var el = document.getElementById('del1');
el.onclick = del1;
function del() {
// I have to set $_SESSION here
return false;
}
</script>
echo "<a href=\"delete.php\" title=\"Delete\" id=\"del1\">";
//Here, I have to pass the item["id"] to the javascript function.
I had tried some other ways but I have modified the code a lot so, I can't post them. Thanks for your help.
Regarding #2, you can't access the user's session from Javascript, so that will not work.
My preferred way (if using jquery) is to put the id in a data attribute of the delete button (or the block as a whole). Then in the delete onclick function do something like
<div class="block" data-itemid="<?=$item['id']?>">
...
<div class="delete_button">Delete</div>
</div>
...
$('.delete_button').on('click',function(event) {
block = $(event).target.parent('.block');
itemid = block.data('itemid');
$.post('delete.php',[itemid: itemid]...);
});

Execute javascript inside the target of an Ajax Call Drag and Drop Shopping Cart without Server language

Well i wanna create an Ajax Drag and Drop Shopping cart using only javascript and ajax. Currently i'm using the example in this page as a stepping stone. Right now it's only with local jquery and it works fine but i want to make the cart work with ajax calls. Note that i do not want to use a server side language( like php, rubby, asp etc), only html and javascript.
My initial thought was that at the $(".basket").droppable i should add an ajax call to another html page containing the "server logic" in javascript, execute in that file all the necessary steps( like reading the get variables (product name, product id and quantity), set a cookie and then return an ok response back. When the server got the "ok" response it should "reload" the cart div with the updated info stored inside the cookie.
If this was with php i would know how to do it. The problem is that as far as i know, you can execute javascript once it reaches the DOM, but how can you execute that js from inside the page that isbeing called upon ? ( thanks to Amadan for the correction)
I've thought about loading the script using $.getScript( "ajax/test.js", function( data, textStatus, jqxhr ).. but the problem with that is that the url GET variables i want to pass to the "server script" do not exist in that page.
I havent implemented all the functionality yet as i am stuck in how to first achieve javascript execution inside an ajax target page.
Below is a very basic form of my logic so far
// read GET variables
var product = getQueryVariable("product");
var id = getQueryVariable("id");
var quantity= getQueryVariable("quantity");
//To DO
//--- here eill go all the logic regarding cookie handling
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
Any help regarding this matter will be appreciated.
Note: Logic in simple words:
1)have an html page with products+cart
2)Have an "addtocart.html" with the "Cart Server Logic"( being the target of the ajax call when an item is dropped into the product.)
If you have some other idea on this, please enlighten me :)
thanks in advance
Foot Note-1:
if i try loading the scipt using
$("#response").load("ajax/addtocart.html?"+ $.param({
product: product,
id: id,
quantity:quantity
})
);
i get the alert about not being able to find the url parameters( something that i thing is normal as because the content is being loaded into the initial page, from which the request is started, there are no get parameters in the url in the first place)
The problem is that as far as i know, you cannot execute javascript contained in the target of an ajax call, as that page never reaches the browser interpreter.
This is either incorrect or misleading. The browser will execute any JavaScript that enters DOM. Thus, you can use $.load to load content and execute code at the same time. Alternately, you can use hacked JSONP to both execute code and also provide content as a JSON document.
EDIT: Yes, you can't get to the AJAX parameters from JavaScript. Why do you want to? Do you have a good reason for it, or is it an XY problem?
The way I'd do it is this:
$('#response').load(url, data, function() {
onAddedToCart(product, id, quantity);
});
and wrap your JS code in your HTML into the onAddedToCart function.
Depending on what exactly you're doing, it could be simplified even further, but this should be enough to cover your use case.

Basic questions about javascript

Please take a peek at the following code, which is in _form.html.erb:
<script>
function typeCatch(){
$.post("<%= update_readers_link_essay_path(#essay) %>");
$(this).off("keypress", typeCatch);//remove handler
}
$(function(){
("form#new_revision").on("keypress", typeCatch);
});
</script>
When the user starts typing in a form, the ajax request should be fired and update the readers list. However, the post request is not fired when I start typing in the form and I am trying to debug this problem.
Since I am not that familiar with javacsript yet, I would appreciate if you helped me clarify a few things.
a. For the second part, can I just do
$("form#new_revision").on("keypress", typeCatch);
without wrapping it with $(function() {} ?
b. Is there anything that I'm doing wrong? Since ajax call isn't fired, I must have made a mistake in the second part?
Additional Question
my_personal_chat.js (in app/assets/javascripts pipeline)
$(function() {
var pusher = new Pusher('app_key');
var channel = pusher.subscribe('presence-my-chat');
channel.bind('pusher:subscription_succeeded', function(members) {
$('#online_users').empty();
members.each(function(member){
addMember(member);
});
... other functions ...
});
This is how I implemented my chat feature, using Pusher. Since the channel is private, everytime I call var channel, an ajax call to POST /pusher/auth is invoked.
I found that every time I navigate to a different page, even when it's not where the chat feature is, POST /pusher/auth is called. Basically, every time my_personal_chat.js is loaded, the ajax call will be unnecessarily invoked.
Question: How do I prevent this from happening? my_personal_chat.js should only be loaded when I go to myapp.com/chat. Should I just pull out everything from the javascript file and put it inside chat.html.erb? Is that the conventional way of doing it?
to answer my own question: I moved the code from my_personal_chat.js to chat.js.coffee and deleted my_personal_chat.js. Now the javascript only gets loaded when users go to the chat page.
a. There are alternatives, but wrapping the code in $(function() {}) is one of the best ways to ensure that the code isn't executed until all the elements are loaded into the DOM. It's a jQuery feature.
b. ("form#new_revision").on("keypress", typeCatch); should be $("form#new_revision").on("keypress", typeCatch);. You're missing the $ at the beginning.

Categories

Resources