I am trying to take data from my div an add it to php file:
my javascript is:
$(document).ready(function(){
$('#save').on('submit',function(e) {
var bufferId = document.getElementById('data2save');
$.ajax({
url:'saver.php',
data:{id : bufferId},
type:'POST',
success:function(data){
console.log(data);
alert("ok"); //=== Show Success Message==
},
error:function(data){
alert("not ok"); //===Show Error Message====
}
});
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
});
});
my html part is:
<input type="button" value="save" id="save">
<div id="data2save">
Data to be added.
</div>
and my saver.php file is:
<?php
$data = $_POST['id'];
if (($fp = fopen("test.txt", "w"))){
fwrite($fp,$data);
fclose($fp);
echo "ok";
}
?>
Can someone please point out the issue?
Your have a wrong selector, replace document.getElementById('info1'); with var bufferId = $("#data2save").html();
$(document).ready(function(){
$('#save').on('submit',function(e) {
var bufferId = $("#data2save").html();
$.ajax({
url:'saver.php',
data:{id : bufferId},
type:'POST',
success:function(data){
console.log(data);
alert("ok"); //=== Show Success Message==
},
error:function(data){
alert("not ok"); //===Show Error Message====
}
});
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
});
});
As document.getElementById('data2save') is an DOM element. You cannot sent it directly as data in the AJAX request.
Replace it with document.getElementById('data2save').value and then let us know if it works.
The new javascript would be like this
(document).ready(function(){
$('#save').on('submit',function(e) {
var bufferId = document.getElementById('data2save').value;
$.ajax({
url:'saver.php',
data:{id : bufferId},
type:'POST',
success:function(data){
console.log(data);
alert("ok"); //=== Show Success Message==
},
error:function(data){
alert("not ok"); //===Show Error Message====
}
});
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
});
});
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 got this website when I fill the information and try to send the OTP page reload
Here's the website:
https://tunisia.blsspainvisa.com/english/book_appointment.php
After you fill the information and click on (Request verification code) and you will know what I mean
What I tried is:
$(function () {
$('#tunisiaThird').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'https://tunisia.blsspainvisa.com/book_appointment.php',
data: $('#tunisiaThird').serialize(),
success: function () {
}
});
});
});
I'm only a client, so I'm using Tampermonkey to inject.
You need to read more about jquery ajax post or get method here:
https://api.jquery.com/jQuery.post/
And there are tons of questions here if you search you will find tons of examples
Here is a complete example, which is getting error messages from php part and displaying on html form.
Like this: in php : $error .= 'an error happend'; and ajax $('#result').html(data.error);
to display in html.
<div id="result"></div>
$(document).ready(function(){
$('#tunisiaThird').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"book_appointment.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if(data.error === 'ok'){
$('#result').html('Successfuly');
$('#tunisiaThird')[0].reset();
setTimeout(function() {
window.location = 'index.php';
}, 1000);
} else {
$('#result').html(data.error);
}
}
});
});
});
So I'm trying to send the form info to php with ajax form every second, but for some reason it doesn't want to.
Here is my latest attempt, I tried every other similar combination(like put everything in the function or just put everything into the setInterval).
$(document).ready(function() {
var ajaxCall=function() {
$("#myForm").ajaxForm(function(e) {
$.ajax({
type:'post',
url:'php1.php',
data:$("#myForm").serialize(),
success:function(data) {
document.getElementById("result").innerHTML=data;
}
});
});
}
setInterval(ajaxCall,1000);
});
EDIT
Solved with M.M answer, thank you for the help!
Simply change ajaxForm to ajaxSubmit
See this (question) and this (documentation) for more information on AjaxForm vs AjaxSubmit
Essentially AjaxForm submits when the user clicks the button and AjaxSubmit does it immediately so your code should be:
$(document).ready(function()
{
var ajaxCall=function()
{
$("#myForm").ajaxSubmit(function(e)
{
$.ajax(
{
type:'post',
url:'php1.php',
data:$("#myForm").serialize(),
success:function(data)
{
document.getElementById("result").innerHTML=data;
}
});
});
}
setInterval(ajaxCall,1000);
});
Update after comment explanation
$(document).ready(function(){
//live feed
var ajaxCall=function(){
$("#myForm").ajaxSubmit(function(e){
ajax_submit();
});
}
setInterval(ajaxCall,1000);
//real submit
$("#myForm").ajaxForm(function(e){
ajax_submit();
});
function ajax_submit(){//ajax_code
$.ajax({
type:'post',
url:'php1.php',
data:$("#myForm").serialize(),
success:function(data) {
document.getElementById("result").innerHTML=data;
}
});
}
});
If you wish to differentiate the feed from the submit you can pass a parameter to the ajax_submit function
Getting rid of the ajaxForm() call seems to accomplish what you are trying to do:
$(document).ready(function() {
var ajaxCall = function() {
$.ajax({
type: 'post',
url: 'php1.php',
data: $("#myForm").serialize(),
success: function(data) {
document.getElementById("result").innerHTML = data;
}
});
}
setInterval(ajaxCall, 1000);
});
I want to execute a JS function when a PHP form is submitted, and from that function, I want to return a value (which is based on user's input) to PHP, where I'd like to echo it.
This is an SSCCE. In the real code, there is more than just echoing the value, and the value is a JSON object.
Following is my code. The problem is that the $.ajax(); part is not working. Nothing happens in the browser after alert(name);.
Why isn't this working properly? How can I fix this?
From index.php:
<form id="form">
Name:
<input id="name" type="text" />
<input type="Submit" value="Go" />
</form>
From scripts.js:
$(document).ready(function() {
$("#form").submit(function(event) {
event.preventDefault();
var name = $("#name").val();
alert(name);
$.ajax({
type:'POST',
url:'echo.php',
data: {
nameEntered : name
}
});
});
});
echo.php:
<?php
if ( isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"]) ) {
echo $_POST["nameEntered"];
} else {
echo '$_POST["nameEntered"] is not set.';
}
?>
EDIT:
Console:
Network:
EDIT 2:
Added the following to $.ajax():
,
success: function(){
alert("success");
},
error : function(){
alert("error");
}
I get an alert saying success but the browser NEVER directs to echo.php =s
EDIT 3:
After the alert saying success, a ? is added to the URL in the browser. Initially the URL was http://localhost/Test12/index.php and it changed to http://localhost/Test12/index.php?.
This way should show response.
JAVASCRIPT
$("#form").submit(function(event) {
event.preventDefault();
var name = $("#name").val();
//alert(name);
$.ajax({
type:'POST',
url:'http://localhost/Test12/echo.php',
data: {
nameEntered : name
},
success : function(data){
console.log(JSON.parse(data));
},
error : function(error){
console.log('erro', error);
}
});
});
PHP
<?php
if (isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"])) {
$name = array("nome" => $_POST["nameEntered"]);
echo json_encode($name);
} else {
echo '$_POST["nameEntered"] is not set.';
}
?>
As a test, replace your echo.php with:
<?php
echo 'Incoming = ' .$_POST["nameEntered"]. "/r/n";
if (isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"])) {
echo 'Here 01';
} else {
echo 'Here 02';
}
?>
Try removing the document.ready() or instead of .submit use .on('submit', function(e){}); or add absolute path '/page.php'
I think you need to add "event" as parameter in your submit function, in addition to the success call to show results
What does this give you:
$.ajax({
type:'POST',
url:'echo.php',
data: {
nameEntered : name
},
success: function(recd){ // <-------
alert(recd); // <-------
},
error : function(){
alert("error");
}
});
You're calling event.preventDefault(), but you've failed to add the event to your callback's parameters... so you're not actually stopping the form from being submitted. That is why you see the question mark in the address bar.
Try:
function(e){
e.preventDefault();
};
I send a form with jquery ajax like this:
$("#login").submit(function(e) {
e.preventDefault();
var url = "login";
$.ajax({
url:url,
type:'POST',
data:$(this).serialize(),
success:function(result){
$("#response").text(result)
});});
I wanna locate page if login was successful.
This is my php condition:
if(islogin())
header("Location:".$home_url."home");
}
else{
echo "Oops! Something is wrong!";
}
How can I change my jquery script to locate page? thanks.
Change your ajax success statements with:
success: function(data, status, xhr) {
console.log(xhr.getResponseHeader('Location'));
}
So your complete script would be:
$("#login").submit(function(e) {
e.preventDefault();
var url = "login";
$.ajax({
url:url,
type:'POST',
data:$(this).serialize(),
success: function(data, status, xhr) {
console.log(xhr.getResponseHeader('Location'));
}
});});
And your php script would change to:
<?php
header("Access-Control-Expose-Headers: Location");
if(islogin())
echo $home_url."home";
}
else{
echo "Oops! Something is wrong!";
}
?>
Try this:
JS
$("#login").submit(function(e) {
e.preventDefault();
var url = "login";
$.ajax({
url:url,
type:'POST',
data:$(this).serialize(),
success:function(result){
if (result.indexOf('Oops') !=-1) {
$("#response").text(result)
} else {
window.location.href = result;
}
});
});
PHP
if(islogin())
echo $home_url."home";
}
else{
echo "Oops! Something is wrong!";
}
Why would you use Ajax at all if you change the page anyway?
If you still want to, echo the actual new location instead of setting a header and do
success:function(result){
if (result.indexOf("Oops") !=-1) $("#response").text(result);
else location.replace(result);
});