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();
Related
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;
basically i have a form and in that form i have a username textbox with a submit button. now what i want is that before we submit the form i want to send the text value to server so the server could check if the username has not been taken by any other user and then submit the form, based on research i had, i found this tutorial useful https://scotch.io/tutorials/submitting-ajax-forms-with-jquery, altough this tutorial is using php for server coding and i am using java servlet but my ajax script never gets to execute.
here is my code:
<html>
<head>
<meta charset="utf-8" name="viewport" content="width=device-width, initial- scale=1">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"> </script>
<script>
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
event.preventDefault();
alert('hello');
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'username' : $('input[name=UserName]').val(),
};
alert('hello');
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : '../postr', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
});
});
</script>
<form class="Registration_Form" id="Registration_Form" action="../postr" method="POST">
<div id="Registeration_Username_DIV" class="Registeration_Username_DIV">
<input type="text" id="Registeration_Username_box" class="Registeration_Username_box"
name="UserName" onblur="Usernameerrorfunc(this, 'Usernameerror_spn', 'Usernamenowallow_spn');" maxlength="30" onclick="textboxfocus(this)"/>
</div>
<div class="Registration_Submit_Div">
<input type="submit" value="submit" id="SumbitForm_btn" class="SumbitForm_btn" name="Submit_btn"/>
</div>
</form>
<script>function Usernameerrorfunc(field, errordiv, Notallowcharserror_SPN) {
if (field.value == '') {
field.style.borderColor = "red";
document.getElementById(Notallowcharserror_SPN).style.visibility = "hidden";
document.getElementById(errordiv).style.visibility = "visible";
} else if(!field.value.match(/^[a-zA-Z0-9~`!##\(\.)]+$/)){
field.style.borderColor = "red";
document.getElementById(Notallowcharserror_SPN).style.visibility = "visible";
document.getElementById(errordiv).style.visibility = "hidden";
} else {
field.style.borderColor = "rgb(150,150,150)";
document.getElementById(errordiv).style.visibility = "hidden";
document.getElementById(Notallowcharserror_SPN).style.visibility = "hidden";
}
}</script>
as you can see in my ajax script i have an alert() which it should pop up hello but it never does
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;
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.
I am trying to send post data to my post data file handler called postinfo.php with jQuery but so far I can make it.
Here is my post.php code:
<HTML>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<script type="text/javscript">
$('#form_id').on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "http://www.vemvo.com/test/postinfo.php",
data: $(this).serialize(),
success: function() {
alert('success');
}
});
});
</script>
<form method="post" id="form_id">
<input type="text" name="ime">
<input type="submit" id="submit" name="submit" value="Send">
</form>
You can see the page here: http://www.vemvo.com/test/post.php
Here is the code from my postinfo.php:
<?PHP
$ime = $_POST['ime'];
echo "Your name is $ime";
?>
Here is located postinfo.php - http://www.vemvo.com/test/postinfo.php
So where is my mistake and how I can make it work?
Now it's not sending the data and not giving me the success alert.
Your jQuery selector isn't going to find that form, since the selector is running before the form tag exists in the DOM. Try wrapping it in the jQuery function to wait for the document to be ready:
$(function () {
$('#form_id').on('submit', function(e){
// the rest of your code
});
});
It also might be a good idea to return false at the end, to further suppress the form's default post action:
e.preventDefault();
$.ajax({
type: "POST",
url: "./postinfo.php",
data: $(this).serialize(),
success: function() {
alert('success');
}
});
return false;
Currently the form is posting as normal. Since the AJAX handler is never attached (because the element doesn't exist when the selector executes), it's just doing a normal document-level form post. And since there's no action attribute specified in the form tag, the page is posting to itself by default. Which just responds with the current page.
Edit: You also have a typo which may be preventing the browser from executing your JavaScript code at all:
<script type="text/javscript">
You're missing the second "a". This should be:
<script type="text/javascript">
You MUST spell text/javascript correctly
You need to assign the event handler on load
There should not be any need to return false as posted by some other people here
NEVER call anything submit in a form
Wrap your html in body tags
Use a correct DOCTYPE
For files you can have a look at uploadify or How can I upload files asynchronously?
Fixed code for point 1 to 6
<!DOCTYPE html>
<html>
<head>
<title>Test Ajax</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#form_id').on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "./postinfo.php",
data: $(this).serialize(),
success: function() {
alert('success');
}
});
});
});
</script>
</head>
<body>
<form method="post" id="form_id">
<input type="text" name="ime">
<input type="submit" value="Send">
</form>
</body>
</html>