I have included a contact form in my page. In the same page I have a script that gets prices depending on the value of a dropdown. Now when I try to submit the contact message I have a conflict with the script for prices. Basically it tries to run it and I have no clue why. Also the contact form when submitted never works...I just get a new page to open with URL..?message=blablabla
Any idea what is going wrong?
I am working on Laravel 4.2 and so the route you see redirects to my php function.
Here is the JSfiddle and here is the php code:
public function postSendMessage() {
echo "<span class=\"alert alert-success\" >Your message has been received. Thanks!</span><br><br>";
}
Cancel the click so the form will not submit
$("button#send").click( function(evt){
evt.preventDefault();
New error, form has an id of contact, not a class
data: $('form.contact').serialize(),
needs to be
data: $('form#contact').serialize(),
This is what I do for the same situation
//For your drpbox use this code
$(document).on("change", "#yorDropBoxId", function(){
dropBoxValue=$("#yorDropBoxId").val();
var request = $.ajax({//http://api.jquery.com/jQuery.ajax/
url: "samePagePHPcript.php",
type: "POST",
data: {
ObjEvn:"dropBoxEvent",
dropBoxValue: dropBoxValue //You will use $myVar=$_POST["dropBoxValue"] to retrieve the information from javascript
},
dataType: "json"
});
request.done(function(dataset){
//If you want to retrieve information from PHP sent by JSON.
for (var index in dataset){
JsResponse=dataset[index].phpResponse;
}
if(JsResponse test someting){
"do dometing"
control the beheaivor of your HTML elements
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
//To submit your form use this code. You must use Prevent default if you are using a button or using a <a> link tag to trigger the evenrmrnt
$(document).on("click", "#btn_sendForm", function(e){
e.preventDefault();
var dt={
ObjEvn:"FormEvent",
input1:$("#txt_input1").val(),
input2: $("#txt_input2").val(),
input3: $("#txt_input3").val()
};
var request = $.ajax({//http://api.jquery.com/jQuery.ajax/
url: "samePagePHPcript.php",
type: "POST",
data: dt,
dataType: "json"
});
request.done(function(dataset){
//If you want to retrieve information from PHP send by JSON.
for (var index in dataset){
JsResponse=dataset[index].phpResponse;
}
if(JsResponse test someting){
"do dometing"
control the beheaivor of your HTML elements
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
//In the samePagePHPcript.php you can do this:You will return your information from PHP using json like this
$event = $_POST["ObjEvn"];
if(event==="FormEvent"){//Event to insert in your form
$arrToJSON = array(
"phpResponse"=>"data you want to send to javascript",
"asYouWant"=>"<div class=\".class1\">more data</div>"
);
echo json_encode(array($arrToJSON));
}
elseif(event==="dropBoxEvent"){//Event to your dropbox - if you want
$arrToJSON = array(
"phpResponse"=>"data you want to send to javascript",
"asYouWant"=>"<div class=\".class1\">more data</div>"
);
echo json_encode(array($arrToJSON));
}
Related
I'm trying to create error validation handling for my custom form. What I want to do is get the error messages in a div instead of the browser alert box but I'm new to all of this and have no idea how to do it. I tried to do some research but found nothing useful for my case.
Basically my form works and shows error or success messages correctly, but I don't want to display them in the alert box, but in a dedicated div. Thanks for any answers, I appreciate any help.
So here's what I have:
My section which contains all the various messages error
<div class="error-message-wrapper">
<!-- Here are all my error messages that are printed with the wc_print_notices(); function -->
</div>
My Script
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
url: "wp-admin/admin-ajax.php",
success : function( response ) {
alert( response );
}
});
});
});
My function
function save_account_details() {
if (trim($_POST['account_first_name']) == '') {
$msg = wc_print_notices();
$response = $msg;
} else {
$response = "Settings Saved!";
}
// Don't forget to exit at the end of processing
echo json_encode($response);
exit();
}
If u wanna show in exist class then choose element by document.querySelector(".className").innerHtml = response.textFromResponse or u can do like below
Query(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
url: "wp-admin/admin-ajax.php",
success : function( response ) {
alert( response );
const uiDivElement = document.createElement("DIV");
uiDivElement.innerHTML = response.textFromResponse
document.appendChild(uiDivElement)
}
});
});
});
I have a bootstrap 3 modal that is launched via a button on the parent and then populate the modal-body with form data coming from my MySQL database. Among the populated data is small gallery showing attachment pictures and one unique delete-button underneath each picture to launch a query to delete the attachment from a specific attachment folder.
Gallery and delete button ON THE MODAL:
<div class=\"row\">
<div class=\"box box-widget widget-user-2\">
<div class=\"widget-user-header bg-gray\">
<div class=\"lightBoxGallery\">";
$files = scandir($log_folder);
foreach ($files as $attachment) {
if (in_array($attachment, array(".",".."))) continue;
echo "
<span class=\"input\"><button type=\"button\" id=\"DeleteAttachmentButton\" name=\"DeleteAttachmentButton\" class=\"form-btn btn-danger btn-xs\" data-filename=\"".$attachment."\"><i class=\"fa fa-trash\"></i></button><img src=\"".$log_folder.$attachment."\" style=\"height:100px; width:150px;\"></span> ";
}
echo "
</div>
<!-- ./lightbox gallery -->
The problem now is that nothing happens when I press the delete button for the specific attachment. I believe this to be caused by the JavaScript code below which is located ON THE PARENT right after the modal.
// DELETE ATTACHMENT - DELETE BUTTON ON EDIT MODAL
$("#DeleteAttachmentButton").click(function(e){
var modal = $(this);
if (confirm('Are you sure you want to delete this attachment?')) {
var attachment_name = $(e.relatedTarget).data('filename'); // Extract info from data-* attribute
$.ajax({
url: "../../plugins/MySQL/ajax_action.php",
type: "POST",
async: true,
data: { action:"delete_attachment",Holidex:$("#dataLogID").val(), LogID:$("#dataLogID").val(), Filename:attachment_name).val()}, // form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#logbook_output').html(data);
drawVisualization();
},
error: function(data) {
console.log(err);
}
});
// close modal and refresh page
$('#EditLogModal').modal('hide');
}
});
I checked with Chrome Debugger to see whether any AJAX call is made, but I do not even get to the JavaScript Confirm Alert nor do I receive any error message in the console.
Any hints please?
Thanks
You have an invalid JSON data in your AJAX call (may be you can see errors in your browser's console),
data: { action:"delete_attachment",Holidex:$("#dataLogID").val(),
LogID:$("#dataLogID").val(), Filename:attachment_name).val()}, // form data to post goes here as a json object
//------------------^ don't use this
Just use Filename:attachment_name}
data: { action:"delete_attachment",Holidex:$("#dataLogID").val(),
LogID:$("#dataLogID").val(), Filename:attachment_name)}
change this
$("#DeleteAttachmentButton").click(function(e){
to this
$(document).on("click","#DeleteAttachmentButton",function(e){
Read about event-delegation
$(document).on('click', '#DeleteAttachmentButton', function(e){
var modal = $(this);
if (confirm('Are you sure you want to delete this attachment?')) {
var attachment_name = $(e.relatedTarget).data('filename'); // Extract info from data-* attribute
$.ajax({
url: "../../plugins/MySQL/ajax_action.php",
type: "POST",
async: true,
data: { action:"delete_attachment",Holidex:$("#dataLogID").val(), LogID:$("#dataLogID").val(), Filename:attachment_name).val()}, // form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#logbook_output').html(data);
drawVisualization();
},
error: function(data) {
console.log(err);
}
});
// close modal and refresh page
$('#EditLogModal').modal('hide');
}
});
I'm trying to make a CRUD in jquery/ajax/php for learning purposes.
But I can't figure out what I'm doing wrong with the delete part.
My goal is to delete an record from the database without refreshing the page.
Ajax function:
$(document).on('click', '.deleteOrder', function(e){
var id = $(this).attr('id');
console.log('Clicked order: ' + id);
$.ajax({
type: 'POST',
url: 'orders/deleteorder/',
data: {
orderId: id
},
success: function(data){
updateOrder(e);
},
error: function(){
console.log('error');
}
});
});
Php function:
public function deleteOrder(){
$orderId = $_POST['id'];
$count=$this->connection->prepare("DELETE FROM orders WHERE orderNumber = :number");
$count->bindParam(":number",$orderId,PDO::PARAM_INT);
$count->execute();
echo 'Finished order ' . $orderId;
}
First check the delete function called or not through ajax, in browser Network tab (you see this when clicking F12 button in browser)
you did not call deleteOrder function .
I want to keep a record of every click that occurs within a specific DIV and child DIVS on page. The client should not be aware of this. Inside of the div is a link to an external website.
Client clicks link inside div > ajax inserts record in db > client is sent to site of link clicked
PHP on page
include('quotemaster/dbmodel.inc.php');
if(isset($_POST['dataString'])) {
clickCounter();
}
PHP Model Function
function clickCounter() {
global $host, $user, $pass, $dbname;
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
$stmt = $DBH->prepare("INSERT INTO clickcounter (counter) VALUES (1)");
$stmt->execute();
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
AJAX POST
$(function() {
$("body").click(function(e) {
if (e.target.id == "results" || $(e.target).parents("#results").size()) {
//alert("Inside div");
ajax_post();
}
});
})
function ajax_post() {
var dataString = 'CC='+1;
$.ajax({ type: "POST", url: "tq/--record-events.inc.php", data: dataString });
}
The problem I am having (I think) is that the AJAX post is not being sent. Any ideas? Thanks!
on your PHP you have
if(isset($_POST['dataString'])) {...
you are expecting a parameter named dataString so you can fix it on your javascript ajax_post function with something like
var postData={dataString:true, CC:1}
$.ajax({ type: "POST", url: "tq/--record-events.inc.php", data: postData });
this way jQuery will create the proper dataString parameter.
Hope this helps
Try changing the POST check to:
if(isset($_POST['CC'])) {
clickCounter();
}
Also, if your DIV contains a link that navigates away from the page, clicking the link may cause the page location to change before the event bubbles down to the body tag. If so, you could try attaching an event to the link which calls preventDefault and therefore allow the event to bubble. If so, you could then detect that the user clicked the link and perform the navigation manually after recording the click. To show code as to how this can be achieved you need to post your full div code (including the link).
To add callbacks to the ajax call:
function ajax_post() {
var dataString = 'CC='+1;
$.ajax({
type: "POST",
url: "tq/--record-events.inc.php",
data: dataString,
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
Here's a link i saw but still confused over the answers provided for them : jQuery Ajax returns the whole page
My situation is something similar.
I have a index.php that calls for a popup login form, that tries to submit this login information to a ajax call to another php called login_check.php.
This is my index.php :
var dataString = 'email='+ email.val() + '&password=' + password.val();
$.ajax({
type: "POST",
url: "login_check.php",
data: dataString,
cache: false,
error: function (request, status, error) {
alert("An error occured while trying to complete your request: " + error);
},
success: function(data)
{
alert(data);
}
});
This is what is in my login_check.php :
session_start();
//input from login form
$myemail = htmlspecialchars(trim($_POST['email']));
$mypassword = htmlspecialchars(trim($_POST['password']));
//selecting from database to check user account
$sql="SELECT * FROM user WHERE email='$myemail' and password='$mypassword'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$count=mysql_num_rows($result);
//If result matched $myemail and $mypassword, table row must be 1 row
if($count==1)
{
echo 'true';
session_register("myemail");
$_SESSION['login_user']=$myemail;
}
else if($count==0)
{
echo 'false';
}
And the output of the alert box is the full html of the page i am currently in, i.e. index.php.
And i have no idea whyy. ):
Same happen here, I figured it out it has a conflict with other plugin, deactivate your plugin and it should works.
Hope it helps on other looking for this solution.
You might also want to try this syntax of making an Ajax POST request.
$.post('login_check.php',{'email':email.val(),'password':password.val()},function(response){
alert(response);
},"json");
No clue whether this solves your problem, but it's always a good idea to encode the data:
var dataString = encodeURIComponent('email='+ email.val() + '&password=' + password.val());
Maybe this solves your problem, too...