I am trying to create a ajax-login-form, but my jquery-script cant find the php file. they are in the same directory (!), but it doesn't work.
my php-file (logreg.php)
<?php
echo 'true';
?>
my script-file (logreg.js)
$("button[action=\"register\"]").click(function(){
var username = $("#login-username").val();
var password = $("#login-password").val();
var repassword = $("#login-repassword").val();
$.ajax({
type: "POST",
url: "logreg.php",
data: "name="+username+"&pass="+password+"&repass="+repassword,
success:function(html){
if(html=='true'){
}
},
beforeSend:function(){
$("button[action=\"register\"]").text("Sendet ...");
},
error: function(ts) { $("div#content").html(ts.responseText); }
});
});
why isnt this working? i am getting everytime "Error 404" (not found).
they are in the same directory
URLs are relative to the HTML document not the JavaScript file.
You should be able to load your logreg.php in your browser and get the 'true' message on your screen. So use whatever url to get to your php file, then use the same url in your js file:
url: "http://mydomain.local/logreg.php",
Related
I have used before these jquery-ajax and php codes. Everything was fine but know there is a problem that success function not working. However, php codes are working, I can add data to mysql database, but I couldn't post info back to javascript file again by use "echo" or any way. Is this problem could originate because of server? I need your support.
I have checked php file is working or not and there was no problem about php. In javascript file in ajax codes, I have tried beforeSend and complete functions, everything were fine. But success function not working.
JS codes:
var userCookie = 1;
var question_txt = document.getElementById("question_txt").value;
var category_slct = document.getElementById("category_slct").value;
$.ajax({
type: "POST",
url: websitePHP + "ask.php",
data: {
user : userCookie,
quest : question_txt,
cat : category_slct
},
beforeSend: function(){
},
success: function(data){
alert(data);
if(data == 'ok'){
alert('Question added');
}
}
})
PHP codes:
include("ayar.php");
$userID = $_POST['user'];
$categoryID = $_POST['cat'];
$question_txt = $_POST['quest'];
$askedTime = time();
$addQuestion = $vt->prepare("INSERT INTO ".$QUESTIONS." (userID, categoryID, question, image, link, sight, pinned, bestAnswerID, askedTime, publishedTime, published)
VALUES (?,?,?,?,?,?,?,?,?,?,?)");
$addQuestion->execute(array(''.$userID.'',''.$categoryID.'', ''.$question_txt.'', '', '', 0, 0, '', ''.$askedTime.'', '', 0));
echo 'ok';
exit();
I need to get back response from php to js by success function in ajax.
Thanks for your help,
Best regards.
Can you try
return 'ok'; instead of echo 'ok'; and removing exit(); function
I am using some ajax request to access to php file. It's working perfectly exept one part. When I am getting the $_POST value of one of my variable, it crops the end of the word.
$.ajax({
type: 'post',
url: 'https://myadress.com',
data: {
workout: JSON.stringify(workout),
username: localStorage.getItem('username'),
workout_name: $('#name').val().toString(),
},
success: function (data) {
alert(data);
},
});
If i alert workout_name before sending it, it displays "test" but when i echo it from my php file, it displays "te".
I am wondering why it's doing that, i can't fix it. I was thinking maybe the size of my other variable are too big...
Here is my php code:
` if(isset($_POST['username']) && isset($_POST['workout_name']) && isset($_POST['workout'])) {
$workout_name = $_POST['workout_name'];
echo $workout_name;
$username = $_POST['username'];
$workout = json_decode($_POST['workout']);
}`
Thank you for your answer.
Edit:
Thanks to the answer, it's working now. I just need to do :
workout_name: encodeURIComponent($('#name').val())
in my js file and when I retrieve the data in the php file I use :
urldecode($_POST['workout_name']);
On my website I am trying to basically generate a random code (which I will set up later) and then pass that code into a PHP file to later retrieve it when the client needs it. But my code just isn't working.
Here is the code:
Javascript/HTML:
function init() {
var code = "12345";
$.ajax({
type: 'POST',
url: 'codes.php',
data: { code: code},
success: function(response) {
$('#result').html(response);
}
});
}
PHP:
<?php
$code = $_POST['code'];
echo $code
?>
So what I understand that is supposed to happen is that the code is uploaded or 'posted' to the php file and then the #result is the echo $code. None of that happens and I have no idea.
Your code working perfect with some basic changes.
You need a html element with id 'result'.
And then you need to call your init() as per requirement.
<div id="result"></div>
<script>
function init() {
var code = "12345";
$.ajax({
type: 'POST',
url: 'codes.php',
data: { code: code},
success: function(response) {
$('#result').html(response);
}
});
}
init();
</script>
I tried this on my server in the head of my document, and it worked :)
I used on complete instead of on success.
<script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script>
<script>
function init() {
$.ajax({
type: "POST",
url: "codes.php",
data: {
'code': '12345'
},
complete: function(data){
document.getElementById("result").innerHTML = data.responseText
},
});
}
init();
</script>
with codes.php the same as you have :)
just a few notes:
Make sure you point your url to the correct file. You can check it by using the console network. Or you can simply print anything out, not just the $_POST data. e.g:
echo 'Test info';
Open browser developer panel, to see if is there any client code issue. For example, document with id 'result' existed, or you have not included jquery in. The developer console will tell you everything on the client side. For Chrome, check it out here https://developer.chrome.com/devtools
Have you actually called init() ?
I am trying to get the contents from some autogenerated divs (with php) and put the contents in a php file for further processing. The reason for that is I have counters that count the number of clicks in each div. Now, I ran into a problem. When I echo back the data from the php file, the call is made, but I get undefined in the form-data section of the headers, and NULL if I do var_dump($_POST). I am almost certain I am doing something wrong with the AJAX call. I am inexperienced to say the least in AJAX or Javascript. Any ideas? The code is pasted below. Thanks for any help / ideas.
The AJAX:
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).find(".test");
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#resultcart").html(returnhtml);
}
});
});
});
The PHP is a simple echo. Please advise.
Suppose you have a div
<div id="send_me">
<div class="sub-item">Hello, please send me via ajax</div>
<span class="sub-item">Hello, please send me also via ajax</span>
</div>
Make AJAX request like
$.ajax({
url: 'get_sorted_content.php',
type: 'POST', // GET is default
data: {
yourData: $('#send_me').html()
// in PHP, use $_POST['yourData']
},
success: function(msg) {
alert('Data returned from PHP: ' + msg);
},
error: function(msg) {
alert('AJAX request failed!' + msg);
}
});
Now in PHP, you can access this data passed in the following manner
<?php
// get_sorted_content.php
if(!empty($_POST['yourdata']))
echo 'data received!';
else
echo 'no data received!';
?>
It's sorted. Thanks to everyone. The problem was I didn't respect the pattern parent -> child of the divs. All I needed to do was to wrap everything in another div. I really didn't know this was happening because I was echoing HTML code from PHP.
When I want to printout the output of jQuery AJAX, which has been recived from server. It doesn't show the right charset. What I want exactly is to get š instead I am getting ? or without using utf8_decode() when sending data from server, I get ĹĄ. All files script.js and server php proceed.php are saved in UTF-8 and set in UTF-8. Database is set to UTF-8 as well. All other request from database give the right charset. I've tried most of the things.
In .js file for AJAX:
$.ajaxSetup({
url: "proceed.php", //file to procces data
ContentType : 'charset=UTF-8', // tried here
global: false,
type: "POST",
dataType: "html" // change to text/html, application/text doesnt work at all
});
In .php file:
mysql_query("SET NAMES utf8");
$output = utf8_decode($sql_result);
All possible combinations.
CODE:
PHP
if(!empty($_POST['select_had'])){
$zem = $_POST['select_had'];
$vysledek = mysql_query("SELECT typ_hadanky, jazyk FROM hlavolam RIGHT JOIN hadanka ON hlavolam.id_hlavolamu=hadanka.id_hlavolamu WHERE zeme_puvodu='$zem'");
$out = "";
while ($zaznam = mysql_fetch_array($vysledek)) {
$zaz = $zaznam['jazyk'];
$out .= "<option>".$zaz."</option>";
}
$vys = utf8_decode($out);
echo $vys;
}
jQuery:
$("#sel_had_zem").change(function(){
var select_had = $("#sel_had_zem option:selected").text();
$.ajax({
data:{'select_had':select_had},
success: function(data){
$("#sel_had_jaz option").nextAll().remove();
$("#sel_had_jaz").append(data);
},
error: function(){
alert('No server response');
}
});
});