Iam facnigg and issue with ajax, Im working on a contact form and I have an issue with the ajax call,
The call is never succseed, even if the field are all typed correctly.
I tried few things but nothing is working
Somene can give me an advice..?
Many thanks.
$.ajax({
url: "assets/contact_form/process-contact.php",
type: "POST",
dataType: "html",
data: userData,
beforeSend: function () {
$( sb ).html('Sending...');
},
success: function (response) {
if (response == true) {
setTimeout(function () {
window.location = 'index.html';
}, 1000);
} else {
$( sb ).html('Can not send, please try latter'); //IT GOES STRIGHT TO HERE
}
}
});
}
});
here is the php code:
<?php
$userData['name'] = filter_var(trim($_POST['name']),
FILTER_SANITIZE_STRING);
$userData['email'] = filter_var(trim($_POST['email']),
FILTER_VALIDATE_EMAIL);
$userData['phone'] = filter_var(trim($_POST['phone']),
FILTER_SANITIZE_STRING);
$userData['message'] = filter_var(trim($_POST['message']),
FILTER_SANITIZE_STRING);
if( ! in_array( null, $userData ) ){
$my_email = 'roni.itzhaik#gmail.com';
$nameRegx = "/^[' a-zא-ת]+(\s[' a-zא-ת]+)*$/i";
$phoneRegx = "/^(?:0(?!(5|7))(?:2|3|4|8|9))(?:-?\d){7}$|^(0(?=5|7)(?:-?\d)
{9})$/";
if( strlen($userData['name']) > 2 && strlen($userData['name']) < 70 &&
preg_match($nameRegx, $userData['name']) ) {
if( preg_match($phoneRegx, $userData['phone']) ){
if( strlen($userData['message']) > 2 ){
$subject = 'Message from ' . $userData['name'] ;
$message_phone= $userData['message'].'Phone number:
'.$userData['phone'];
$headers = 'From: ' . $userData['email']. "\r\n";
mail($my_email, $subject, $message_phone, $headers);
// send mail
// Save data to db (DON'T FORGET TO CLEAN AGAINST SQL INJECTIONS!!!)
echo true;
}}}}
This may work.
......
if (response) {
setTimeout(function () {
window.location = 'index.html';
.....
It will be better if you could return an object instead :
echo json_encode(['success' => true]);
Then the check in your success callback will looks like :
if (response.success){
//Your logic
}
Hope this helps.
Related
My JavaScript always returns an error, even if PHP did what it should.
No matter if I write dataType: "JSON" or "JSONP" or delete it completely.
When I remove echo json_encode(... it works as it should. I see the alert for success.
But I want to make two or three success messages appear in-line in html.
Here is my JS code:
jQuery(document).ready(function($){
$('#przypinanie').click(function() {
var data_cat = $('select#cat').val();
var data_post_id = $('input#przypinanie-post-id').val() ;
var przypinanie = $('input#przypinanie').val();
$.ajax({
url: ajaxurl,
data: {
cat_id: data_cat,
post_id: data_post_id,
przypinanie_usuwanie: przypinanie,
action: "przypinanie_php"
},
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
},
});
});
My PHP code:
if ( $przypinanie == "PRZYPNIJ" ) {
$validate = $wpdb->get_var("SELECT przypieta_cat_id FROM polecane_przypinane WHERE przypiety_post_id = '$post_id'");
if ( isset($validate) ){
$msg = 'Wpis jest już przypięty do kategorii '. $validate ;
}else{
$wpdb->insert( 'polecane_przypinane',
array(
'przypiety_post_id' => $post_id,
'przypieta_cat_id' => $cat_id,
)
);
$msg = 'Wpis został przypięty do kategorii '. $validate ;
}
$responce = $msg;
}
header('Content-type: application/json');
echo json_encode($responce);
OK. Thank You for answers.
I resigned from JSON and I just did echo $responce; at the end of function.
Pleased to solwed my first question here.
The Problem is in the var a I have created
<script>
$( "#EDITsave" ).click(function() {
var a = parseInt(window.id.charAt(window.id.length-1)) //a gets parsed correctly but nothing happens in ajax until i set a number myself
console.log(a)
$.ajax({
type: "POST",
datatype: "text",
url: "edit.php",
data: {
inputID: a,
inputtxt: //issue is in 'a' here!
document.getElementById("editinputtext").value
},
});
});
</script>
PHP: // PHP CODE FOR AJAX
$inputID = $_POST['inputID'];
$inputtxt = $_POST['inputtxt'];
$sql = "UPDATE Contributions SET inputtxt = '$inputtxt' WHERE inputID = $inputID";
if ($connection->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $connection->error;
}
$connection->close();
?>
I am running a simple chat application and it's powered by a process.php file, but the chat is on chat.php.
Basically people can search for a "Topic", and it'll take them to domain.tld/chat.php?topic=topicname (topicname being whatever they searched for)
I need my process.php file to echo
<?php echo $_GET['topic']; ?>.txt
instead of chat.txt, so that each topic has a unique text file (so that all chats aren't linked)
This is my process.php file:
<?php
$function = $_POST['function'];
$log = array();
switch($function) {
case('getState'):
if(file_exists('logs/chat.txt')){
$lines = file('logs/chat.txt');
}
$log['state'] = count($lines);
break;
case('update'):
$state = $_POST['state'];
if(file_exists('logs/chat.txt')){
$lines = file('logs/chat.txt');
}
$count = count($lines);
if($state == $count){
$log['state'] = $state;
$log['text'] = false;
}
else{
$text= array();
$log['state'] = $state + count($lines) - $state;
foreach ($lines as $line_num => $line)
{
if($line_num >= $state){
$text[] = $line = str_replace("\n", "", $line);
}
}
$log['text'] = $text;
}
break;
case('send'):
$nickname = htmlentities(strip_tags($_POST['nickname']));
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$message = htmlentities(strip_tags($_POST['message']));
if(($message) != "\n"){
if(preg_match($reg_exUrl, $message, $url)) {
$message = preg_replace($reg_exUrl, ''.$url[0].'', $message);
}
$message = preg_replace('/#(\w+)/', ' #$1', $message);
fwrite(fopen('logs/chat.txt', 'a'), "<span>". $nickname . "</span>" . $message = str_replace("\n", " ", $message) . "\n");
}
break;
}
echo json_encode($log);
?>
This is my chat.js file
/*
Created by: Kenrick Beckett
Name: Chat Engine
*/
var instanse = false;
var state;
var mes;
var file;
function Chat () {
this.update = updateChat;
this.send = sendChat;
this.getState = getStateOfChat;
}
//gets the state of the chat
function getStateOfChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "process.php",
data: {
'function': 'getState',
'file': file
},
dataType: "json",
success: function(data){
state = data.state;
instanse = false;
},
});
}
}
//Updates the chat
function updateChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "process.php",
data: {
'function': 'update',
'state': state,
'file': file
},
dataType: "json",
success: function(data){
if(data.text){
for (var i = 0; i < data.text.length; i++) {
$('#chat-area').append($("<p>"+ data.text[i] +"</p>"));
}
}
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
instanse = false;
state = data.state;
},
});
}
else {
setTimeout(updateChat, 1500);
}
}
//send the message
function sendChat(message, nickname)
{
updateChat();
$.ajax({
type: "POST",
url: "process.php",
data: {
'function': 'send',
'message': message,
'nickname': nickname,
'file': file
},
dataType: "json",
success: function(data){
updateChat();
},
});
}
In theory this should create a unique topicname.txt file in /logs/ whenever somebody starts chatting in a topic that's nonexistent. I'm just having trouble adding the topicname in place of chat.txt in process.php. So far I know that it does create a chat.txt file by itself, so it should create a unique .txt file once I echo it correctly.
Also, I'm aware that a database is a better option when compared to storing messages in unique .txt files, but this is how I want to do it.
Here's an example of how I was trying to add it to my process.php a snippet from process.php)
case('getState'):
if(file_exists('logs/<?php echo $_GET['topic']; ?>.txt')){
$lines = file('logs/<?php echo $_GET['topic']; ?>.txt');
}
^ That probably isn't even the right format, as I'm new to PHP and make tons of mistakes, and it probably won't know what the GET is because it's not a part of chat.php ... it's a separate file.
Try with -
'logs/' . $filename . '.txt'
where ever you want.
Update
if (!empty($_GET['topic'])) {
$filename = $_GET['topic'];
} else {
$filename = 'something else';
}
if(file_exists('logs/' . $filename . '.txt')){ $lines = file('logs/' . $filename . '.txt') ....
It is already in php. So no need to add <?php ?> and echo. Just simply concatenate them.
you are already in php tag.. no need to add extra php tags
case('getState'):
if(file_exists("logs/".$_GET['topic'].".txt")){
$lines = file("logs/".$_GET['topic'].".txt");
}
or Try this
case('getState'):
if(isset($_GET['topic']){
$filename = "logs/".$_GET['topic'].".txt";
if(file_exists($filename)){
$lines = file($filename);
}
}
}
I have : Html + jQuery + ajax post and a PHP file to process the form values and returning a error(true or false) and a message with html markups.
My javascript code:
$(document).ready(function() {
var form = $('#form'); // contact form
var submit = $('#submit'); // submit button
var alert = $('.alert'); // alert div for show alert message
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: 'contact.php', // form action url
type: 'post', // form submit method get/post
dataType: 'json', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('Sending....'); // change submit button text
},
success: function(result) {
if(result.error){
/* On error stuff */
alert(result.html).fadeIn();
}else{
/* On success stuff */
alert(result.html).fadeIn();
}
}
});
});
});
and at last my php:
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
$result = array("error" => false, "html" => null);
$vars = array('name', 'email','telefoonnummer', 'message');
$verified = TRUE;
foreach($vars as $v) {
if(!isset($_POST[$v]) || empty($_POST[$v])) {
$verified = FALSE;
}
}
if(!$verified) {
$result["error"] = true;
$result["html"] = "<b>Error11</b>";
echo json_encode($result);
exit;
}
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$tel= filter_var($_POST['telefoonnummer'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
$to = '';
$sent = email($to, $email, $name, $tel, $message);
if ($sent) {
$result["error"] = false;
$result["html"] = "<b>Success</b>";
echo json_encode($result);
} else {
$result["error"] = true;
$result["html"] = "<b>Error</b>";
echo json_encode($result);
}
return;
}
/**
* Email send with headers
*
* #return bool | void
**/
function email($to, $name, $email, $tel, $message){
$header = array();
$header[] = "MIME-Version: 1.0";
$header[] = "From: <".$name."> <".$email.">";
/* Set message content type HTML*/
$header[] = "Content-type:text/html; charset=iso-8859-1";
$header[] = "Content-Transfer-Encoding: 7bit";
if( mail($to, $tel, $message, implode("\r\n", $header)) ) return true;
}
Ok.. now that's clear I know something goes wrong with the error returning, it does show up and then goes away again n my html so I don't know what exactly happens there..
I don't want "fixes" just so i can copy paste the code but an explanation of what happened and what goes wrong and how to solve it (at least then I learn a little)
You are using alert in two different ways... One time as an object, one time as a function. The latter is probably what causes the undesired effect. Look closely at the brackets after alert;
alert() is a function
alert. signafies it's an object
We cannot use jquery chaining method in alert function.
can anyone help me...how do i put an conditional alert dialog box in ajax that if the data in a query is successfully saved or the data already been saved.
I want to do is if the query is saved an alert box will pop-op same goes to if the data is already been saved.
script code:
<script type="text/javascript">
$(document).ready(function () {
$('#updates').click(function (e) {
e.preventDefault();
var data = {};
data.region_text = $('#t_region').val();
data.town_text = $('#t_town').val();
data.uniq_id_text = $('#t_uniq_id').val();
data.position_text = $('#t_position').val();
data.salary_grade_text = $('#t_salary_grade').val();
data.salary_text = $('#t_salary').val();
for(var $x=1;$x<=15;$x++) {
data['id'+$x+'_text'] = $('#id'+$x).val();
data['aic'+$x+'_text'] = $('#aic'+$x).val();
data['name'+$x+'_text'] = $('#name'+$x).val();
data['optA'+$x+'_text'] = $('#optA'+$x).val();
data['optB'+$x+'_text'] = $('#optB'+$x).val();
data['optC'+$x+'_text'] = $('#optC'+$x).val();
data['optD'+$x+'_text'] = $('#optD'+$x).val();
data['other_qual'+$x+'_text'] = $('#other_qual'+$x).val();
data['interview'+$x+'_text'] = $('#interview'+$x).val();
data['total'+$x+'_text'] = $('#total'+$x).val();
}
$.ajax({
type: "POST",
url: "insert.php",
data: data,
cache: false,
success: function (response) {
// We are using response to distinguish our outer data variable here from the response
}
});
});
});
</script>
insert.php code:
<?php
include('../connection.php');
date_default_timezone_set('Asia/Manila');
$region = #$_POST['region_text'];
$town = #$_POST['town_text'];
$uniq_id = #$_POST['uniq_id_text'];
$position = #$_POST['position_text'];
$salary_grade = #$_POST['salary_grade_text'];
$salary = #$_POST['salary_text'];
$dupesql = "SELECT * FROM afnup_worksheet WHERE funiq_id = '$uniq_id'";
$duperow = mysql_query($dupesql);
if(mysql_num_rows($duperow) > 0){
exit;
}else{
for($n=1;$n<=15;$n++) {
$id = #$_POST['id'.$n.'_text'];
$aic = #$_POST['aic'.$n.'_text'];
$name = #$_POST['name'.$n.'_text'];
$optA = #$_POST['optA'.$n.'_text'];
$optB = #$_POST['optB'.$n.'_text'];
$optC = #$_POST['optC'.$n.'_text'];
$optD = #$_POST['optD'.$n.'_text'];
$other_qual = #$_POST['other_qual'.$n.'_text'];
$interview = #$_POST['interview'.$n.'_text'];
$total = #$_POST['total'.$n.'_text'];
if(!empty($name)){
$query = "INSERT INTO afnup_worksheet (faic,fregion,ftown,funiq_id,fposition,fsalary_grade,fsalary,fnl_name,edu_attain,experience,seminars,eligibility,other_qual,interview,ftotal,dateinputed)
VALUES
('$aic','$region','$town','$uniq_id','$position','$salary_grade','$salary','$name','$optA','$optB','$optC','$optD','$other_qual','$interview','$total',CURRENT_TIMESTAMP)";
$resource = mysql_query($query) or die(mysql_error());
}
}
}
?>
Just return that status from PHP:
if(mysql_num_rows($duperow) > 0){
echo "1"; // Dup status
exit;
}else{
// All your else code.. echo must be the last thing inside your else block
echo "2"; // Saved status
}
Then in your ajax success callback you check it:
$.ajax({
type: "POST",
url: "insert.php",
data: data,
cache: false,
success: function (response) {
if (Number(response) == 1)
{
alert("Dup message");
}
else
{
alert("Saved message");
}
}
});
Instead of exit; in your conditinal for dupes, you could echo "duplicate". Also you should remove die() after your $resource and add if ($resource) echo "ok"; else echo "error";
Then in your success function(response) in javascript you can do if (response=="...") echo duplicate; else if ...
This is just basic explanation, but it should be enough to point you in the right direction.