Submit a Form Using Jquery Ajax - javascript

Fiddle And Code:
$("form.signupform").submit(function(e) {
var data = $(this).serialize();
var url = $(this).attr("action");
var form = $(this); // Add this line
$.post(url, data, function(data) {
try {
data = JSON.parse(data);
$(.result).html(data.result + " Watchlist");
} catch (e) {
console.log("json encoding failed");
return false;
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="result"></p>
<form class="signupform" method="post" action="admin/signupinsert.php" onsubmit="this.onsubmit=function(){return false;}">
<input type="text" name="firstname" />
<input type="submit" value="Sign Up"/>
</form>
admin/signupinsert.php code:
// Insert into DB code in PHP
$response = new \stdClass();
$response->result = "".$result."";
die(json_encode($response));
I am trying to submit this form using My Jquery Ajax Code. And the signupinsert.php file will return a value in $result variable. I am trying to print it inside <p class="result"></p>
But, the code re-directs users to signupinsert.php page.
What's wrong?

you must prevent the default action of submitting the form
$("form.signupform").submit(function(e) {
e.preventDefault(); // <-- add this
var data = $(this).serialize();
var url = $(this).attr("action");
also, in your php file return proper JSON and avoid parsing the response in javascript with JSON.parse(data);
the output in your php file should look like this
$response = new \stdClass();
$response->result = $result;
header('Content-Type: application/json');
print json_encode($response);
and in your success handler just process the data parameter as a normal json object
$.post(url, data, function(data) {
$(.result).html(data.result + " Watchlist");
}
Also, just a curiosity, what is this supposed to do?
$response->result = "".$result."";
Update:
I just realized why you had most of the issues:
$('.result').html(data.result + " Watchlist");
^ ^
see the missing quotes

you are redirecting because of action:
action="admin/signupinsert.php"
var url = $(this).attr("action");
got me?

Related

PHP Google reCAPTCHA with AJAX not working

I have form in 100.php with ajax call to 200.php.
<html>
<head>
<!-- include reCAPTCHA API JavaScript library given by Google -->
<script src='https://www.google.com/recaptcha/api.js'></script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myaddress = $("#address").val();
var yourData ='name='+myname+'&address='+myaddress; // php is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '200.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
//alert('Submitted');
}else{
return false;
}
}
});
});
});
</script>
</head>
<body>
<form method="post" id="testform">
Name: <input type="text" name="name" value="" id="name"/> <br />
Address: <input type="text" name="address" value="" id="address"/>
<!--
place for the reCAPTCHA widget div with your site key
data-theme="dark" attribute - gives dark version
-->
<div class="g-recaptcha" data-sitekey="6LeJ8h8TAAAAAMS9nQX89XccpsC-SDeSycipiaHN"></div>
<input type="submit" name="ok" value="Send" id="btn"/>
</form>
<div id='result'></div>
</body>
200.php does validate captcha and diaplay name and adddress user entered. But my problem is that when I entered name and address, click on captcha. Captha is also validated and shows as in my screenshot. but name and address is not shown on the page. You can also check yourself here: http://raveen.comlu.com/100.php
I am new to Ajax call by PHP. I googled and I can troubleshoot by firebug. Can you say what I am doing wrong here? and steps to troubleshoot by firebug like to check if my ajax call is done, etc? thanks for your help.
Note: when I put all these code in one page without using ajax call. it works fine!!!!! I want this happens without page reload....
output
200.php
<?php
require_once('recaptchalib.php');
if( isset($_POST['ok']) ){
if( isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']) ){
$secret = "6LeJ8h8TAAAAAB3IFQVQEaoApFe6lvq4Wxlktvn1"; //your secret key
$response = null; //empty response
$reCaptcha = new ReCaptcha($secret); //check secret key is present
$response = $reCaptcha->verifyResponse( $_SERVER['REMOTE_ADDR'], $_POST['g-recaptcha-response'] );
//$response variable will report back with "success"
if( $response!=null && $response->success ){
echo "<h1>Hi ". $_POST['name']. " from ". $_POST['address']. ", thanks for submitting the form!</h1>";
}
}
else{
echo "<h1>Please click on the reCAPTCHA box.</h1>";
}
}
?>
There are few errors in your code, such as:
Look at the following two statements,
if( isset($_POST['ok']) ){...
and
var yourData ='name='+myname+'&address='+myaddress;
You're not sending any variable named ok to 200.php page, so the control won't even enter the if block.
You're validating reCaptcha in the wrong way. From the documentation:
If your website performs server side validation using an AJAX request, you should only verify the user’s reCAPTCHA response token (g-recaptcha-response) once. If a verify attempt has been made with a particular token, it cannot be used again. You will need to call grecaptcha.reset() to ask the end user to verify with reCAPTCHA again.
So you have to use grecaptcha.getResponse() to get the user's response.
And as a sidenote use grecaptcha.reset() to ask the end user to verify with reCAPTCHA again.
Your jQuery/AJAX script should be like this:
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var recaptchaResponse = grecaptcha.getResponse();
var myname = $("#name").val();
var myaddress = $("#address").val();
var yourData = {name: myname, address: myaddress, recaptchaResponse: recaptchaResponse};
$.ajax({
type: 'POST',
data: yourData,
dataType: 'html',
url: '200.php',
success: function(data) {
// reset form
$('#testform')[0].reset();
// display data
$('#result').html(data);
// reset the reCaptcha
grecaptcha.reset();
},
error: function(jqXHR, textStatus, errorThrown){
// error
}
});
});
});
</script>
And on 200.php page, process your AJAX data like this:
<?php
//your site secret key
$secret = '6LeJ8h8TAAAAAB3IFQVQEaoApFe6lvq4Wxlktvn1';
if(isset($_POST['recaptchaResponse']) && !empty($_POST['recaptchaResponse'])){
//get verified response data
$param = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['recaptchaResponse'];
$verifyResponse = file_get_contents($param);
$responseData = json_decode($verifyResponse);
if($responseData->success){
// success
echo "<h1>Hi ". $_POST['name']. " from ". $_POST['address']. ", thanks for submitting the form!</h1>";
}else{
// failure
echo "<h1>You have incorrect captcha. Please try again.</h1>";
}
}else{
echo "<h1>Please click on the reCAPTCHA box.</h1>";
}
?>

AJAX submit and 500 server error

I get the 500 server error when trying to run my AJAX. I am very new to AJAX. Every thing works in the code if I run no AJAX in the script, for example just running:
$("#book-appointment-form").submit();
Therefore, it appears that all the database functions are fine. However, I need AJAX to run my code in a Wordpress page.
I do not see any notes in the error logs. The console log shows that the url is pointing to the correct location. What may I be missing?
The console log shows data within the hidden input showing up in confirmedData:
0: Object
name: "csrfToken"
value: "0f4343dfd0e71a8fa515d08f340f7bc9"
__proto__: Object
1: Object
name: "post_data"
value: "{"customer":{"last_name":"Test","first_name":"Joe","email":"email4me#verizon.net","phone_number":"9093334444","address":"","city":"","zip_code":"","id_cellcarrier":"2","wp_id":"1"},"appointment":{"start_datetime":"2015-12-25 11:00:00","end_datetime":"2015-12-25 11:50:00","notes":"","is_unavailable":false,"id_users_provider":"85","id_services":"13"},"manage_mode":false}"
__proto__: Object
length: 2
__proto__: Array[0]
VIEW:
<html>
<form id="book-appointment-form" style="display:inline-block" method="post">
<button id="book-appointment-submit" type="button">Confirm</button>
<input type="hidden" name="csrfToken" />
<input type="hidden" name="post_data" />
</form>
</html>
JS
<script>
$("#book-appointment-form").submit(function(event){
var confirmedData = $(this).serializeArray();
var dataUrl = GlobalVariables.baseUrl + '/index.php/appointments/ajax_confirm_appointment';
$.post(dataUrl, confirmedData, function(response) {
////////////////////////////////////////////////////////////
console.log('Customer Confirmed Post Response:', response);
////////////////////////////////////////////////////////////
}, 'json');
event.preventDefault();
});
$("#book-appointment-form").submit();
</script>
PHP CONTROLLER
<?php
public function ajax_confirm_appointment() {
if($_POST["post_data"]){
try {
$post_data = json_decode($_POST['post_data'], true);
$appointment = $post_data['appointment'];
$customer = $post_data['customer'];
...some database stuff here ....
} catch(Exception $exc) {
$view['exceptions'][] = $exc;
}
$this->load->view('appointments/book_success', $view);
$form_data = TRUE;
break;
} else {
$form_data = FALSE;
}
echo json_encode($form_data);
}
?>
I have tried replacing serializeArray() with serialize(). I have also tried serializeArray() converted with $.param(confirmedData)-- same results really and still it does not appear to reach the server. 500 error persists. I think serialize() may be the more appropriate one however.
I do not think it is related to Ajax. There may be problem in script that you are calling through ajax.
Try to check without ajax dataUrl
Please also check link .
http://pcsupport.about.com/od/findbyerrormessage/a/500servererror.htm
This worked:
My JS
<script>
$("#book-appointment-form").submit(function(event){
var postData = {
csrfToken: $('input[name=csrfToken]').val(),
post_data: jQuery.parseJSON($('input[name="post_data"]').val())
};
var postUrl = GlobalVariables.baseUrl + '/index.php/appointments/ajax_confirm_appointment';
$.post(postUrl, postData, function(response) {
////////////////////////////////////////////////////////////
console.log('Customer Confirmed Post Response:', response);
////////////////////////////////////////////////////////////
if (!GeneralFunctions.handleAjaxExceptions(response)) return;
}, 'json');
});
</script>
My CONTROLLER
<?php
public function ajax_confirm_appointment() {
try {
$post_data = $_POST['post_data'];
$appointment = $post_data['appointment'];
$customer = $post_data['customer'];
...some database stuff here ....
}
echo json_encode($yn_response);
}
?>
No more 500 server error.

how to html form post - file uploading and reading json response from php server

i am trying file uploading to php my server.file and data uploading through multi part /form-data ,the file and data received on php server but in my php server return json response .please help me how to read json response in my webpage and if its success(code=0) means it redirect another page .the php sever is common for both android and web pages .json response look like {"code":0,"message":"success"}
<div style="height:0px;overflow:hidden">
<form id="myForm" action="http://192.168.2.4/digiid/api/addid"
method="post" enctype="multipart/form-data" runat="server">
<input type="file" name="file" id="file" onchange="showMyImage(this)" />
<input type="hidden" name="userid" value="<?php echo $_SESSION["userid"]?>">
<input type="hidden" id="inputfilename" name="filename" value="here">
</form>
</div>
<a class="button1" id="browseButton" onclick="" style="width:12%;height: 30px; text-decoration:none;"><font color="white" size="5px">Select ID</font></a>
<br/>
<div>
<img src='images/capture_picture_size.png' id='imgscreen' width='200' height='200'>
<br/>
<p id="filename" style="color: #ffffff; font-size: 20px" >
Title of the ID<br/></p>
<a class="button1"onclick="myFunction()" style= " width:12%;height: 30px; text-decoration:none;"><font color="white" size="5px">Save ID</font></a></form>
</div>
<script>
function myFunction() {
document.getElementById("myForm").submit();
}
</script>
<script>
browseButton.onclick=function chooseFile() {
document.getElementById("file").click();
};
function showMyImage(fileInput) {
var files = fileInput.files;
var file = files[0];
var imageType = /image.*/;
var img=document.getElementById("imgscreen");
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
//x=e.target.result
img.src = e.target.result;
var extfilename=file.name;
document.getElementById("filename").innerHTML=extfilename.slice(0,-5) ;
document.getElementById("inputfilename").value=extfilename.slice(0,-5);
};
})(img);
reader.readAsDataURL(file);
}</script>
I think it should work for you. Using AJAX, as I do
//Your php code
$arrToJSON = array(
"dataPHPtoJs"=>"yourData",
"asYouWant"=>"<div class=\".class1\">soemting</div>"
);
return json_encode(array($arrToJSON));
//Your javaScript code
$(document).on("event", "#idElement", function(){
//Data you want to send to php evaluate
var dt={
ObjEvn:"btn_Login",
dataJsToPHP: $("#txt_EmailLogin").val()
};
//Ajax
var request =$.ajax({//http://api.jquery.com/jQuery.ajax/
url: "yourServer.php",
type: "POST",
data: dt,
dataType: "json"
});
//Ajax Done catch JSON from PHP
request.done(function(dataset){
for (var index in dataset){
dataPHPtoJsJS=dataset[index].dataPHPtoJs;
asManyasYouWantJS=dataset[index].asYouWant;
}
//JavaScript conditions. Here you can control the behaivior of your html object, based on your PHP response
if(dataPHPtoJsJS){
$( "#idYourHtmlElement" ).removeClass( "class1" )
$( "#idYourHtmlElement" ).addClass( "class2" )
}
});
//Ajax Fail
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
You should probably use an AJAX call. Here's a solution using jQuery:
<script type="text/javascript">
$(document).ready(function(){
$("#browseButton").click(function(){
var url = "";
var formdata = $("#myForm").serialize();
$.ajax({
url: url,
type: 'POST',
data: formdata,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
success: function(response){
if(response.status == "success"){
// Success
} else {
// Failure
}
},
error: function(response){
// Error
}
});
});
});
</script>
In order to redirect the user, you can use: window.location.href = " ... your_url ...";
Here's an explanation on how to use jQuery AJAX and multi-part data:
Sending multipart/formdata with jQuery.ajax
try json_decode.
$data = ({"code":0, "message":"success"});
$array = json_decode($data, true);
by passing 2nd parameter to true you will get response in array instead of object.
the array will be then populated as follow:
array (size=2)
'code' => int 0
'message' => string 'success' (length=7)
Your JSON response would be a kind of associative array in php.
Encode your array data into JSON using "json_encode" and return values as you want .
$arr = array('status' => $status, 'status2' => $status2, );
echo json_encode($arr);
NOTE: If you are using ajax to call php file then do not use any php echo/print in that file and not even HTML. ECHO only "json_encode();" Nothing else.
To sum it up:
Upload your data to server using AJAX with native JS (>=IE10) or jQuery
Catch (xhr.responseText in native JS) and parse the response
Redirect with window.location.href="success.php"

Pass view as data to js in symfony

I am tryng to implement a search function in my index page using java script. I hav got a form to enter the name and when apply serach, the index page will get updated and load the new index page with the search results
Here is the form in my index page
<div id="content">
<form id="myForm" action="{{path('index_search')}}" method="POST" >
Write your name here:
<input type="text" name="name" id="name_id" value="" /><br />
<input type="submit" value="Send" />
</form>
</div>
<div id="output">#current index</div>
Here is the action exexcuted
public function searchAction()
{
$request = $this->get('request');
$name=$request->request->get('formName');
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('SystemVmsBundle:VisitorsDetails')->findOneByfirstname($name);
$view = $this->render('SystemVmsBundle:VisitorsDetails:index.html.twig',array(
'entities' => $entities,
));
$return=array("responseCode"=>200, "view"=>$view);
$return=json_encode($return);//jscon encode the array
return new Response($return,200,array('Content-Type'=>'application/json'));
}
Here is the js
$(document).ready(function() {
//listen for the form beeing submitted
$("#myForm").submit(function(){
//get the url for the form
var url=$("#myForm").attr("action");
$.post(url,{
formName:$("#name_id").val(),
other:"attributes"
},function(data){
//the response is in the data variable
if(data.responseCode==200 ){
$('#output').html(data.view);
$('#output').css("color","red");
}
else{
alert("An unexpeded error occured.");
}
});
return false;
});
});
However my js is working,but can not pass data as view to the js.How to pass the view 'index.html.twig' to the js?
When inspects with firebug,i got like
{"responseCode":200,"view":{"headers":{}}}
Any ideas?Thanks in advance!
Try to specify the dataType on your $.post function, like this:
$.post(url, {formName: $("#name_id").val(), other: "attributes"},
function(data) {
if(data.responseCode == 200){
$('#output')
.html(data.view)
.css("color","red");
} else {
alert("An unexpeded error occured.");
}
}, 'json');
But If you only need the html, not other data inside the json, you should change the logic, render a normal template and use dataType 'html'. goes like this:
// ...Controller.php
$view = $this->render('SystemVmsBundle:VisitorsDetails:index.html.twig',array(
'entities' => $entities,
));
return new Response($view);
// index.html.twig
$.ajax({
url: url,
dataType: 'html',
type: 'POST',
data: {formName: $("#name_id").val(), other:"attributes"},
success: function (data) {
$('#output').html(data).css("color","red");
}
});

How to submit an AJAX form with a <a href> link?

I have the following form:
<form id='confirm_reset' action='login/forgotPassword_action' method='post'>
<input type='hidden' name='user_email' value='user_email'>
Submit
</form>
<div id="alert_box_register"></div>
I am trying to submit this with Ajax to return JSON in the alert box:
$("#confirm_reset").on("submit", function(event) {
//disable default click operation
event.preventDefault();
var action_url = $(this).attr("action");
alert_box_register("Resetting password...");
console.log(action_url);
var postData = $(this).serializeArray();
console.log(postData);
$.post(action_url, postData, function(data) {
console.log(data);
var obj = $.parseJSON(data);
alert_box_register(obj.message);
});
});
This script returns no result (as if the link did not function). Where am I going wrong?
Not sure if this code is still a problem for you or not...?
A quick note about out your progress messages ("Resetting password..."): this code will probably run so fast that this message will just barely flash on the screen for the user. I don't know how your stuff is set up but you may never see this on the screen.
<!-- The following line was missing .php from the action -->
<!--form id='confirm_reset' action='login/forgotPassword_action' method='post'-->
<form id='confirm_reset' action='login/forgotPassword_action.php' method='post'>
<input name="txtbox" type="text" value="hello world"/>
<input type='hidden' name='user_email' value='user_email'>
<!-- submit_confirm_reset() is a function I made in the javascript tages-->
Submit
</form>
<div id="alert_box_register"></div>
<script>
function submit_confirm_reset() {
$("#confirm_reset").submit();
}
$("#confirm_reset").on("submit", function(event)
{
console.log('("#confirm_reset").on("submit", function(event)');
//disable default click operation
event.preventDefault();
var action_url = $(this).attr("action");
// you were using alert_box_register like it was a function
// but it doesn't exist in the code you posted in your question
// but a DOM element has this name so I assume you meant that
$("#alert_box_register").html("Resetting password...");
console.log(action_url);
var postData = $(this).serializeArray();
console.log(postData);
$.post(action_url, postData, function(data) {
console.log(data);
// if this response is already json, you don't need to parse it
var obj = $.parseJSON(data);
$("#alert_box_register").html(obj.message);
});
});
</script>

Categories