JQuery Ajax/laravel form submit not working - php

I've been trying some stuff with Ajax and laravel, I've tried a lot at this point and have no idea what is going wrong. I can't seem to get the form data (that's what this is mainly about). If ANYONE is able to help, it'd be great. Here's the code, and thanks in advance.
$('.bier').on('click', bier);
$('.delete-check-close').on('click', closeDelete);
$('.delete-check-show').on('click', showDelete);
$('.message').on('click', closeMessage);
hideMessage();
$('form.page').on('submit', bier);
function bier() {
var form = $(this);
var url = form.attr('action');
console.log(url);
console.log(form);
console.log('bier');
console.log(form.find('input').serialize());
console.log('/bier');
var wtf = new FormData(form);
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
contentType: 'json',
data: form.serialize(),
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data, textStatus, jqXHR) {
console.log('success');
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
var data = $.parseJSON(jqXHR.responseText);
console.log(data);
if (data.errors) {
console.log(data.errors);
$.each( data.errors, function( key, value ) {
console.log(key);
console.log(value);
if(key.length > 0) {
var $error = $('td.' + key);
$error.removeClass('hidden');
$error.addClass('visible');
$error.html(value);
}
});
} else {
console.log('======================================== error');
console.dir(jqXHR);
console.dir(textStatus);
console.dir(errorThrown);
}
}
});
return false;
}
});

Try the following code:
$('form.page').on('submit', function() {
var form = $(this);
var url = form.attr('action');
console.log(url);
console.log(form);
console.log('bier');
console.log(form.find('input').serialize());
console.log('/bier');
var wtf = new FormData(form);
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
contentType: 'json',
data: form.serialize(),
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data, textStatus, jqXHR) {
console.log('success');
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
var data = $.parseJSON(jqXHR.responseText);
console.log(data);
if (data.errors) {
console.log(data.errors);
$.each( data.errors, function( key, value ) {
console.log(key);
console.log(value);
if(key.length > 0) {
var $error = $('td.' + key);
$error.removeClass('hidden');
$error.addClass('visible');
$error.html(value);
}
});
} else {
console.log('======================================== error');
console.dir(jqXHR);
console.dir(textStatus);
console.dir(errorThrown);
}
}
});
return false;
});

Related

Ajax getting 400 Bad Request when submitting Form only on Firefox

I have written a php code in wordpress to submit a form using ajax. It working fine on chrome but getting 400 Bad request on Firefox. This is my code:
jQuery(document).ready(function($){
jQuery( 'form[name="contact-me"]' ).on( 'submit', function(e) {
e.preventDefault();
var form_data = {};
$(this).serializeArray().forEach( function(element){
form_data[element.name] = element.value;
});
$.post(zt_send_form_obj.ajax_url, {
action: "zt_save_campain_form_data",
_ajax_nonce: zt_send_form_obj.nonce,
type: "POST",
contentType: 'application/json; charset=utf-8',
values: JSON.stringify(form_data),
}, function(data) {
if (data.success) {
if(data.data.info.message=='no'){
$('#myModal').show();
console.log('cod is in')
}
if(data.data.info.message=='yes'){
$('#CodeModal').show();
$('.the_cod_div').append('<span>'+data.data.info.code+'</span>');
console.log('data saved');
}
}
else{
console.log("not working");
}
});
});
});
Try this
$('form[name="contact-me"]').submit(function (e) {
e.preventDefault();
var form = $('#form_id')[0]; //set form id
var varform = new FormData(form);
varform.append("action", "zt_save_campain_form_data");
$.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: varform,
processData: false,
contentType: false,
cache: false,
crossDomain: true,
success: function (response) {
//if success do this...
console.log(response);
},
error: function (xhr, textStatus, error) {
console.log(xhr, textStatus, error);
}
})
});
Inside your form you can put this code for nonce validation
<?php wp_nonce_field( 'name_of_my_action', 'name_of_nonce_field' ); ?>

Loop through ajax response in jquery

I got the following ajax response.
{"ord_item_Json_string":"[{\"code\":\"1002\",\"item\":\"Diamond Softy\",\"size\":\"15 inch\",\"color\":\"Light Blue\",\"qty\":\"2\",\"price\":\"849.45\",\"amount\":\"1698.90\"},{\"code\":\"1001\",\"item\":\"sAMPLE\",\"size\":\"Cob\",\"color\":\"Naturtal\",\"qty\":\"5\",\"price\":\"434.05\",\"amount\":\"2170.25\"}]"}
now the problem is that i want to display only code and item fields & value but i am unable. please help me how to access that fields.
my code is following.
$.ajax({
url: base_url + 'order_jobcard/getOrderDetails/' + ord_id,
type: "POST",
data: JSON.stringify($('ord_id').serializeArray()),
success: function (data) {
$("#OrdItem").html(data);
console.log(data);
return true;
},
error: function () {
alert('Not Working');
$('#ord_buyer_pack_inst').empty();
}
});
Try this:
var abc = {"ord_item_Json_string":"[{\"code\":\"1002\",\"item\":\"Diamond Softy\",\"size\":\"15 inch\",\"color\":\"Light Blue\",\"qty\":\"2\",\"price\":\"849.45\",\"amount\":\"1698.90\"},{\"code\":\"1001\",\"item\":\"sAMPLE\",\"size\":\"Cob\",\"color\":\"Naturtal\",\"qty\":\"5\",\"price\":\"434.05\",\"amount\":\"2170.25\"}]"}
var a = JSON.parse(abc.ord_item_Json_string)
$.each(a, function(index,value){
console.log(value.code+'--'+value.item)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
try the code below...in success callback you will be getting data in json object format. so just get value using its key.
$.ajax({
url: base_url + 'order_jobcard/getOrderDetails/' + ord_id,
type: "POST",
data: JSON.stringify($('ord_id').serializeArray()),
success: function (jsonResponse) {
var itemsList = jsonResponse.ord_item_Json_string;
$.each(itemsList, function (index, value) {
console.log(value.code + '--' + value.item);
});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error");
}
});
try this: you can try below code where you can iterate over json array and read each attribute
$.ajax({
url: base_url + 'order_jobcard/getOrderDetails/' + ord_id,
type: "POST",
data: JSON.stringify($('ord_id').serializeArray()),
success: function (data) {
var dataStr = "";
var jsonData = data.ord_item_Json_string; // this is already json
jsonData = JSON.parse(jsonData);//value need to parse
for (var i = 0; i < jsonData.length; i++) {
var ord= jsonData[i];
console.log(ord.code);
dataStr += ord.code;
}
$("#OrdItem").html(dataStr);
console.log(data);
return true;
},
error: function () {
alert('Not Working');
$('#ord_buyer_pack_inst').empty();
}
});
JSFiddle

jQuery Ajax get json returned result

I want to get the return result of a php function in an Ajax request in order to make some verification in onSucces. How can I get the JSON result from the php function into the ajax request?
public function verifyEmailAction()
{
$is_valid = true;
$is_duplicate = false;
$email_reset = false;
$register = $this->getRegisterHelper();
$register->addEmailCheck();
$register->setData($this->getAllParams());
$validationErr = $register->getValidationResult();
if (!empty($validationErr['badWords']['email']) || $validationErr['banned']['email'] == true
|| empty($validationErr['isEmailValid'])
) {
$is_valid = false;
} elseif (!empty($validationErr['duplicates']['email'])) {
$is_duplicate = true;
$email_reset = $this->sendResetEmail();
}
$result = [
'duplicate' => $is_duplicate,
'valid' => $is_valid,
'reset' => $email_reset
];
$this->getResponse()->setBody(json_encode($result));
}
jQuery.validator.addMethod("checkDuplicate", function (value, element) {
jQuery.ajax({
type: 'GET',
url: '/user/register/verify-email.ajax',
data: {
'email': value
}
});
});
jQuery.ajax({
type: 'GET',
url: '/user/register/verify-email.ajax',
data: {
'email': value
},
dataType:'json',
success:function(response){
console.log(response);
var duplicate=response.duplicate;
var valid=response.valid;
var reset=response.reset;
},
error:function(err){
console.log('Error '+err);
}
});
You need to use the success and error functions like below,
jQuery.validator.addMethod("checkDuplicate", function (value, element) {
jQuery.ajax({
type: 'GET',
url: '/user/register/verify-email.ajax',
data: {
'email': value
},
success : function(data, status, xhr) {
console.log(JSON.stringify(data));
},
error: function(jqXhr, textStatus, errorMessage){
console.log("ERROR " + errorMessage);
}
});
});
$.ajax({
type: 'GET',
url: url,
data: {
'email': value
},
dataType:'json',
}).success(function(response){
//YOUR Json KEY
if(response.success){
}
});
I hope this article will help you.
http://api.jquery.com/jquery.ajax/
Specially you can use this
jQuery.ajax({
url: "YOURURL",
type: "YOURTYPE",
dataType:"json",
}).done(function(data) {
console.log(data) // to see the reqested data
// manipulate data here
});
Add dataType:'json':
jQuery.validator.addMethod("checkDuplicate", function (value, element) {
jQuery.ajax({
type: 'GET',
url: '/user/register/verify-email.ajax',
data: {
'email': value
},
dataType:'json'
});
});
You can use this to convert JSON string to a JavaScript object:
var txtReturned = JSON.parse(data);
Reference:
jQuery AJAX Call to PHP Script with JSON Return

jQuery ajax posting data to php

I am trying to post some data via ajax to php. The issue i have is the original data is pulled in via some java, like this:
var taskID = jQuery(this).attr('data-id');
var taskTitle = jQuery(this).attr('data-title');
var taskContent = jQuery(this).attr('data-content');
jQuery('.task_title').val(taskTitle);
jQuery('.task_description').val(taskContent);
When i then try and update this content in the browser (via a form), only the original data is getting posted back, and not the updated data.
Here is my ajax to post the data:
$( ".saveTaskEdit" ).click(function(event) {
var ta = $('.task_title').val();
var da = $('.task_description').val();
var taskID = $('.editTaskPanel').attr('data-id');
$.ajax({
type: "post",
url: "task-edit.php?t="+ ta + "&d=" + da + "&id=" + taskID,
contentType: "application/x-www-form-urlencoded",
success: function(responseData, textStatus, jqXHR) {
jQuery('p.status').text('Task Saved');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
})
});
Is there any reason behind this?
You set type as "post" but send data as "get"; change your ajax , update "url" add "data" like this:
$( ".saveTaskEdit" ).click(function(event) {
var ta = $('.task_title').val();
var da = $('.task_description').val();
var taskID = $('.editTaskPanel').attr('data-id');
$.ajax({
type: "post",
data: { "t":ta,"d":da,"id":taskID},
url: "task-edit.php",
contentType: "application/x-www-form-urlencoded",
success: function(responseData, textStatus, jqXHR) {
jQuery('p.status').text('Task Saved');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
})
});

passing variables with $.ajax

I have two checkboxes with some values like this:
<label for="hotel_boutique"><input id="hotel_boutique" name="hotel_boutique" value="test" type=checkbox />test</label><br />
3
and I get these values with an Ajax call like this:
<script>
jQuery("input[type='checkbox']").change(function(){
if (jQuery('input#hotel_boutique').is(':checked')) {
var hotel_boutique = jQuery("#hotel_boutique").map(function () {return this.value;}).get();
}else{
var hotel_boutique = 'NULL';
}
if (jQuery('input#hotel_stars').is(':checked')) {
var hotel_stars = jQuery("#hotel_stars").map(function () {return this.value;}).get();
}else{
var hotel_stars = 'NULL';
}
var data = 'hotel_boutique="'+hotel_boutique+'"&hotel_stars="'+hotel_stars+'"';
jQuery.ajax({
url: "processAjax.php",
type: "GET",
data: data,
cache: false,
beforeSend: function() {
jQuery("#loading").show();
},
success: function(data, textStatus, XMLHttpRequest){
jQuery("#content").html('');
jQuery("#content").append(data);
jQuery("#loading").hide();
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
</script>
Now when I echo the variables in the server side (PHP) it displays:
"test"
Who and why are the " added? And how can I remove them?
I have already tried the PHP function preg_replace and other stuff.
please need your help...
You can use an object instead of string like
var data = {
hotel_boutique: hotel_boutique,
hotel_stars: hotel_stars
};
The problem is the " in the data string, you can also try
var data = 'hotel_boutique='+hotel_boutique+'&hotel_stars='+hotel_stars;
The overall code can be simplified as
jQuery("input[type='checkbox']").change(function () {
var data = {
hotel_boutique: $('#hotel_boutique:checked').val()||'NULL',
hotel_stars: $('#hotel_stars:checked').val()||'NULL'
};
jQuery.ajax({
url: "processAjax.php",
type: "GET",
data: data,
cache: false,
beforeSend: function () {
jQuery("#loading").show();
},
success: function (data, textStatus, XMLHttpRequest) {
jQuery("#content").html(data);
jQuery("#loading").hide();
},
error: function (MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
you need to pass key-value pair:
data: {hotel_boutique: hotel_boutique,hotel_stars: hotel_stars},
In this call:
jQuery.ajax({
data: data, // change here
});
it should be :
jQuery.ajax({
url: "processAjax.php",
type: "GET",
data: {
hotel_boutique: hotel_boutique,
hotel_stars : hotel_stars
},
cache: false,
beforeSend: function() {
jQuery("#loading").show();
},
success: function(data, textStatus, XMLHttpRequest){
jQuery("#content").html('');
jQuery("#content").append(data);
jQuery("#loading").hide();
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});

Categories