When i click the button to load the js file, nothing happens, i have testet the php file alone without ajax just pure php and that is working! so i am thinking that there's something wrong with this code here:
$(document).ready(function(){
$('#changePasswordNeededButton').click(function(){
$.post("http://example.com/change_password.php",
{
currentPassword : $('#currentPassword').val(),
newPassword : $('#newPassword').val(),
repeatNewPassword : $('#repeatNewPassword').val()
},
function(data){
if (data.result == 1) {
location.href = data.location;
}
}, "json" // get content which has been returned in json format
);
});
});
The HTML for this:
<div class='changePassword'>
<div id='changePasswordInner'>
<form>
<input id='currentPassword' type='password' name='currentPassword' placeholder='Nuværende adgangskode'>
<input id='newPassword' type='password' name='newPassword' placeholder='Ny adgangskode'>
<input id='repeatNewPassword' type='password' name='repeatNewPassword' placeholder='Gentag ny adgangskode'>
<input id='changePasswordNeededButton' type='button' name='changePasswordNeededButton' value='Skift adgangskode'>
</form>
<div id'errorChangePassword'></div>
</div>
</div>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="../script/change_password.js"></script>
And my php:
if (isset($_POST['currentPassword']) && isset($_POST['newPassword']) && isset($_POST['repeatNewPassword']) {
$currentPassword = $_POST['currentPassword'];
$newPassword = $_POST['newPassword'];
$repeatNewPassword = $_POST['repeatNewPassword'];
$query = "SELECT * FROM user WHERE password = '$currentPassword'";
$result = $db->query($query);
while ($row = $result->fetch_assoc()) {
$password = $row['password'];
}
if ($password == $currentPassword) {
$update = "UPDATE user SET password = '$newPassword' WHERE password = '$currentPassword'";
$db->query($update);
$result = array(
'result' => 1,
'location' => 'index.php',
);
}
// return the result
echo json_encode($result);
die();
}
I hope that someone can see the error here?
Thanks..
Take a look at jQuery's $.post documentation to start. I would actually argue using $.ajax instead because of the additional features you get with it; mainly the ability to add callbacks for success and failure.
From jQuery's docs on AJAX:
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function(jqXHR, textStatus, errorThrown) {
// Add error thrown console.logs here like console.log(textStatus, errorThrown)
alert( "error" );
})
.always(function() {
alert( "complete" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second complete" );
});
Check this line
'location' => 'index.php',
your code is not working for the extra , at the end of that line. Since your script is expecting json and receiving malformed json string.
<?php
if (isset($_POST['currentPassword']) && isset($_POST['newPassword']) && isset($_POST['repeatNewPassword'])) {
$result = array(
'result' => 1,
'location' => 'index.php'
);
echo json_encode($result);
exit();
};
?>
<form>
<input id='currentPassword' type='password' name='currentPassword' placeholder='Nuværende adgangskode'>
<input id='newPassword' type='password' name='newPassword' placeholder='Ny adgangskode'>
<input id='repeatNewPassword' type='password' name='repeatNewPassword' placeholder='Gentag ny adgangskode'>
<input id='changePasswordNeededButton' type='submit' name='changePasswordNeededButton' value='Skift adgangskode'>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#changePasswordNeededButton').click(function(){
$.post("",
{
currentPassword : $('#currentPassword').val(),
newPassword : $('#newPassword').val(),
repeatNewPassword : $('#repeatNewPassword').val()
},
function(data){
if (data.result == 1) {
location.href=data.location;
}
},"json"
);
return false;
});
});
</script>
Related
I use this code for get form data in json object. After submit I get this response:
{ user: "asdf", password: "asdfsadf" }
But the problem is i didn't know how to save this in database using php. If any one knows how to save in db please guide me. Any help is appreciated.
HTML code
<form onsubmit='return onSubmit(this)'>
<input name='user' placeholder='user'><br>
<input name='password' type='password' placeholder='password'><br>
<button type='submit'>Try</button>
</form>
Javascript code
function onSubmit( form ){
var data = $(form).serializeArray(); // <-----------
var json = {};
$.each(data, function() {
json[this.name] = this.value || '';
});
$.ajax({
type: "POST",
url: "php/tracker.php",
data: json,
dataType: "json"
});
}
here is html code
<input name='user' placeholder='user'>
<input name='password' type='password' placeholder='password'><br>
<button type='submit'>Try</button>
here is script
<script> $("button").click(function(){
var user = $("input name=user").val();
var password = $("input name=password").val();
var responce_type = "from-1";
$.post('php/tracker.php',{ user:user, password:password,responce_type:responce_type},function(resp){
resp = $.parseJSON(resp);
console.log(resp);
if(resp.status == true)
{
alert("DONE");
}
else
{
alert("error");
}
}) }) </script>
here is php code
that right in
php/tracker.php
this page
<?php
if(isset($_POST['from-1']))
{
$user = $_POST['user'];
$password = $_POST['password'];
//do some thing in php then send back request
echo json_encode(array("Data" => $_POST , "status" => true )) ;
}
else
{
echo json_encode(array("Data" => $_POST , "status" => false)) ;
}
?>
I want to append form data into a json file, here is my code however i'm not sure what I have done wrong. Every time I submit data via post I only get an error response. Where is this code going wrong?
HTML
<form class="ajax form-inline">
<div class="form-group">
<label for="exampleInputAmount">Yo, whats your first name?</label>
<div class="input-group">
<input type="text" class="form-control" id="fname" placeholder="First name">
</div>
</div>
<div class="form-group">
<label for="exampleInputAmount">&& Last name?</label>
<div class="input-group">
<input type="text" class="form-control" id="lname" placeholder="Last name">
</div>
</div>
<button type="submit" class="btn btn-primary">Submit to JSON</button>
</form>
JS/ Jquery
$('form.ajax').on('submit', function(){
var $fname = $("#fname")
var $lname = $("#lname")
var object = {
firstname: $fname.val(),
lastname: $lname.val(),
}
var params = JSON.stringify(object);
$.ajax({
type: 'POST',
data: params,
dataType: "json",
url: 'save_to_json.php',
success: function(data) {
console.log('success');
},
error: function(data) {
console.log('error');
},
complete: function() {
console.log('complete');
}
});
return false;
e.preventDefault()
});
PHP / save_to_json.php
<?php
if (!isset($_POST['params']) && !empty($_POST['params'])) {
$params = $_POST['params'];
$jsonObject = json_encode($params);
file_put_contents('my_json_data.json', $jsonObject, FILE_APPEND);
}
else {
echo "Noooooooob";
}
?>
First of all, use event.preventDefault() method to stop your form from being submitted.
Here's the reference:
event.preventDefault()
Second, there's no point using var params = JSON.stringify(object); in your code.
And finally, Remove this line dataType: "json", unless you're expecting a json object as response from server. dataType is the type of data that you're expecting back from the server.
So your jQuery script should be like this:
$(document).ready(function(){
$('form.ajax').on('submit', function(e){
e.preventDefault();
var $fname = $("#fname");
var $lname = $("#lname");
var params = {
firstname: $fname.val(),
lastname: $lname.val(),
}
$.ajax({
type: 'POST',
data: params,
url: 'save_to_json.php',
success: function(data) {
console.log('success');
},
error: function(data) {
console.log('error');
},
complete: function() {
console.log('complete');
}
});
return false;
});
});
And this is how you can process the AJAX request,
<?php
if (isset($_POST['firstname']) && isset($_POST['lastname'])) {
$params = array('firstname' => $_POST['firstname'], 'lastname' => $_POST['lastname']);
$jsonObject = json_encode($params);
file_put_contents('my_json_data.json', $jsonObject, FILE_APPEND);
}
else {
echo "Noooooooob";
}
?>
Edited:
Based on your requirement you should process the AJAX request like this:
<?php
if (isset($_POST['firstname']) && isset($_POST['lastname'])) {
$params = array('firstname' => $_POST['firstname'], 'lastname' => $_POST['lastname']);
$jsonObject = json_encode($params);
$json = file_get_contents('my_json_data.json');
if(empty($json)){
$jsonObject = json_encode(array('username' => [$jsonObject]));
file_put_contents('my_json_data.json', $jsonObject);
}else{
$json = json_decode($json, true);
$newJson = $json['username'][0] . "," . $jsonObject;
$jsonObject = json_encode(array('username' => [$newJson]));
file_put_contents('my_json_data.json', $jsonObject);
}
}
else {
echo "Noooooooob";
}
?>
I have a form in a modal window. When I submit the form through ajax I don't get the success message. My aim is to see the message created in the php file in the modal after submitting the form. Here is the code:
<p><a class='activate_modal' name='modal_window' href='#'>Sign Up</a></p>
<div id='mask' class='close_modal'></div>
<div id='modal_window' class='modal_window'>
<form name="field" method="post" id="form">
<label for="username">Username:</label><br>
<input name="username" id="username" type="text"/><span id="gif"><span>
<span id="user_error"></span><br><br>
<label for="email">Email:</label><br>
<input name="email" id="email" type="text"/><span id="gif3"></span>
<span id="email_error"></span><br><br>
<input name="submit" type="submit" value="Register" id="submit"/>
</form>
</div>
The modal.js
$('.activate_modal').click(function(){
var modal_id = $(this).attr('name');
show_modal(modal_id);
});
$('.close_modal').click(function(){
close_modal();
});
$(document).keydown(function(e){
if (e.keyCode == 27){
close_modal();
}
});
function close_modal(){
$('#mask').fadeOut(500);
$('.modal_window').fadeOut(500);
}
function show_modal(modal_id){
$('#mask').css({ 'display' : 'block', opacity : 0});
$('#mask').fadeTo(500,0.7);
$('#'+modal_id).fadeIn(500);
}
The test.js for the registration of the user
$(function() {
$('#form').submit(function() {
$.ajax({
type: "POST",
url: "test.php",
data: $("#form").serialize(),
success: function(data) {
$('#form').replaceWith(data);
}
});
});
});
And the PHP FILE
<?php
$mysqli = new mysqli('127.0.0.1', 'root', '', 'project');
$username = $_POST['username'];
$email = $_POST['email'];
$mysqli->query("INSERT INTO `project`.`registration` (`username`,`email`) VALUES ('$username','$email')");
$result = $mysqli->affected_rows;
if($result > 0) {
echo 'Welcome';
} else {
echo 'ERROR!';
}
?>
Try putting the returncode from your AJAX call into
$('#modal_window')
instead of in the form
$('#form')
BTW: Why not use the POST or GET method of jQuery? They're incredibly easy to use...
Try something like this.
First write ajax code using jquery.
<script type="text/javascript">
function submitForm()
{
var str = jQuery( "form" ).serialize();
jQuery.ajax({
type: "POST",
url: '<?php echo BaseUrl()."myurl/"; ?>',
data: str,
format: "json",
success: function(data) {
var obj = JSON.parse(data);
if( obj[0] === 'error')
{
jQuery("#error").html(obj[1]);
}else{
jQuery("#success").html(obj[1]);
setTimeout(function () {
jQuery.fancybox.close();
}, 2500);
}
}
});
}
</script>
while in php write code for error and success messages like this :
if(//condition true){
echo json_encode(array("success"," successfully Done.."));
}else{
echo json_encode(array("error","Some error.."));
}
Hopes this help you.
I got a form with some data that needs to be sent and I want to do it with ajax. I got a function that respond on an onclick event of a button. When I click the button I got some post data in firebug but it just doesn't reach my PHP script. Does anyone know what's wrong?
JS:
function newItem() {
var dataSet = $("#createItem :input").serialize();
confirm(dataSet); //Below this code box is the output of this variable to check whether it is filled or not
var request = $.ajax({
type: "POST",
url: "/earnings.php",
data: dataSet,
dataType: "json"
});
request.done(function(){
$('.create_item').children(".row").slideUp('100', 'swing');
$('.create_item').children("h2").slideUp('100', 'swing');
confirm("succes");
});
request.fail(function(jqXHR, textStatus) {
confirm( "Request failed:" + textStatus );
});
}
dataSet result when the form is completly filled in:
id=123&date=13-09-2013&amount=5&total=6%2C05&customer=HP&invoicenumber=0232159&quarter=1&description=Test
The PHP:
<?php
include('includes/dbconn.php');
function clean_up($string){
$html = htmlspecialchars($string);
$string = mysql_real_escape_string($html);
return $string;
}
if($_POST){
$date = clean_up($_POST['date']);
$amount = clean_up($_POST['amount']);
$total = clean_up($_POST['total']);
$customer = clean_up($_POST['customer']);
$invoicenumber = clean_up($_POST['invoicenumber']);
$quarter = clean_up($_POST['quarter']);
$description = clean_up($_POST['description']);
$sql = ("INSERT INTO earnings (e_date, e_amount, e_total, e_customer, e_invoicenumber, e_quarter, e_description)
VALUES ($date, '$amount', '$total', '$customer', $invoicenumber, $quarter, '$description')");
echo $sql;
if($mysqli->query($sql) === true){
echo("Successfully added");
}else{
echo "<br /> \n" . $mysqli->error;
}
}
?>
The form works fine without the ajax but with it it just doesn't work.
Your help is appreciated!
Try this snippet code bro...
<form id="F_login">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button id="btn_login" type="submit">Login</button>
</form>
$("#btn_login").click(function(){
var parm = $("#F_login").serializeArray();
$.ajax({
type: 'POST',
url: '/earnings.php',
data: parm,
success: function (data,status,xhr) {
console.info("sukses");
},
error: function (error) {
console.info("Error post : "+error);
}
});
});
Reply me if you try this...
prevent your form submitting and use ajax like this:
<form id="createItem">
<input id="foo"/>
<input id="bar"/>
<input type="submit" value="New Item"/>
</form>
$('#createItem).on("submit",function(e){
e.preventDefault;
newItem();
});
Try this
<input type="text" id="foo"/>
<input type="text" id="bar"/>
<input type="button" id="btnSubmit" value="New Item"/>
<script type="text/javascript">
$(function() {
$("#btnSubmit").click(function(){
try
{
$.post("my php page address",
{
'foo':$("#foo").val().trim(),
'bar':$("#bar").val().trim()
}, function(data){
data=data.trim();
// alert(data);
// this data is data that the server sends back in case of ajax call you
//can send any type of data whether json or json array or any other type
//of data
});
}
catch(ex)
{
alert(ex);
}
});
});
</script>
I have a form that I wish to submit which is posting to a php script to deal with the form data.
What I need to do is after hitting submit have a colorbox popup with the php results in it.
Can this be done?
This is what i've been trying:
$("#buildForm").click(function () { // #buildForm is button ID
var data = $('#test-buildForm'); // #test-buildForm is form ID
$("#buildForm").colorbox({
href:"build_action.php",
iframe:true,
innerWidth:640,
innerHeight:360,
data: data
});
return false;
});
UPDATE: This would need to be returned in an iframe as the
build_action.php has specific included css and js for those results.
This is simple, untested code but it'll give you a good jumping off point so you can elaborate however much you please:
<form action="/path/to/script.php" id="formID" method="post">
<!-- form stuff goes here -->
<input type="submit" name="do" value="Submit" />
</form>
<script type="text/javascript">
$(function() {
$("#formID").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(data) {
$.colorbox({html:data});
},
'html');
return false;
});
});
</script>
this article will help you with the problem
http://www.php4every1.com/tutorials/jquery-ajax-tutorial/
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(500);
$('#demoForm').hide(0);
$('#message').hide(0);
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#demoForm').show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
return false;
});
});
< ?php
sleep(3);
if (empty($_POST['email'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter you email.';
}
else {
$return['error'] = false;
$return['msg'] = 'You\'ve entered: ' . $_POST['email'] . '.';
}
echo json_encode($return);
You will need to see the exact way to use your colorbox jQuery plugin. But here is a basic (untested) code example that I've just written to hopefully get you on your way.
If you wish to submit a form using jQuery, assuming you have the following form and div to hold dialog data:
<form id="myForm">
<input type="text" name="num1" />
<input type="text" name="num2" />
<input type="submit" name="formSubmit" />
</form>
<div style="display: hidden" id="dialogData"></div>
You can have a PHP code (doAddition.php), which might do the addition of the two numbers
<?php
// Do the addition
$addition = $_POST['num1'] + $_POST['num2'];
$result = array("result" => $addition);
// Output as json
echo json_encode($result);
?>
You can use jQuery to detect the submitting of the code, then send the data to the PHP page and get the result back as JSON:
$('form#myForm').submit( function() {
// Form has been submitted, send data from form and get result
// Get data from form
var formData = $('form#myForm').serialize();
$.getJSON( 'doAddition.php', formData, function(resultJSON) {
// Put the result inside the dialog case
$("#dialogData").html(resultJSON.result);
// Show the dialog
$("#dialogData").dialog();
});
});
This is how I ended up getting it to work:
<div id="formwrapper">
<form method="post" action="http://wherever" target="response">
# form stuff
</form>
<iframe id="response" name="response" style="display: none;"></iframe>
</div>
<script>
function hideresponseiframe() {
$('#formwrapper #response').hide();
}
$('form').submit(
function (event) {
$('#formwrapper #response').show();
$.colorbox(
{
inline: true,
href: "#response",
open: true,
onComplete: function() {
hideresponseiframe()
},
onClosed: function() {
hideresponseiframe()
}
}
);
return true;
}
);
</script>