$(document).ready(function(){
$('.clickthetext').click(function(){
$.post("submit.php", $("#formbox").serialize(), function(response) {
$('#content').html(response);
});
return false;
});
});
My target to pass content from the form and edit the data and show response at current page.
.clickthetext button content:
<div class="clickthetext">Click here to see the result</div>
content inside id #formbox:
Part of the form inside this id. rest of the form is out side this id will be processed later. only content/input inside of id "formbox" will be processed.
Whatever response we will get, we will show inside of "#content" id.
What i am doing wrong here?
----edit----
i didn't add anything on submit.php
only to show response, i wrote there:
<?php
echo 'somthing blah blah blah something';
?>
Maybe there is a problem with the result of submit.php
You can try calling
$(document).ready(function(){
$('.clickthetext').click(function(){
$.ajax({
type: "POST",
url: "submit.php",
data: $("#formbox").serialize(),
success: function(response) { $('#content').html(response); },
error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); },
dataType: dataType
});
return false;
});
});
instead and get more detail of the result of the ajax call.
Here's the API for the ajax object in jQuery
Recreating your set up,
JS/HTML
<form action="" id="formbox">
<input type="text" name="firstName" value="First Name">
</form>
<button class="clickthetext">Button</button>
<div id="content"></div>
<script>
jQuery(document).ready(function ($) {
$('.clickthetext').click(function() {
$.post("submit.php", $("#formbox").serialize(), function (response) {
$('#content').html(response);
})
})
});
</script>
PHP: submit.php
<?php echo 'this is the response'; ?>
Everything works perfectly.
Debugging tips:
1) Most likely - Check your javascript console for any errors. You probably have errors elsewhere in the page.
2) Ensure you're accessing the HTML page with the javascript via localhost, not a filepath
3) Unlikely, but check your PHP log.
Related
So here is the scenario:
I have HTML, JS, and PHP Files. Within the PHP File is an associative array of default values to fill out various form elements on the HTML file. I am attempting to use AJAX to take the files from the PHP Files, and put them in the corresponding form elements. However nothing is working.....
Below is the code for the corresponding files. Any help figuring this out is greatly appreciated :)
HTML
<html>
<body>
<h1>Form Validation</h1>
<form id="PersonForm">
Name: <input type="text" id="name" name="name"> <br>
Postal Code: <input type="text" id="postal" name="postal"> <br>
Phone Number: <input type="text" id="phone" name="phone"> <br>
Address: <input type="text" id="address" name="address"> <br>
<input type="submit">
</form>
Refresh
<a id="InsertDefault" href="">Insert Default Data</a>
<br>
<ul id="errors"></ul>
<p id="success"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
PHP
<?php
// Return JSON default data if requested
if ($_REQUEST['act'] == 'default')
{
$defaultData = array('name' => "Jane",
'postal' => "L5B4G6",
'phone' => "9055751212",
'address' => "135 Fennel Street");
echo json_encode($defaultData);
}
?>
JAVASCRIPT
$(document).ready(function()
{
$("#InsertDefault").click(function()
{
// make an AJAX call here, and place results into the form
$.post('backend.phps',
{ act: 'default' },
function(data) {
for (var key in data) {
document.getElementById(key).value = data[key] }
},
'json');
// prevents link click default behaviour
return false;
});
});
As a side note, I always have trouble with web development stuff because I have no idea how to properly debug what I am doing. If anyone has any tips on what are some useful tricks/tools to use for debugging web code, I'd be more than happy to get some input on that too.
Thanks for your time.
For ajax code request use:
$("#InsertDefault").click(function(){
$.ajax({
type: "POST",
url: "backend.phps",
data: "act=default&name=test&phone=test", //Something like this
success: funtion(msg){
console.log(msg);
},
beforeSend:function(dd){
console.log(dd)
}
});
});
and in your backend.php file
if ($_REQUEST['act'] == 'default'){
//echo $_REQUEST['name'];
}
And for simple debugging use browsers' console, right click on the page and click Inspect Element. (Simple)
You can also install Firebug extension on Mozilla Firefox and then right click on the page and click on inspect Element with firebug. after this click on the Console tab there.
These are the basic and simple debugging for simple ajax request.
Per the newest Ajax documentation your ajax should include the Success and Failure callbacks where you can handle the response being sent from your PHP.
This should work with you existing PHP file.
Ajax
$(document).ready(function () {
//look for some kind of click below
$(document).on('click', '#InsertDefault', function (event) {
$.ajax({
url: "/backend.phps",
type: 'POST',
cache: false,
data: {act: 'default'},
dataType: 'json',
success: function (output, text, error)
{
for (var key in output.defaultData) {
document.getElementById(key).value = data[key]
}
},
error: function (jqXHR, textStatus, errorThrown)
{
//Error handling for potential issues.
alert(textStatus + errorThrown + jqXHR);
}
})
})
preventDefault(event);
});
I have this PHP file:
JSONtest.php
<?php
$a=5;
echo json_encode($a);
//This converts PHP variable to JSON.
?>
I want to alert this variable's value using Ajax and JSON, and for that I've written this script:
learningJSON.php
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: 'JSONtest.php',
type: 'POST',
data: data,
dataType: 'json',
success: function(result){
alert(result);
},
error: function(){
alert("Error");
}
});
});
});
But when I click the button, I get this error message:
learningJSON.php:14 Uncaught ReferenceError: data is not defined
What wrong I'm doing? How can I fix this?
<?php
$a=5;
echo json_encode($a);
//This converts PHP variable to JSON.
?>
Nope, it doesn't. Whats the point in converting a simple number to JSON? It stays the number 5
Now the real problem. Yes your data variable is not defined anywhere in your JavaScript code. If you have no data to send, remove that parameter.
However if you still want to pass some data, define it accordingly then. For example
data: { fname: "John", lname: "Doe" }
Now let's say on your next exercise you want to post form data you can use this nice function named serialize(). This will take all the postable fields from your form and send them along with this request.
data : $("#formID").serialize()
Data variable is not defined, you can delete that
Php file
<?php
$a = $_REQUEST['number'];
echo json_encode($a);
//This converts PHP variable to JSON.
?>
Javascript file
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: 'JSONtest.php',
type: 'POST',
//data: {'number' : 10}, //this is when you need send parameters to the call, uncomment to send it parameters
dataType: 'json',
success: function(result){
alert(result);
},
error: function(){
alert("Error");
}
});
});
});
I think this one should be perfect for you.
We need 3 files
index.php
login.js
login.php
That mean when user submit [index.php] script js file [login.js] running ajax process script [json] in login.js by collect all data from form input [index.php] and send and run script login.php ... This is powerful script of ajax & json
check code below
index.php
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="login.js" type="text/javascript" charset="utf-8"> </script>
</head>
<body>
<form method="post" id="login" name="login">
Email: <input type="email" id="log-mail" name="log-mail" > <br />
Password: <input type="password" id="log-pass" name="log-pass" > <br />
<button type="submit" >Log in</button>
</form>
</body>
</html>
login.js
$(document).ready(function(){
// #login = login is the name of our login form
$('#login').submit(function(e) {
$.ajax({
type: "POST",
url: "login.php",
data: $('#login').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
window.location=msg.txt;
}
}
});
e.preventDefault();
});
});
login.php
<?php
if(isset($_POST['log-mail']) && $_POST['log-mail'] != '' && isset($_POST['log-pass']) && $_POST['log-pass'] != '' ) {
$_data_ = 'index.php?user_data='.$_POST['log-mail'];
echo msg_result(1,$_data_);
}else{
$msg_att = "index.php?login_attempt=1";
echo msg_result(0,$msg_att);
}
function msg_result($status,$txt) {
return '{"status":'.$status.',"txt":"'.$txt.'"}';
}
?>
you can see on your url if you
complete all field => ...index.php?user_data=user_data#gmail.com
uncomplete => ...index.php?login_attempt=1
Hope this solve your issue
I have a form with an input field for a userID. Based on the entered UID I want to load data on the same page related to that userID when the user clicks btnLoad. The data is stored in a MySQL database. I tried several approaches, but I can't manage to make it work. The problem is not fetching the data from the database, but getting the value from the input field into my php script to use in my statement/query.
What I did so far:
I have a form with input field txtTest and a button btnLoad to trigger an ajax call that launches the php script and pass the value of txtTest.
I have a div on the same page in which the result of the php script will be echoed.
When I click the button, nothing happens...
Test.html
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
</script>
</head>
<body>
<form name="testForm" id="testForm" action="" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="txtTest" id="txtTest"/>
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
<input type="submit" name="SubmitButton" id="SubmitButton" value="TEST"/>
</form>
<div id="testDiv" name="testDiv">
</div>
</body>
The submit button is to insert updated data into the DB. I know I have to add the "action". But I leave it out at this point to focus on my current problem.
testpassvariable.php
<?php
$player = $_POST['userID'];
echo $player;
?>
For the purpose of this script (testing if I can pass a value to php and return it in the current page), I left all script related to fetching data from the DB out.
As the documentation says 'A page can't be manipulated safely until the document is ready.' Try this:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
You need to correct two things:
1) Need to add $(document).ready().
When you include jQuery in your page, it automatically traverses through all HTML elements (forms, form elements, images, etc...) and binds them.
So that we can fire any event of them further.
If you do not include $(document).ready(), this traversing will not be done, thus no events will be fired.
Corrected Code:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
$(document).ready() can also be written as:
$(function(){
// Your code
});
2) The button's HTML is improper:
Change:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
To:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
$.ajax({
url: "testpassvariable.php",
type: "POST",
data: {
userID: $("#txtTest").val(),
},
dataType: text, //<-add
success: function (response) {
$('#testDiv').html(response);
}
});
add dataType:text, you should be ok.
You need to specify the response from the php page since you are returning a string you should expect a string. Adding dataType: text tells ajax that you are expecting text response from php
This is very basic but should see you through.
Change
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
Change AJAX to pass JSON Array.
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "action.php",
data: data,
....
// action.php
header('Content-type: application/json; charset=utf-8');
echo json_encode(array(
'a' => $b[5]
));
//Connect to DB
$db = mysql_connect("localhst","user","pass") or die("Database Error");
mysql_select_db("db_name",$db);
//Get ID from request
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
//Check id is valid
if($id > 0)
{
//Query the DB
$resource = mysql_query("SELECT * FROM table WHERE id = " . $id);
if($resource === false)
{
die("Database Error");
}
if(mysql_num_rows($resource) == 0)
{
die("No User Exists");
}
$user = mysql_fetch_assoc($resource);
echo "Hello User, your number is" . $user['number'];
}
try this:- for more info go here
$(document).ready(function(){
$("#btnLoad").click(function(){
$.post({"testpassvariable.php",{{'userID':$("#txtTest").val()},function(response){
$('#testDiv').html(response);
}
});
});
});
and i think that the error is here:-(you wrote it like this)
data:{userID:$("#txtTest").val(),}
but it should be like this:-
data:{userID:$("#txtTest").val()}
happy coding :-)
When I click on "Register Now" Button, I want to execute 'input.php' in which I have code to insert my data to the database and show a success message. I don't want to leave current page.
<input type="button" id="confirm" value="Register Now" class="button">
<script type="text/javascript">
$(document).ready(function() {
$("#confirm").click(function() {
<?php
include 'input.php';
?>
alert ("data Added successfully.");
});
});
</script>
My code is giving me "data Added successfully" message but PHP file hasn't executed and no data is added to the database. All necessary data is in session variables.
Suggest you try something like the below. You shouldn't be trying to execute PHP inside of a jQuery script. Do an AJAX call and pass the data through and process it in the PHP rather than relying on the session variables. For example:
<script type="text/javascript">
$(document).ready(function () {
$("#confirm").click(function () {
$.ajax({
type: "POST",
url: "index.php",
data: {
firstname: "Bob",
lastname: "Jones"
}
})
.done(function (msg) {
alert("Data Saved: " + msg);
});
});
});
</script>
Where firstname, lastname would be your normal session data.
You can learn more about the jQuery.ajax() function in the jQuery API Documentation.
To execute a Php script from javascript, you have to use Ajax.
the following code :
$("#confirm").click(function() {
<?php
include 'input.php';
?>
alert ("data Added successfully.");
});
will not work
http://api.jquery.com/jquery.ajax/
You need to use AJAX. Ajax is the concept of calling php files from javascript from inside the page. You then get the php page output in a variable and you can choose wether you will display it or not. An example of this technology is the show more posts of Facebook. This can be easily done with jQuery.
$.post( PHP_FILE, { field1: 'value', field2: 'value'}).done(function( data )
{alert("this function will be run when the request is over and the variable data
will have the output : " + data);});
you can do this by ajax post method..
$.ready(function(){
$("#confirm").click(function() {
$.ajax({
type: "POST",
url: "give url to the input.php file ",
data:,
success:function(data)
{
alert('data');// data is the return value from input.php
}
});
});
});
Try this:
<input type="button" id="confirm" value="Register Now" class="button">
<script type="text/javascript">
$(document).ready(function() {
$("#confirm").click(function() {
$.get('input.php').
success(function(){
alert ("data Added successfully.");
});
});
});
</script>
I'm not quite sure what you've tried to do there. Anyway here's a snippet of js that should do for you (I'm pretty sure in the new jQuery release there's a better way to do this though):
$.ajax({
url: "input.php",
success:
function(data)
{
// here, for example, you load the data received from input.php into
// an html element with id #content and show an alert message
$("#content").html(data);
alert("Success")
}
});
I am trying to add users to a database using jquery ajax calls. The users get added just fine to the database, but the ajax always returns with error. I'm not sure how to retrieve the specific error either. Below is my code, form, php, and jquery.
Here is the jquery
$(document).ready(function() {
//ajax call for all forms.
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
Here is the PHP
<?php
include 'class_lib.php';
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
echo json_encode('true');
} else {
echo json_encode('false');
}
}
Here is the HTML
<div id='newUser' class='tool'>
<h3>New User</h3>
<form method='post' name='newUser' data='../php/newUser.php'>
<span>Username</span><input type='text' name='username'><br>
<span>Password</span><input type='password' name='password'>
<input type='submit' name='submit' class='button' style='visibility: hidden'>
</form>
<span class='result'> </span>
</div>
#Musa, above you mentioned
My guess is its a parsing error, try removing dataType: 'json', and see if it works
You absolutely solved the problem I was having! My ajax post request was similar to above and it just kept returning to the 'error' section. Although I checked using firebug, the status was 200(ok) and there were no errors.
removing 'dataType:json' solved this issue for me. Thanks a lot!
Turns out I had to add async: false to the $.ajax function. It wasn't getting a response back from the php.
I know this is an old question but I have just run into a weird situation like this ( jquery ajax returns success when directly executed, but returns error when attached to button, even though server response is 200 OK )
And found that having the button inside the form tags caused JQuery to always return error. Simply changing the form tags to div solved the problem.
I believe JQuery assumes the communication should be form encoded, even though you say it is application/json.
Try moving your button outside your form and see what happens...
I had the same problem and discovery there. All the time the problem is the version of my jQuery, I had use jquery version (jquery-1.10.2.js) but this version is not Ajax stablish. So, I change version for (jquery-1.8.2.js) and this miracle heppened.
Good Luck Guy!
You should specify status Code 200 for successful response.
<?php
http_response_code(200);
?>
See here: http://php.net/manual/en/function.http-response-code.php
The first solution
Try to remove dataType in your js file like that:
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
The second solution
Send a real clean JSON to AJAX like that:
PHP
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
$error = [
"title"=> 'true',
"body"=> 'some info here ... '
];
echo json_encode($error);
} else {
$error = [
"title"=> 'false',
"body"=> 'some info here ... '
];
echo json_encode($error);
}
}
JavaScript
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (data) {
let x = JSON.parse(JSON.stringify(data));
console.log(x.title);
console.log(x.body);
},
error: function() {
//code here
}
});
});
});