I'm a PHP developer and know a little bit of javascript. I am using ajax to submit a request to the server. I've read that it's good to put all your code inside the javascript anonymous function like: (function($){ //code here }(jQuery)). So, I've put my ajax code inside the anonymous function as well. It's working absolutely fine, but, I'm curious if it's okay to do so or not?
P.s: By all your code, I mean the whole .js file of the app containing user defined scripts.
Here's an example of my question.
HTML:
<form action="https://www.server-url.com/" method="POST" id="form">
<input type="text" name="user-name">
<button type="submit">submit</button>
</form>
JavaScript:
(function($){
var main = {
serverRequest: ()=>{
$('#form').submit((e)=>{
e.preventDefault();
var username= $('input[name=user_name]').val();
$.ajax({
url: $('#form').attr('action'),
type: 'POST',
data: {
user_name: username
},
success: (res)=>{
// success code here...
},
error: (err)=>{
// error code here...
}
});
});
}
};
$(document).ready(()=>{
main.serverRequest();
});
}(jQuery));
Any help would be appreciated, thanks in advance. :)
This is indeed a good practice, as it prevents your code getting in conflict with other libraries that might use the $-sign in their own context.
if you are interested, you could take a look here, where your question has already been answered.
Related
I'm doing a simple project to practice node js along with Jquery Ajax.
So I have an ajax post request that sends some data to nodejs server and wait for a response. In the server-side, I have a code that reads the data and do something with it. This works fine. But when I try to send the response back to ajax, the page changes and it shows the response in plain text. What I want is to do something with the response in ajax side.
Sorry if I'm not clear, but hope you understand when reading the code.
Jquery Ajax code:
$("submitBtn").on("click", e=>{
e.preventDefault();
$.ajax({
url: "/getCity",
type: "POST",
data: `city=${cityName}&country=${countryName}`,
success: function(data){
console.log(data);
}
});
});
server-side code:
app.post("/getCity", (req, res)=>{
//a promise
.then(cityID=>{
res.status(200).send(cityID.toString());
});
});
html code:
<form method="post" action="/getCity">
<input/>
<input/>
<button id="submitBtn" type="submit">Search Weather</button>
</form>
I included html code because I don't know if putting method="post" action="/getCity" is necessary even though making the ajax post request.
I hope you help me with this and if possible the html thing.
Thank you in advance.
NOTE: This question is a recreation of another question I asked before. I did it because it was marked as a duplicate, but after that it was answered by another user, only in a comment, who asked to do so in order to benefit others from it in the future.
Please use it as following in your html file. Should solve your problem
<body>
<form method="post" id="cityform">
<button id="submitBtn" type="submit">Search Weather</button>
</form>
</body>
<script>
$("#cityform").submit(function(e) {
e.preventDefault();
$.ajax({
url: "https://localhost:8443/getCity",
type: "POST",
data: {
'city': 'pune',
'country': 'India',
},
success: function(data){
console.log(data);
}
});
});
</script>
Post request should look like this, I'm calling some function as findCity, you don't have to use it.
app.post("/getCity", (req, res) => {
var cityname= req.body.city;
var country= req.body.country;
city.findCity(cityname, country).then((cityID) => {
res.status(200).send({ cityID: '123' });
}).catch((e) => {
res.status(400).send(e);
});
});
In the duplicate, they discuss how it's possible for the DOM selector to fire before the element is on the page. That's not quite your issue. You're missing the # part of your selector (since you're selecting by ID). Change your first line of your AJAX to $("#submitBtn").on("click", e=>{ and it will work. Because this was erroneously marked as a duplicate, I wasn't able to post this as an answer. If this solution works, please create your question again, provide my comment as an answer, and accept it, so that others will be able to benefit from it in the future. #Welkie
Quick question. I know this is a problem solved many times on stackoverflow, but if I try to make it work it no methodes work out for me. Am I doing it so bad? Here is my code:
$('.submit').click(function(){
$.ajax({
type: 'POST',
url: 'http://localhost/clicky%20game/index.php',
data:
{
userScore:score
},
succes: function(){
alert('succes');
}
});
});
This piece of code is inside a script.js (linked to click.php) and it sould send the data to index.php. But it doesn't, I check this with the code (inside index.php):
if (isset($_POST['userScore'])){
echo $_POST['userScore'];
}
It just keeps showing nothing, hope someone can help me with this, thanks in advance!
That's not how Ajax works. $_POST is a PHP method that stores global variables from page to page. If you pass a javascript variable to a page then PHP will never see it. If this was possible to do then everyone would be hacked in a matter of seconds. You should look into REST APIs. That's what Ajax requests are for. HTTP POST and PHP POST are two very different things, but they do the exact same thing.
What you want to do is store a POST variable with PHP with a Form using the POST method. Then you can send that to index.php.
<form action="index.php" method="POST">
<inputs></inputs>
</form>
Since you are using a regular button to click, you will have to prevent the default submission of the form:
$('.submit').click(function(e){ // added the `e` for the `event`
e.preventDefault(); // this will prevent the default action of the submission of the form.
$.ajax({
type: 'POST',
url: 'http://localhost/clicky%20game/index.php',
data:
{
userScore:score
},
succes: function(){
alert('succes');
}
});
});
I wanted to submit a form to the server, in order to run some server-side code. By using a form, it is a lot easier to harvest the variables in the form, instead of harvesting a bunch of fields by hand with Javascript.
But, I don't want the page to refresh or redirect. I would like to be able to return some Javascript that lets the page signal the outcome of the server-side code.
In short, an xmlHttp request that includes all the fields from the form.
Is that possible?
Yes, you can use XMLHttpRequest object to send the requests to the server. Feel free to learn it from MDN, https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
Secondly, to stop the page refresh of redirect, you can use this code
event.preventDefault();
..this will stop the page from loading etc but still it will send the request to the page you're trying to access.
Example code
<form method="post">
<input type="text" name="someName" />
<input type="submit" value="Submit" onclick="sendData()" />
</form>
..in the JavaScript write
function sendData() {
// at the top of the code
event.preventDefault();
// execute the XMLHttpRequest here
}
My Recommendation
I would recommend that you use jQuery for this. jQuery is same as JavaScript as it is a library built right on JavaScript, it will minimize the long code you're going to write.
Learn it here, jquery.com
In jQuery it is as easy as
function sendData() {
$.ajax({
url: 'page.html',
// as barmar has suggested in comments
data: $("#formID").serialize(),
success: function (data) {
alert('Message from server' + data);
}
});
}
The above code would send the request, and you will get the results in the success function's data object.
So, I have this problem. I am using a plugin named jRating, it is esentially a rating system in jquery. My problem is, that onClick, the ajax request fires twice.
After searching a lot, I tried those things:
I checked and double checked that the $(document).ready(function(){} and the jQuery shortcut $(function() {}); is not twice in the page.
I also checked that the id of the call is unique.
So, here is my code:
jQuery:
$("#rating").jRating({
step:true,
length : 5,
canRateAgain : true,
nbRates : 3,
onClick : function(element,rate) {
var data = (rate, 1);
$.ajax({
url: 'application/index/rate',
type: 'POST',
dataType: 'x-www-form-urlencoded',
async:false,
contentType: 'application/x-www-form-urlencoded',
data: rate,
success: function () {
console.log('SUBMIT WORKS');
},
error: function () {
console.log('There is error while submit');
}
});
}
});
pHTML:
<div id="rating" data-average="<?=$average //note that this is working everytime!?>" data-id="1"></div>
Thanks for any inputs!
EDIT: JsFiddle: http://jsfiddle.net/Je79U/ ;
To recreate the problem, click run, then go to console/network, clear all contents, then click anywhere on the yellow/orange bar, to rate, and see what happens. Thanks again for your time!
with reference of http://demos.myjqueryplugins.com/jrating/ , already jRating will work as ajax. So, that it takes ajax running twice
Please check their demo website clearly.
In that once you rate it will update the records to http://demos.myjqueryplugins.com/jrating/php/jRating.php
and use the following version of jRating
https://github.com/alpixel/jRating
Overview:
I'm using the JQuery Form Plugin to send Form Data to a remote file via AJAX. The File then processes the form data and inserts it into the MySQL Database.
Problem:
The Problem is, however, when I want to run code on a successful add, (usually completed using the "success" option, it never runs. Doing further research I found that I needed to send back "responseText" to make the function under "success" run.
Questions:
1) Is this true?
2) How do I go about sending back responseText?
3) (If number on is that it is not true) How do I get the function under success to run?
A few code Snippets:
JQuery (Using the JQuery Form Plugin):
$("#form1").ajaxForm({url: 'submit.php', type: 'post', resetForm: true, success: function () { $('#new-paste').modal({show: false}) }});
I can provide the contents of the remote file (submit.php) if needed.
Thank you in advance!
Change your success to:
function(response) {
$('#new-paste').modal({show: false});
alert(response); // response is the output from the php script it submitted to.
}
Hope this helps.
Alright, so I found the solution.
The Script had to be included on the page itself, not in a remote .js file.
so:
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
</script>
Should be included in the head.