php ajax form submit ..nothing happens - javascript

I have a PHP Ajax form that I'm trying to submit a Zendesk API call. Whenever I use the ajax part, in order to keep the user on the same page, it doesn't work. When I remove the <script> part, it works fine, but obviously redirects to contact.php from contact.html so I'm thinking the problem is in the Ajax part, not in the PHP part.
Here is my HTML form:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div class="box_form">
<form id="zFormer" method="POST" action="contact.php" name="former">
<p>
Your Name:<input type="text" value="James Duh" name="z_name">
</p>
<p>
Your Email Address: <input type="text" value="duh#domain.com" name="z_requester">
</p>
<p>
Subject: <input type="text" value="My Subject Here" name="z_subject">
</p>
<p>
Description: <textarea name="z_description">My Description Here</textarea>
</p>
<p>
<input type="submit" value="submit" id="submitter" name="submit">
</p>
</form>
</div>
<div class="success-message-subscribe"></div>
<div class="error-message-subscribe"></div>
<script>
jQuery(document).ready(function() {
$('.success-message-subscribe').hide();
$('.error-message-subscribe').hide();
$('.box_form form').submit(function() {
var postdata = $('.box_form form').serialize();
$.ajax({
type: 'POST',
url: 'contact.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.valid == 1) {
$('.box_form').hide();
$('.error-message-subscribe').hide();
$('.success-message-subscribe').hide();
$('.subscribe form').hide();
$('.success-message-subscribe').html(json.message);
$('.success-message-subscribe').fadeIn();
}
}
});
return false;
});
});
</script>
</body>
</html>
And the PHP Part:
You can probably ignore most of this since it works when I don't use the Ajax. Only the last few lines gives the response $array['valid'] = 1; which should then be catched by if(json.valid == 1) above.
<?php
( REMOVED API CALL CODE FROM ABOVE HERE )
if (isset($_POST['submit'])) {
foreach($_POST as $key => $value){
if(preg_match('/^z_/i',$key)){
$arr[strip_tags($key)] = strip_tags($value);
}
}
$create = json_encode(array('ticket' => array(
'subject' => $arr['z_subject'],
'comment' => array( "body"=> $arr['z_description']),
'requester' => array('name' => $arr['z_name'],
'email' => $arr['z_requester'])
)));
$return = curlWrap("/tickets.json", $create, "POST");
$array = array();
$array['valid'] = 1;
$array['message'] = 'Thank you!';
echo json_encode($array);
?>
Any ideas why this isn't working?

I expect your use of contact.php as a relative URL isn't resolving properly. Check your JavaScript console and you should see an error that shows the post failing. Change contact.php to www.your_domain.com/contact.php and it should work fine

Replace jQuery(document).ready(function() { by
$(document).ready(function() {
Secondly from Jquery documentation:
Note: Only "successful controls" are serialized to the string. No
submit button value is serialized since the form was not submitted
using a button. For a form element's value to be included in the
serialized string, the element must have a name attribute. Values from
checkboxes and radio buttons (inputs of type "radio" or "checkbox")
are included only if they are checked. Data from file select elements
is not serialized.
Therefore submit button won't serialize through jQuery.serialize() function.
A solution below:
<script>
$(document).ready(function() {
$('.success-message-subscribe').hide();
$('.error-message-subscribe').hide();
$('#submitter').click(function(e) {
e.preventDefault();
$myform = $(this).parent('form');
$btnid = $(this).attr('name');
$btnval = $(this).attr('value');
var postdata = $myform.serialize();
$.ajax({
type: 'POST',
url: 'contact.php',
data: { "btnid" : $btnid, "btnval": $btnval, "form-data": $form.serialize() },
dataType: 'json',
success: function(json) {
if(json.valid == 1) {
$('.box_form').hide();
$('.error-message-subscribe').hide();
$('.success-message-subscribe').hide();
$('.subscribe form').hide();
$('.success-message-subscribe').html(json.message);
$('.success-message-subscribe').fadeIn();
}
}
});
return false;
});
});
</script>

Related

Ajax value with redirect and echo to page

I have developed the website using jquery & PHP, I have created a page using HTML, / PHP so what I want is if I click on submit, item ajax should send value to PHP variable and then execute index.php and get that value to another page.
Please help me to resolve the issues.
So far, I have tried the following:
index.php
my Javascript Code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function() {
var val = $("#number").val();
$.ajax ({
type: "POST",
url: "ajax.php",
data: { val : val },
dataType:'text',
success: function( result ) {
// window.location.href = 'ajax.php';
// alert(result);
}
});
});
});
</script>
my HTML Code
<form name="numbers" id="numbers">
<input type="text" name="number" id="number" >
<button type="button" id="btn">Submit</button>
</form>
ajax.php
<?php
session_start();
$_SESSION['val'] = $_POST['val'];
print_r($_SESSION);
?>
You can store the value in session and redirect the user to other page and get data from session at other pages.
<?php
session_start();
$_SESSION['data'] = $_GET['val'];
?>
Your HTML code must be like that
<form name="numbers" id="numbers">
<input type="text" name="number" id="number">
<button type="button" id="btn">Submit</button>
</form>
For redirect to other page you can use like
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function() {
var val = "Hi";
$.ajax ({
url: "ajax.php",
data: { val : val },
success: function( result ) {
window.location.href = 'url';
}
});
});
});
</script>
in this if you click button its refresh the page because you using input type="submit" on button , so just change it to input type="button"
<input type="button" id="btn" value="submit">
and if you want to keep input type="submit" as you already did then just add prevent default to jquery
$(document).ready(function(){
$("#btn").click(function(event) {
event.preventDefault();
var val = "Hi";
$.ajax ({
url: "ajax.php",
data: { val : val },
success: function( result ) {
}
});
});
});
you can use session
in ajax.php you have to add:
<?php
session_start();
echo $_GET['val'];
$_SESSION['val'] = $_GET['val'];
?>
and use variable $_SESSION['val'] to any page

ajax submit form why it cannot echo $_POST

I'm test using ajax submit form (submit to myself page "new1.php")
The thing that I want is, after click submit button, it will echo firstname and lastname. But I don't know why I do not see the firstname and lastname after submit.
here is new1.php page
<?php
echo $_POST['firstname']."<br>";
echo $_POST['lastname']."<br>";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form id="myform" action="new1.php" method="post">
Firstname : <input type="text" name="firstname"> <br>
Lastname : <input type="text" name="lastname"> <br>
<input type="submit" value="Submit">
</form>
<script>
// this is the id of the form
$("#myform").submit(function(e) {
$.ajax({
type: "POST",
url: 'new1.php',
data: $("#myform").serialize(), // serializes the form's elements.
success: function(data)
{
alert('yeah'); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
</body>
</html>
In your case the best option to retrieve values as JSON format using json_encode in your PHP code and then accessing these values through data object.
Example:
PHP code:
if($_POST)
{
$result['firstname'] = $_POST['firstname'];
$result['lastname'] = $_POST['lastname'];
echo json_encode($result);
die(); // Use die here to stop processing the code further
}
JS code:
$("#myform").submit(function (e) {
$.ajax({
type : "POST",
url : 'new1.php',
dataType : 'json', // Notice json here
data : $("#myform").serialize(), // serializes the form's elements.
success : function (data) {
alert('yeah'); // show response from the php script.
// make changed here
$('input[name="firstname"]').text(data.firstname);
$('input[name="lastname"]').text(data.lastname);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
When you use form as a serialize you have to retrieve like this.
Edit your ajax like this :
data: { formData: $("#myform").serialize()},
Then you can retrieve like this in your controller:
parse_str($_POST['formData'], $var);
echo "<pre>";
print_r($var);
exit;
Make some changes in javascript here:
success: function(data)
{
$('#response').html(data); // show response from the php script.
}
And in html code make a div with id response
<div id="response"></div>
Change from
alert('yeah'); // show response from the php script.
to
alert(data); // show response from the php script.
the value firstname, lastname will not display because you called the new1.php via ajax and the data (firstname, lastname and the page code) is returned to java script variable (data) you need to inject the data to your document
Try this
$.ajax({
type: "POST",
url: 'new1.php',
data: $("#myform").serialize(), // serializes the form's elements.
success: function(data) {
document.documentElement.innerHTML = data;
}
});

PHP validation for Javascript

I have a new problem. My whole website is written in PHP as well as all validations. Is there a way to do validations in php and then execute javascript like the example bellow?
if (#$_POST['submit']) {
if ($txt == "") {
$err = "No comment";
}
else {
echo "<script type='text/javascript'>
function myFunction() {
var txt' = '$txt';
var dataString = 'txt=' + txt;
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: dataString,
cache: false,
success: function(php) {
alert(php);
}
});
}
</script>";
}
}
<div id="text">
<form action="" method='POST'>
<textarea maxlength="2000"></textarea>
<input type='button' onclick="myFunction()" name='submit' value='post' />
</form>
</div>
This doesn't work. So I'm wondering how should I do it?
I guess forms don't work with javascript, but how do I do it without a form?
You don't need to use php at all. You can post your textarea data like in the below example.
HTML
<div id="text">
<textarea id="txtArea" maxlength="2000"></textarea>
<button id="btnSubmit" name='submit'>post</button>
</div>
Javascript/jQuery
$("#btnSubmit").on('click',function(e) {
e.preventDefault();
var txtValue = $("#txtArea").val();
if(txtValue.length==0) {
alert("You have not entered any comments");
} else {
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: {txt:txtValue},
cache: false
})
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
});
}
});
The solutions is:
1. add function for submit event.
2. call ajax with form fields values as data.
3. do vildation inside php called with ajax request and return status code (valid/not valid)
4. analyse code in js and output error/success message.
First of all: Your code has a couple of errors.
You are asking if $txt == "" whilst $txt was not visibly set.
Your text area has no name
Your if doesn't ask if empty($_POST["submit"])
Second of all: You mentioned that you want the code to be executed on submit of the form. Therefore you can simple do this:
<form onsubmit="formSubmit();">
...
</form>
<script>
function formSubmit()
{
if(...)
{
return true; // Valid inputs, submit.
}
return false; // Invalid inputs, don't submit.
}
</script>
The return false is important because if it would miss, the form would be submitted as usual.

jQuery ajax form doesn't work

I tried many ways to create a simple jquery ajax form but don't know why it is not submitting and/or returning the notification.
Here is my code:
Javascript
...
<script type="text/javascript" src="assets/js/jquery1.11/jquery-1.11.0.min.js"></script>
...
$('#form_signup').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
HTML
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<a type="submit">Sign up!</a>
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
PHP
<?php
$our_mail = "our#email.com";
$subject = "Wohoo! A new signup!";
$email = $_POST['inputEmail1'];
$return = array();
$return['msg'] = 'Thank you!';
$return['error'] = false;
if(preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)){
$message = "Yesss!! We receive a new signup!
E-mail: $email
";
mail($our_mail, $subject, $message);
}
else {
$return['error'] = true;
$return['msg'] .= 'Something is wrong... snifff...';
}
return json_encode($return);
Solved:
There were three problems. And different users solve each of these problems.
In PHP, you must "echo" the return array instead of "return"
At first, you should use a submit button instead of an anchor in the form
In the input, you must set both "id" and "name"
If any of these users want, you can edit or add a new answer with these details, and the points are yours.
You need to do 3 things.
First, wrap your jQuery codes inside $(document).ready() function,
<script type="text/javascript">
$(document).ready(function()
{
$('#form_signup').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
});
</script>
Second, Add a submit button to your form. Also you are missing the name attribute for the email input field. That causes the error in the php file.
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<input type="submit" name="signup" value="Sign Up!"/>
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
Third, echo the results since you are using AJAX to submit the form. return will not have any effects.
<?php
$our_mail = "our#email.com";
$subject = "Wohoo! A new signup!";
$email = $_POST['inputEmail1'];
$return = array();
$return['msg'] = 'Thank you!';
$return['error'] = false;
if(preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)){
$message = "Yesss!! We receive a new signup!
E-mail: $email
";
mail($our_mail, $subject, $message);
}
else {
$return['error'] = true;
$return['msg'] .= 'Something is wrong... snifff...';
}
echo json_encode($return);exit;
I checked and it's working fine.
Hope this helps :)
The problem is in your form.
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<input type="submit" name="submit" value="Submit">
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
The php code needs to echo instead of return.
just like this:
echo json_encode($return);
Also, your form needs a submit button - type="submit" on an <a> tag doesn't trigger the browser's functionality for handling <form>s
Finally, you need to ensure that your special submit handler is loaded at just the right time -- which, if it is included at the bottom of the page, right before the footer, it should be just fine. However, you can ensure this by wrapping it in
$(document).ready(function(){
//[...]
});
doesn't your a type="submit" need to be an input instead? or a button
I am trying to call webmethod in a ajax using jquery in asp.net, but sometimes it works well and sometimes it doesn't.
Here is my ajax code :
$.ajax({
type: "POST",
url: "frmTest.aspx/fncSave",
data: "{}"
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "false",
cache: "false", //True or False
success: function (response)
result = response.d;
if (result != "") {
alert(response);
}
},
Error: function (x, e) {
alert("err");
return false;
}
});
Here My Server Side Code :
<WebMethod()>
Public Shared Function fncSave() As String
Dim sResult As Int16
Try
Dim obj As New ClsCommon()
sResult = obj.Save()
Catch ex As Exception
ex.Message.ToString()
End Try
Return sResult
End Function
$(this) in the "ajax" function is not the form.
So just try:
$('#form_signup').submit(function(event) {
event.preventDefault();
var $this = $(this);
$.ajax({
type: 'POST',
url: 'signup.php',
data: $this.serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
I admit i didn't check the rest of the code, im pretty sure thats the problem.
Of course if the problem still goes, just "f12" and check console and network for server request and headers, make sure all the params are there.
Hope that helped

Partially working AJAX that writes form input to text file

This script is supposed to take the users input in an HTML form and use AJAX to write that input to a text file via PHP. When I run this code, however, I get two alerts, first 'error' then 'complete' (form the .fail and .always functions in AJAX) which leads me to believe that the problem is in the information being sent back by PHP.
<?php
$fileHandle = fopen('emailList.txt', 'a') OR die ("Can't open file\n");
$email=$_POST['email'];
var_dump($email);
$result = fwrite ($fileHandle, "$email; \n");
fclose($fileHandle);
echo (!$result)? "error" : $result;
die;
?>
Where 'email' is the name of the text input of the form.
But in case the PHP is correct, I'll put the HTML and javascript here as well:
<form>
<input type="text" name="email" value="" class="emailSubmitSidebar" placeholder=" Your Email">
<input type="submit" value="Add" class="submitButton" id="subscribeButton">
</form>
<script>
$(document).ready(function() {
var input = $('.emailSubmitSidebar').val();
var subscribeButton = $('#subscribeButton');
subscribeButton.click(function() {
$.ajax({
url: 'emailform.php',
type: 'POST',
dataType: 'text',
data: {email: $("input[name=email]").val()},
})
.done(function(data) {
alert("success!")
})
.fail(function() {
alert("error");
})
.always(function() {
alert("complete");
})
});
});
</script>

Categories

Resources