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;
Related
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>
I am trying to call a function that isn't being recognised. I have a PHP block of code that adds the form to the HTML when the user is logged in:
<?php
if(isset($_SESSION['user'])) {
$usr = $_SESSION['user'];
echo("<form onsubmit=\"nbpost('#nbpost','$usr'); return false;\">\n");
echo("<textarea id='nbpost' placeholder='Create a post...'></textarea>\n");
echo("<button type='submit'>SUBMIT</button>\n");
echo("</form>\n");
}
?>
I put my JavaScript below that HTML. According to W3Schools, the script has nothing to do with how it's executed. Additionally, I've tried countless times to execute the script when the script was on top, with no result either.
Also, I previously had the code in a separate script, but I've taken it out to see if that's the issue.
Here's the script with an example of the generated HTML:
<form onsubmit="nbpost('#nbpost','$usr'); return false;">
<textarea id='nbpost' placeholder='Create a post...'></textarea>
<button type='submit'>SUBMIT</button>
</form>
<script type="text/javascript">
const nbpost = function(element, name) {
alert("WORKING");
name[0] = name[0].toUpperCase();
const msg = $(element).val;
console.log(name, msg);
$.ajax({
url: "http://rmpc/php/nbpost.php",
method: "POST",
data: {
name: name,
notice: msg
}
});
};
</script>
Whenever I execute the code, it simply says in the console:
Uncaught TypeError: nbpost is not a function at HTMLFormElement.onsubmit (index.php:54)
What's going wrong?
Change the name of the function nbpost so it does not match the textarea id='nbpost'
CodePen
I would try and separate your content a little better, it can make it less confusing. Give this a try with jQuery enabled.
<?php
if(isset($_SESSION['user'])) {
$usr = $_SESSION['user']; ?>
<form id="form" method="post">
<textarea id='nbpost' placeholder='Create a post...'></textarea>
<input type="hidden" name="user" value="<?=$usr;?>">
<button type='submit'>SUBMIT</button>
</form>
<?php
}
?>
This needs to go at the bottom of your document. You can also put the JavaScript in a separate file and call it by filename of course.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$("#form").on("submit", function (e) {
e.preventDefault();
var name = $("input[name=user]").val().toUpperCase();
var msg = $("#nbpost").val();
console.log(name, msg);
$.ajax({
url: "http://rmpc/php/nbpost.php",
method: "POST",
data: {
name: name,
notice: msg
}
});
});
</script>
see if this works for you.
You should declare your submit event as an entire function
onsubmit=\"function(){nbpost('#nbpost','$usr'); return false;}\"
I viewed so many post aboit this but still cant get my code to work.
I want to get a php array of my checked checkboxes values.
heres my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<title>Untitled Document</title>
</head>
<body>
<?php
echo'<form method="post">
<input type="checkbox" name="cim" value="valami">';
echo'<input type="checkbox" name="cim" value="valami2">';
echo'<input type="checkbox" name="cim" value="valami3">';
echo'<input type="checkbox" name="cim" value="valami4">
<input type="submit" value="Felvisz" name="feladat"></form>';
if (isset($_POST['feladat'])) {
?>
<script type="text/javascript">
var checkedValue = $('.messageCheckbox:checked').val();
var myJSON = JSON.stringify(checkedValue);
$.ajax({
type: "POST",
url: "proba.php",
data: { tomb : myJSON },
success: function(){
alert("OK");
}
});
</script>
<?php
var_dump($_POST);
$array = json_decode(stripslashes($_POST['tomb']));
foreach($array as $arr){
echo $arr;
}
}
?>
</body>
</html>
Massages i got:
Notice: Undefined index: tomb in D:\programok\xamp\htdocs\SZAKDOGA\Dropbox\proba.php on line 48
Warning: Invalid argument supplied for foreach() in D:\programok\xamp\htdocs\SZAKDOGA\Dropbox\proba.php on line 49
Please someone can help me to solve this?
To get an array , you must convert the name to accept multiple so change the input's :
name="cim"
to
name="cim[]"
Also your jquery ajax function should be this :
<script type="text/javascript">
$(function(){
$("form").on("submit",function(e){
e.preventDefault();
var checkedValue = $(this).serialize();
$.ajax({
type: "POST",
url: "proba.php",
data: checkedValue,
success: function(){
alert("OK");
}
});//end ajax
});//end form submit
});
</script>
in php the cim will be the array example
var_dump($_POST["cim"]);
hope it helps
currently, you are testing for checked boxes with class messageChecked. assign your checkboxes that class, give your form an id, then test for checked condition on each checkbox,
$('#yourForm').each(function() {
if($('.messageChecked').is(':checked')) {
checkedValue.push($('.messageChecked:checked').val());
}
}
now send it to your php script via ajax,
$.ajax({
type: "POST",
url: "proba.php",
data: { tomb : (checkedValue) },
success: function(){
alert("OK");
}
});
if done like this you can remove json_decode and stripslashes from your $_POST statement
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;
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>