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');
}
});
});
Related
I basically don't seem to understand sending a variable to another page.
I've tried PHP sessions, javascript cookies and ajax POST and GET.
I'm trying to send the innerHTML of a div, with the data created by a jQuery call,
a variable called savedartists. It displays correctly in the console.log on the sending page but the $_POST['savedArtists']
is undefined in the receiving page. I have spent hours looking at different posts on this site but I haven't been able to get it to work.
Any help is appreciated.
<input class="et_pb_button et_pb_button_0 et_pb_bg_layout_light" onClick="savequote();" type="button" id="savedchoices" value="Commander la prestation" >
<script>
function savequote() {
var savedartists = document.getElementById('selectedList').innerHTML;
console.log(savedartists);
$.ajax({
type: "POST",
url: 'example.com/artiste/mise-en-relation/',
data: { savedArtists : savedartists },
success: function(data) {
console.log("success!");
location.href = "example.com/artiste/mise-en-relation/";
}
});
}
</script>
On the receiving page (example.com/artiste/mise-en-relation/)
<?php
if(isset($_POST['savedArtists']))
{
$uid = $_POST['savedArtists'];
echo $uid;
} else {
echo 'zit!';
}
?>
Thanks for your time
Capturing as an answer for future readers...
Fundamentally what's happening here is that two requests are being made to the target page. The first one is the AJAX request:
$.ajax({
type: "POST",
url: 'example.com/artiste/mise-en-relation/',
data: { savedArtists : savedartists },
success: function(data) {
//...
}
});
This is a POST request which contains the data you expect, and works just fine. However, the result of this request is being ignored. That result is available in the success callback, but the code doesn't do anything with it:
console.log("success!");
location.href = "example.com/artiste/mise-en-relation/";
Instead, what the code is doing is performing a redirect. This creates a second request to that same page (though it's essentially irrelevant that it's the same page). This is a GET request and contains no data to send to the server.
At its simplest, you should either use AJAX or redirect the user. Currently you're mixing both.
I want to redirect to the other page.
In that case AJAX is the wrong tool for the job. You may not even need JavaScript at all, unless you want to modify the elements/values of a form before submitting that form. But if all you want is to POST data to another page while directing the user to that page, a plain old HTML form does exactly that. For example:
<form method="POST" action="example.com/artiste/mise-en-relation/">
<input type="text" name="savedArtists">
<button type="submit">Submit</button>
</form>
In this case whatever value the user enters into the <input> will be included in the POST request to example.com/artiste/mise-en-relation/ when the user submits the form.
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
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.
I need help with this stuff. Chrome doesn't have this problem, only Firefox. When I submit form, ajax creates tasks. My mysql queries ain't got any problems, I added tons of
if not working write mysql error into file
But all are successful. So here is the error
http://i.stack.imgur.com/KYq4L.jpg how to find out what the hell is this? My code of ajax is pure empty here it is:
$.ajax({
type: "POST",
url: '/modules/projects/ajax/ajax_import.php',
data: {
data: array,
id: projectNow,
}
});
Thats it.
First check ajax_import.php is available at this location or not.
/modules/projects/ajax/ajax_import.php
If file is exist at this location then just clear all content from there and just write test content as below.
<?php
echo "testing";
?>
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.