My problem is how JQuery knows when to receive data, when I watch the browser's console I see that GET call is first and then the POST call is second.
It should be POST first, then GET.
I tried solving my problem with .ready,and with some IF statements and so on but I still have not achieved what I wanted to achieve. Should I use some events?
My Javscript:
(function($) {
$(document).ready(function() {
$("form#userdata").submit(function(){
$.post( "savedata.php", $("form#userdata").serialize())
.done(function( data ) {
alert( "Send data" + data );
});
return false;
alert("Error by passing data to php");
});
})})(jQuery);
$.when($.ajax("savedata.php")).then(function(){
$.get("savedata.php", function(data){
alert("Php returns validation errors:+data);
});
});
My php script:
// Get POST data
$postData = $_POST;
// Print out for testing
// print_r($postData);
// Read data
$fistname = $_POST['firstname'];
$surname=$_POST['lastname'];
$email=$_POST['email'];
// VALIDATION
// Build return array and return JSON
$returnData = $postData;
//print(json_encode($returnData));
echo json_encode($returnData);
?>
$.get is called unconditionally, while the page is loading, because you didn't put it in an event handler.
$.post is only called when you submit the #userdata form, because it's called from the .submit() event handler.
You can try something like this:
PHP:
// Get POST data
$postData = $_POST;
// Print out for testing
// print_r($postData);
// Read data
$fistname = $_POST['firstname'];
$surname=$_POST['lastname'];
$email=$_POST['email'];
// VALIDATION
if(//validationError){
echo json_encode(array('error' => //Your error message here));
exit();
}
$returnData = $postData;
//print(json_encode($returnData));
echo json_encode(array('success' => $returnData));
?>
Then...
JS:
(function($) {
$(document).ready(function() {
$("form#userdata").submit(function(){
$.post("savedata.php", $("form#userdata").serialize())
.done(function( data ) {
if(data.error)
alert("Validation error: " + data.error);
else
alert( "Send data" + data.success );
})
.fail(function(){
alert("Error by passing data to php");
});
});
})})(jQuery);
You have your script incorrect
(function($) {
$(document).ready(function() {
$("form#userdata").submit(function(){
$.post( "savedata.php", $("form#userdata").serialize())
.done(function( data ) {
alert( "Send data" + data );
});
return false;
alert("Error by passing data to php");
});
})})(jQuery);
$.when($.ajax("savedata.php")).then(function(){
$.get("savedata.php", function(data){
alert("Php returns validation errors:"+data); // You did not close the string literal and it would throw an error
});
});
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'm trying to add jQuery to the javascript.js file for a child of woodmart theme, but I keep getting "javascript.js:131 Uncaught ReferenceError: jQuery is not defined".
javascript.js
(function($){
jQuery(document).ready(function($) {
//cart_actions parent container
//for POST requests when user saves a cart
clickparent = document.querySelector(".cart-actions");
clickparent.addEventListener("click", function(e) { // e = event object
let carts = JSON.parse(window.localStorage.getItem('yithPOS_carts'));
if (e.target && (e.target.className == "cart-action cart-action--suspend-and-save-cart cart-action--with-icon") || e.target.className == "cart-action__icon yith-pos-icon-saved-cart") {
// Use ajax to do something...
var postData = {
action: 'wpa_49691',
my_var: 'carts',
}
$.ajax({
type: "POST",
data: postData,
dataType:"json",
url: youruniquejs_vars.ajaxurl,
//This fires when the ajax 'comes back' and it is valid json
success: function (response) {
console.log("Cart saved to database.");
}
//This fires when the ajax 'comes back' and it isn't valid json
}).fail(function (data) {
console.log(data);
});
}
});
//pos_current_Cart_buttons parent container
//for GET requests when user views saved carts
viewcartparent = document.querySelector(".yith-pos-cart__buttons");
viewcartparent.addEventListener("click", function(e) { // e = event object
if (e.target && (e.target.className == "yith-pos-cart__buttons-saved-carts")) {
// Use ajax to do something...
var getData = {
action: 'wpa_49692',
my_var: 'my_data',
}
$.ajax({
type: "GET",
data: getData,
dataType:"json",
url: youruniquejs_vars.ajaxurl,
//This fires when the ajax 'comes back' and it is valid json
success: function (response) {
let total;
for(item in response){
total += item[lineTotal];
}
$(".yith-pos-cart__savedcarts").append('</div><i class="yith-pos-cart__savedcart"></i><div class="cart-saved__name"><div class="cart-saved__name__id">' + response['id'] + '</div><div class="cart-saved__name__customer">' + response['cartitems']['names'] + '</div></div><div class="cart-saved__num_of_items">' + response['cartitems'].size + '</div><div class="cart-saved__status">Pending Payment</div><div class="cart-saved__total">'+ total + '</div><button class="btn btn-primary"><i class="yith-pos-icon-refresh"></i> load</button></div>');
}
//This fires when the ajax 'comes back' and it isn't valid json
}).fail(function (data) {
console.log(data);
});
}
});
// Handler for .ready() called.
});
})(jQuery);
I've also tried enqueuing jquery with wp_enqueue_script and passing jquery in an array to the javascript file, neither changed anything.
functions.php:
wp_enqueue_script('jquery');
//First enqueue your javascript in WordPress
function save_cart_enqueue_scripts(){
//Enqueue your Javascript (this assumes your javascript file is located in your plugin in an "includes/js" directory)
wp_enqueue_script( 'javascript.js', plugins_url('https://cigarchiefstg.wpengine.com/wp-content/themes/woodmart-child/yith-pos-additions/javascript.js', dirname(__FILE__) ), array( 'jQuery' ));
//Here we create a javascript object variable called "youruniquejs_vars". We can access any variable in the array using youruniquejs_vars.name_of_sub_variable
wp_localize_script( 'javascript', 'javascript_vars',
array(
//To use this variable in javascript use "youruniquejs_vars.ajaxurl"
'ajaxurl' => admin_url( 'javascript_vars.ajaxurl' ),
)
);
}
add_action( 'wp_enqueue_scripts', 'save_cart_enqueue_scripts' );
//This is your Ajax callback function
function cart_save_callback_function(){
//Get the post data
$my_var = $_POST["my_var"];
//Do your stuff here - maybe an update_option as you mentioned...
update_option('saved_carts', $my_var);
//Create the array we send back to javascript here
$return_array = array();
//Make sure to json encode the output because that's what it is expecting
echo json_encode( $return_array );
//Make sure you die when finished doing ajax output.
die();
}
add_action( 'wp_ajax_' . 'wpa_49691', 'cart_save_callback_function' );
add_action( 'wp_ajax_nopriv_' . 'wpa_49691', 'cart_save_callback_function' );
function cart_view_callback_function(){
//Get the post data
$my_var = $_POST["my_var"];
//Do your stuff here - maybe an update_option as you mentioned...
//Create the array we send back to javascript here
$carts = get_option('saved_carts');
//Make sure to json encode the output because that's what it is expecting
echo json_encode( $carts );
//Make sure you die when finished doing ajax output.
die();
}
add_action( 'wp_ajax_' . 'wpa_49692', 'cart_view_callback_function' );
add_action( 'wp_ajax_nopriv_' . 'wpa_49692', 'cart_view_callback_function' );
Edit: Issues with POS items:
first check if jquery is correctly loaded on you wp website.
I suggest using this syntax for jQuery:
(function($){
$(document).ready(function(){
//your code
})(jQuery);
I am trying to pass a JSON object that looks similar to this:
{"service": "AAS1", "sizeTypes":[{"id":"20HU", "value":"1.0"},{"id":"40FB","2.5"}]}
Just a note: In the sizeTypes, there are a total of about 58 items in the array.
When the user clicks the submit button, I need to be able to send the object to a PHP script to run an UPDATE query. Here is the javascript that should be sending the JSON to the PHP script:
$('#addNewSubmit').click(function()
{
var payload = {
name: $('#addservice').val();
sizeTypes: []
};
$('input.size_types[type=text]').each(function(){
payload.sizeTypes.push({
id: $(this).attr('id'),
value: $(this).val()
});
});
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {service: payload},
dataType: 'json',
success: function(msh){
console.log('success');
},
error: function(msg){
console.log('fail');
}
});
});
Using the above click function, I am trying to send the object over to php script below, which is in api/editService.php:
<?php
if(isset($_POST['service']))
{
$json = json_decode($_POST['service'], true);
echo $json["service"]["name"] . "<br />";
foreach ($json["service"]["sizeTypes"] as $key => $value){
echo $value["value"] . "<br />";
}
}
else
{
echo "Nooooooob";
}
?>
I do not have the UPDATE query in place yet because I am not even sure if I am passing the JSON correctly. In the javascript click function, you see the SUCCESS and ERROR functions. All I am producing is the ERROR function in Chrome's console.
I am not sure where the error lies, in the JavaScript or the PHP.
Why can I only produce the error function in the AJAX post?
Edit
I removed the dataType in the ajax call, and added JSON.stringify to data:
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {servce: JSON.stringify(payload)},
success: function(msg){
console.log('success');
},
error: function(msg){
console.log('fail'), msg);
}
});
In the PHP script, I tried this:
if(isset($_POST['service'))
{
$json = json_decode($_POST['service'], true);
foreach ($json["service"]["sizeTypes"] as $key => $value){
$insert = mysqli_query($dbc, "INSERT INTO table (COLUMN, COLUMN, COLUMN) VALUES (".$json["service"] . ", " . "$value["id"] . ", " . $value["value"]")");
}
}
else
{
echo "noooooob";
}
With this update, I am able to get the success message to fire, but that's pretty much it. I cannot get the query to run.
without seeing the error, I suspect the error is because ajax is expecting json (dataType: 'json',) but you are echoing html in your php
Try to change
error: function(msg){
console.log('fail');
}
to
error: function(msg){
console.log(msg);
}
There might be some php error or syntax issue and you should be able to see it there.
Also try to debug your php script step by step by adding something like
echo "still works";die;
on the beginning of php script and moving it down till it'll cause error, then you'll know where the error is.
Also if you're expecting JSON (and you are - dataType: 'json' in js , don't echo any HTML in your php.
As you are sending an object in your service key, you probably have a multi-dimensional array in $_POST['service'].
If you want to send a string, you should convert the object to json:
data: {service: JSON.stringify(payload)},
Now you can decode it like you are doing in php.
Also note that you can only send json back from php if you set the dataType to json. Anything other than valid json will have you end up in the error handler.
Example how to handle a JSON response from editService.php. Typically, the editService.php script will be the worker and will handle whatever it is you need done. It will (typically) send a simple response back to the success method (consider updating your $.ajax to use the latest methods, eg. $.done, etc). From there you handle the responses appropriately.
$.ajax({
method: 'POST',
url: '/api/editService.php',
data: { service: payload },
dataType: 'json'
})
.done(function(msh) {
if (msh.success) {
console.log('success');
}
else {
console.log('failed');
}
})
.fail(function(msg) {
console.log('fail');
});
Example /editService.php and how to work with JSON via $.ajax
<?php
$response = [];
if ( isset($_POST['service']) ) {
// do your stuff; DO NOT output (echo) anything here, this is simply logic
// ... do some more stuff
// if everything has satisfied, send response back
$response['success'] = true;
// else, if this logic fails, send that response back
$response['success'] = false;
}
else {
// initial condition failed
$response['success'] = false;
}
echo json_encode($response);
I have made a little AJAX-script for my site, which executes a php-script in another file on submission. I managed to echo out the result in the original file with the AJAX-function, but I have not managed to transfer a variable from the php file to the original one.
I need this variable in order to add an event listener which will look for changes in that particular variable (not sure how to do that either).
Here's are what you are looking for it's working:-
Put this in your forsok.php
<div id="input">
<input type="text" id="number" name="value">
<b id="show_result"></b>
</div>`
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$('#number').on('keyup',function(e){
if(e.which == 13){
var get_var_name = $(this).val();
$.get('result.php',{number:get_var_name},function(data,status){
if(status == 'success'){
alert(data['show']);
$('#show_result').text(data['show']);
}else{
alert('Nothing');
}
});
}
});
</script>
For hej.php:-
<?php
$one=$_GET['number'];
if(empty($one)) {
echo "Can't be blank";
$a['result']='null';
$a['error'] = 'No value!!';
} else {
if(is_numeric($one)) {
$show=$one*2;
$arr = array(
'show'=>$show
);
header('Content-Type:application/json');
echo json_encode($arr);
exit();
// echo $show;
} else {
echo "NaN";
$a['result']='null';
$a['error']='nan';
}
}
?>
First create an array of what should be the output. JSON encode that array and then you can parse the output in your ajax success handler. Like in your php file output like:
echo json_encode(array(
'result' => 'null',
'error' => 'nan'
));
Then in you ajax success turn the json into an object and parse data as you want:
success: function (data, textStatus, jqXHR) {
var obj = $.parseJSON(data);
$('#utmatning').html(obj.result); // result value from your json return
$('#utmatning').append(obj.error); // error value from your json return
}
At last of your php file, add,
json_encode($a);
In ajax success,
success: function(html) {
$.each(html, function(index, element) {
alert(element.result);
alert(element.error);
//append to which ever div you want.
});
}
Now with this, you can get n number of array indexes from php
Instead of echoing strings here and there in in hej.php it might better to return JSON data to your ajax call. so you can evaluate if an error occured, which error it is or which valid result has been returned.
hej.php:
<?php
$one=$_GET['value'];
if(empty($one)) {
$a['result']='null';
$a['error'] = 'No value!!';
} else {
if(is_numeric($one)) {
$a['result']=$one*2;
$a['error']='ok';
} else {
$a['result']='null';
$a['error']='nan';
}
}
die(json_encode ($a));
?>
if $value was 1 that would return
{"result":"2","error":"ok"}
In forsok.php you could check the reults and act accordingly
...
$.ajax({
type: "GET",
dataType: "json",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(response)
{
if (response.error=='ok'){
$('#utmatning').html(response.result); // show response from the php script.
}
else{
console.log(response.result); // handle the error
}
}
});
...
Regards,
Stefan
PHP response :
$Result['sendtoshopnumber'] = 'SH-101';
echo json_encode($Result);
I want to show this shop no. to the user after the request is saved successfully to the database.
Jquery code :
var jqxhr = $.post("send_item.php",
{
ItemID: 120032,
Qty : 192
} , 'json')
.done(function(data) {
alert('your item is sent to shop no. = '+data.sendtoshopnumber);
***here it alerts : UNDEFINED***
})
.fail(function() {
alert( "failed" );
});
The console.log shows what is required but am not able to read that and use it in the javascript.
console.log output shows : {"sendtoshopnumber":SH-101}
Try to add this inside the done block:
.done(function(data) {
data = JSON.parse(data);
console.log(data);
alert('your item is sent to shop no. = '+data.sendtoshopnumber);
})
Then in PHP:
$Result['sendtoshopnumber'] = 'SH-101';
echo json_encode($Result);
exit;