$.ajax still does not execute - javascript

herewith my full code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="generator" content="CoffeeCup HTML Editor (www.coffeecup.com)">
<meta name="dcterms.created" content="Tue, 03 Feb 2015 08:06:46 GMT">
<meta name="description" content="">
<meta name="keywords" content="">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function validateLogIn()
{
var username = $("#username").val();
var password = $("#password").val();
var login = $("#login").val();
//var remember = $("#remember").val();
$.ajax({
url: 'validate.php', //i never get to this file!
type: 'POST',
data: { 'username' : username , 'password' : password, 'login' : login}
}).done(function(response){ //Attach a succes handler
alert(response); //this doesn execute
});
return false;
}
</script>
</head>
<body>
<form action="crud.html" method="post" name="form_submit" onsubmit="return validateLogIn()">
<input required placeholder="Username" type="text" name="username" id="username"/>
<input required placeholder="Password" type="password" name="password" id="password"/>
<label for="remember">Remember Me:</label>
<input type="checkbox" name="remember" value="yes" id="remember" />
<br />
<br />
<input type="submit" name="login" value="login" id="login"/>
</form>
</body>
</html>
then validate.php
<?php
//i never get here i dont understand
echo htmlspecialchars($_POST['username'], ENT_QUOTES, 'UTF-8');
echo $username = $_POST['username'];
echo$password = $_POST['password'];
if ($_POST['login']) //check if the submit button is pressed
{
$remember = $_POST['remember'];
....../
please help, i have been struggeing with this the whole day
i get this when i do //localhost/php/validate.php

I've checked your code works perfectly. So what's wrong?
If you access your validate.php directly, you don't send any data to it and hence $_POST[] contains nothing. You should visit your form page, type something in your form and click login and you should get an alert with response from your validate.php.
Via AJAX you send your request in the background and and if you send some data to your validate.php it will work otherwise it won't. I suggest you do all kind of error checking/handling.

For your 'data' property, in my opinion, you should remove the quotes.
Also to really debug and find out the answer, you should debug like this. Adding these other properties will help you determine what issues / errors you're getting.
$.ajax({
url: 'validate.php', //i never get to this file!
type: 'POST',
dataType: 'xml', //YOu're missing this value!!!
data: { username : username , password : password, login : login},
beforeSend: function() {
//This will execute regardless what happends before the AJAX is sent.
},
success: function(xml) {
//Will execute if no errors are present while sending AJAX
},
error: function(xml) {
//If any error happens while sending AJAX, this will be called.
},
complete: function(xHR, textStatus) {
//This will execute regardless what happens.
},
});
The "beforeSend" property will execute before anything is sent to the server to be validated.
The "success" Will only execute if there is no error in the dataType that is returned, or any error for that matter.
The "Error" will only execute if the returned data is not what dataType expected it to be.
The "complete" Will execute regardless what happens.

Related

How can I retrieve data from a database using AJAX and save the results in a variable?

I'm new to jQuery and AJAX and I'm working on a login-page as a project and I need to retrieve data from a database using AJAX. I'm not 100% fluent in English so I'll do my best to explain the problem (with help from Google Translate).
Here's the code I'm using:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<form validate="">
<input type="text" placeholder="Username" id="username" required/><br />
<input type="password" placeholder="Password" id="password" required/><br />
<input type="submit" id="submit" value="Login" />
</form>
<script type="text/javascript">
// when document is loaded
$(document).ready (
// when submit is clicked
$("#submit").click (
// sets test to null
var test = null;
// sets username to value of username input
var username = document.getElementById("username").value;
// AJAX request
$.ajax({
type: "POST",
async: true,
url: test.php,
data: {username: username},
success: function (data) {
test = data;
console.log(test);
return test;
}
});
);
);
</script>
</body>
</html>
test.php
<?php
// connects to database
$conn = mysqli_connect('server', 'username', 'password', 'database');
// sets var username to POST username value
$username = $_POST['username'];
// SQL Query
$sql = "SELECT * FROM users WHERE username='" . $username . "'";
$result = mysqli_query($conn, $sql);
// sets result to mysqli_fetch_assoc()
$result = mysqli_fetch_assoc( $result );
// echos $result
echo $result['password'];
// closes database connection
mysqli_close( $conn );
?>
Console Log
Console Output:
```
[DOM] Input elements should have autocomplete attributes (suggested: "current-password"): (More info: https://www.googlesite.com)
​
Uncaught SyntaxError: Unexpected token var ajax.html:19
I've looked at the code and I can't seem to find an error.
Thanks in advance! ;)
>P.S.
>It's probably going to end up being some stupid typo.
>Other than that, have a great day!
Instead of using click event you can use submit.
In your case, just give id to your form like -
<form validate="" id="submit">
Now,
In your js script -
$(function() { //shorthand document.ready function
$('#submit').on('submit', function(e) {
e.preventDefault(); //prevent form from submitting
console.log(data);
$.ajax({
type: "POST",
async: true,
url: test.php,
data: $(this).serializeArray(),
success: function (data) {
console.log(data);
}
});
});
});
So check your whole code -
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<form validate="" id="submit">
<input type="text" placeholder="Username" id="username" required/><br />
<input type="password" placeholder="Password" id="password" required/><br />
<input type="submit" value="Login" />
</form>
<script type="text/javascript">
// when document is loaded
$(function() { //shorthand document.ready function
$('#submit').on('submit', function(e) {
e.preventDefault(); //prevent form from submitting
console.log(data);
$.ajax({
type: "POST",
async: true,
url: test.php,
data: $(this).serializeArray(),
success: function (data) {
console.log(data);
}
});
});
});
</script>
</body>
</html>
Hope this will help you.
You need to pass in a function to your document.ready() call and your click() call.
<script type="text/javascript">
$(document).ready(function() {
Your variables here...
$('#submit').click(function() {
... Ajax call here.
});
});
</script>

Working in Local system but not when uploaded in server

I created a simple form, onSubmit it takes the values to js page(AJAX CALL) then send to add.php page again returns the value to html page.
This code is working fine on my local system but when i test it in server AJAX call is not working.Even i just tested as on submit(click) alert from add.js(AJAX) but not working and works good in local(XAMP)
var btn = document.getElementById("sub");
btn.addEventListener("click", function() {
//alert('came');
var data=$("#myForm :input").serializeArray();
$.post($("#myForm").attr("action"),data,function(info){
$("#result").html(info);
});
});
$("#myForm").submit(function() {
return false;
});
<!DOCTYPE html>
<html>
<head>
<title>
Ajax call
</title>
</head>
<body>
<form id="myForm" action="add.php" method="post">
<input type="text" name="uname">
<input type="text" name="age">
<button id="sub">submit</button>
</form>
<span id="result"></span>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="add.js"></script>
</body>
</html>
Here is my add.php , which echo the result that will be displayed in my html result div tag `
<?php
$name=$_POST['uname'];
$age=$_POST['age'];
echo $name;
Is there anything to change while uploading in server.Whats wrong in my code.
Thanks in advance.
This is the object you are sending to the server, you can see that it has not the structure that the server side 'add.php' is expecting, so there is no $_POST['uname'] variable. You may use a var_dump($_POST) to see the structure you are receiving or use $("#myForm").serialize() that I've used a lot and worked fin to me.
var btn=document.getElementById("sub");
btn.addEventListener("click",function(){
alert('came');
var data=$("#myForm :input").serializeArray();
$.post($("#myForm").attr("action"),data,function(info){
$("#result").html(info);
$('#myForm')[0].reset();*/
//please have a look in your add.js:9:26
});
});
$("#myForm").submit(function(){
return false;
});
Could you follow ajax in this method, Surely it will works for you.
<button type="button" onclick="submit()" class="input-group-addon addbtn">Submit</button>
function submit(){
var data = $("#myForm").serialize();
$.ajax({
url: 'your url',
type: "post",
data: {'formSerialize':data, '_token': $('meta[name="_token"]').attr('content')},
success: function(data){
if(data.success==1){
alert('success');
}else if(data.error==1){
alert('error');
}
}
});
}
In your controller you can get the value like this
parse_str($data['formSerialize'],$input);
In $input You can easily access all the field value.
Problems: I'm not 100% sure what's causing your problem. But on my end I found the problem to be browser related since it worked on Chrome but not on FireFox.
One scenario would that FireFox didn't recognize your:
$("#myForm").submit(function() {
return false;
});
It does happen that FireFox will do so if you don't abide by its standards. I did explain this in my answer about event.preventDefault();
I also completely changed your add.js as I've found some of your code unnecessary and that it could be combined into a cleaner function. Since you're already using jQuery might as well stick to it and not use DOM.
FORM:
<!DOCTYPE html>
<html>
<head>
<title>
Ajax call
</title>
</head>
<body>
<form id="myForm">
<input type="text" name="uname">
<input type="text" name="age">
<button type="submit">Submit</button>
</form>
<span id="result"></span>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="add.js"></script>
</body>
</html>
ADD.JS
//you need to add "event" as a parameter to the function since Firefox
//will not recognize event.preventDefault(); if its missing
$( "#myForm" ).on( "submit", function( event ) {
event.preventDefault(); //this will prevent the form from submitting
var form_data = $("#myForm").serialize();
$.ajax({
method: "POST",
url: "add.php",
data: {form_data: form_data},
success: function (info) {
$("#result").html(info);
}
});
});
ADD.PHP
<?php
$form_data = $_POST['form_data'];
$params = array();
parse_str($form_data, $params);
$name = $params['uname'];
$age = $params['age'];
echo $name;

jQuery Ajax - Wrong response

I have a problem with jQuery ajax function:
var arrayIdEq = JSON.stringify(iditem);
$.ajax({
type: "POST",
url: "index.php",
dataType : 'text',
contentType: 'application/json; charset=utf-8',
data: {
arrayIdEq : arrayIdEq
},
success: function(answer) {
alert(answer);
},
complete: function() {
},
error: function(jqXHR, errorText, errorThrown) {
alert(jqXHR+" - "+errorText+" - "+errorThrown);
}
});
"arrayIdEq" contains number from 0 to 7, or string "EMPTY".
PHP code:
elseif(isset($_POST['arrayIdEq'])){
$answer = "my_answer";
return $answer;
After request, when success response come, alert show up... but here's the problem. Instead of "$answer" value, alert contains... HTML code from my main page!
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title> Medivia</title>
</head>
<body>
<h1>Medivia</h1>
<form action="index.php" method="POST">
<label>E-mail:<br><input type="text" name="mail" required></label>
<br>
<label>Hasło:<br><input type="password" name="pass" required></label>
<br>
<button name="login">Zaloguj się</button>
</form>
</body>
</html>
I have no idea what happend here. Could anybody explain to me what happend there? What did i do wrong?
Your answer variable in the success function will contain the complete output of your php script.
So when you call index.php and you do:
elseif(isset($_POST['arrayIdEq'])){
$answer = "my_answer";
return $answer;
}
The script will only exit if the return statement is called from the main script (not from within a function) but the output will be the output generated by the script until that point.
Your script should output - and not return - only what you want returned to the javascript.
Probably a separate script for ajax requests will be a more convenient solution than using the index.php file you use to build the complete page.

Php mysql undefined index error used jquery for traferring data from one page to another

This is my first project where I used Jquery.
There are two pages 1. listofleaders.php 2. leadersprofile.php
On First Page i.e. listofleaders.php
I have a input text box, where user enters leaders name and I used jQuery code to transfer textbox values to leaderprofile.php page
<html>
<head>
<script>
function ls()
{
var leaderdetails = "leaderprofile.php?lname="+$("#gopal").val();
$.get(leaderdetails, function( data ) {
//alert(leaderdetails);
location.href = "leaderprofile.php";
});
}
</script>
</head>
<body>
<input type="text" id="gopal" name="t" placeholder="Start Typing" size="50" />
<button onclick="ls();" type="button">Go!</button><br><br>
</body>
</html>
On Second Page leadersprofile.php I have written this,
<?php
include "admin/includes/dbconfig.php";
$lname = $_GET['lname'];
echo $lname;
?>
But on second page i.e. leaderprofile.php it is showing me error
Undefined index : lname
Am I Correct to this approach ?
Where I am Wrong ?
Hope you Understand.
So I am having a guess here at what you are trying to achieve based on your problem description.
If you want to send a <input> value to another page, you better use a classic POST request (without the need of evolving jQuery):
<form method="post" action="leadersprofile.php">
<input type="text" name="lname"/>
<button type="submit">Send</button>
</form>
And in leadersprofile.php:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['lname'])) {
$lname = $_POST['lname'];
var_dump($lname); // outputs whatever the user input was
}
Now if you want to send the data to leadersprofile.php without reloading the page, you are looking for an Ajax request (XmlHttpRequest).
jQuery(function($) {
$('form').on('submit', function(e) {
e.preventDefault(); // prevents default behavior that is submitting the form
$.ajax({
method: 'post', // can be also 'get'
url: 'leadersprofile.php',
data: {lname: $('input').val() },
success: function(html) {
$('div').html(html); // place whataver was printed in leadesrprofile.php into a div
},
error: function(r) { // fire if HTTP status code != 200
console.log(r);
}
});
});
});
You seem to be using JQuery correctly. The Javascript to extract the value and the send the GET request should be working.
Your misunderstanding lies in how you check if the PHP file has received the request. This redirect
location.href = "leaderprofile.php";
Will not provide you any information about the GET request that you just made. Instead you can try:
location.href = "leaderprofile.php?lname=" + $("#gopal").val()
To verify that your PHP and Javascript is performing as expected. If you see the values that you expect then I believe you have confirmed two things:
successfully extracted the correct value from the textbox
GET request is succeeding, and the success callback is being invoked
I understand your question.Try the following codes.
listofleaders.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form>
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td></td>
<td><button id="submit">Submit</button></td>
</tr>
</table>
</form>
<script src = "jquery.js"></script>
<script src = "leader.js"></script>
</body>
</html>
When submit button is click, leader.js file will get the value of text box.
leader.js
$(document).ready(function() {
$('#submit').on('click', function(){
var name = $('#name').val();
$.ajax({
url:'leaderprofile.php',
type:'POST',
data:{'name':name},
success:function(data){
}
});
});
});
Now, this leader.js file will send the name key to liderprofile.php.
After that php file witt return the data(name) to js file..and the js file will alert name.
leaderprofile.php
<?php
$name = $_POST['name'];
echo $name;

jQuery POST Ajax request

i'm trying to post data from Server A, let's say: www.a.com to server B, www.b.com and then fetch the response from server B
I do it like this, this script runs on server A:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Naamloos document</title>
</head>
<body>
<form id="Form" onsubmit="validate();" method="post">
Email Address: <input type="text" id="email" name="email">
Password: <input type="text" id="password" name="password">
<input type="submit">
</form>
<script>
function validate()
{
var e = $('email').value;
var p = $('password').value; //jQuery is easier to type
// the same as
// var p = document.getElementById('password').value;
var req = new Request({
url: 'http://www.B.com/validate.php?',
method: 'post',
data: {'email' : e, 'password' : p},
onComplete: function(response)
{
if (response == "Valid" )
{
alert("succes");
}
else
{
alert("blur");
}
}
}).send();
}
</script>
</body>
</html>
But at this moment, after hitting the submit button, the only thing that happends is that the fields are being cleared, thats all.
Validate.php looks like this:
<?php echo "Valid"; ?>
You're submitting the form, so the JavaScript never gets a chance to do anything significant. Since you haven't specified an action, it submits to the current URL and reloads the page.
Stop using intrinsic event attributes.
Use JS event binding (since you are using jQuery already, keep using it)
Capture the event object and prevent the default behaviour of the submit event
such:
<form id="Form" method="post">
$('#Form').on('submit', validate);
function validate (event) {
event.preventDefault();
var e = $('#email').val();
You also don't appear to have defined Request anywhere. You should probably switch to jQuery ajax
Also note that Server B will have to give Server A permission to make Ajax requests to it using CORS.
Try to replace this
var e = $('email').value;
var p = $('password').value;
with this
var e = $('#email').val();
var p = $('#password').val();

Categories