My jQuery Ajax not working with PHP - javascript

I am trying to post data and receive response using jQuery Ajax Post and I am not sure why my code is not working.
<script>
$(document).ready(function(){
$('#login').click(function(){
$.ajax({
type: 'POST',
url: 'http://code.com/backend/test3',
dataType: 'json',
data: {"username":"akllkkj","password":"kljjkjkl"},
cache: false,
success: function(data){
console.log(data.stack);
console.log(data.key);
},
error:function(){
alert("failure");
}
});
return false;
});
});
</script>
<form autocomplete="off" class="ui fluid form segment" method="post">
<div class="ui fluid form segment">
<div class="two fields">
<div class="field">
<label>Email/Username</label>
<input placeholder="Email/Username" name="username" id="username" type="text">
</div>
<div class="field">
<label>Password</label>
<input placeholder="Password" name="password" id="password" type="password">
</div>
</div>
<input type="button" class="ui fluid submit button" name="dosubmit" value="Submit" id="login" />
</div>
</form>
And my test3 page contains:
<?php
if(isset($_POST['username']) && isset($_POST['password'])) {
$arr = array(
'stack'=>'overflow',
'key'=>'value'
);
echo json_encode($arr);
}
?>

This has worked for me:
$('#form').submit(function (event) {
event.preventDefault();
var data = $('#form').serialize();
$.ajax({
type: 'post',
dataType: 'json',
data: data
}).done(function (resp) {
console.log(resp);
});
});
And on the php side of things, you may need something like this:
header('Content-Type: application/json');
echo json_encode($arr);

Try this. It will work.
<script type="text/javascript">
$(document).ready(function(){
$('#login').click(function(){
$.ajax({
type: 'POST',
url: 'http://code.com/backend/test3.php',
dataType: 'json',
data: {"username":"akllkkj","password":"kljjkjkl"},
async: true,
success: function(data){
var obj = jQuery.parseJSON(data);
if(obj)
{
for(i=0;i<obj.length;i++) {
console.log(obj[i].stack);
console.log(obj[i].key);
}
} else {
console.log("Empty Result");
}
},
error:function(){
alert("failure");
}
});
});
});
<script>
And you test3.php script will be:
<?php
$arr=array();
if(isset($_POST['username']) && isset($_POST['password'])) {
$arr[] = array(
'stack'=>'overflow',
'key'=>'value'
);
}
echo json_encode($arr);
?>

Related

What's the problem with my Wordpress ajax request

I want to add have a form in my Wordpress dashboard that work with ajax but my request response is 400 Bad request
add_action('admin_footer', 'vitrin_admin_ajax');
function vitrin_admin_ajax() {
?>
<script>
(function($) {
$('.vitrin-private-message-form').submit(function(event) {
event.preventDefault();
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: {
action: 'submit_vitrin_pm',
ppmcontent: jQuery('#pmcontent').val(),
ppmusers: jQuery('#pmusers').val(),
},
success: function(data) {
// jQuery('#datafetch').html(data);
alert(data)
}
});
})
})(jQuery);
</script>
<?php
}
?>
I also add:
add_action('wp_ajax_submit_vitrin_pm', 'submit_vitrin_pm');
add_action('wp_ajax_nopriv_submit_vitrin_pm', 'submit_vitrin_pm');
and
function submit_vitrin_pm() {
echo 'ssss';
die();
}
I checked, your ajax response is working, you didn't share your html form, i added a form for check.
add_action('admin_footer', 'vitrin_admin_ajax');
function vitrin_admin_ajax() {
?>
<form action="#" method="POST" class="vitrin-private-message-form">
<div id="name-group" class="form-group">
<label for="name">Name</label>
<input
type="text"
class="form-control"
id="pmcontent"
name="name"
placeholder="Full Name"
/>
</div>
<div id="email-group" class="form-group">
<label for="email">Email</label>
<input
type="text"
class="form-control"
id="pmusers"
name="email"
placeholder="email#example.com"
/>
</div>
<button type="submit" class="btn btn-success">
Submit
</button>
</form>
<script>
(function($) {
$('.vitrin-private-message-form').submit(function(event) {
event.preventDefault();
console.log('working')
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: {
action: 'submit_vitrin_pm',
ppmcontent: jQuery('#pmcontent').val(),
ppmusers: jQuery('#pmusers').val(),
},
success: function(data) {
// jQuery('#datafetch').html(data);
alert(data)
}
});
})
})(jQuery);
</script>
<?php
}
add_action('wp_ajax_submit_vitrin_pm', 'submit_vitrin_pm');
add_action('wp_ajax_nopriv_submit_vitrin_pm', 'submit_vitrin_pm');
function submit_vitrin_pm() {
echo 'ssss';
die();
}

Undefined response while uploading image with ajax

I have a problem uploading images in AJAX.
When I click on send the image, I get a jquery feedback that tells me "undefined" while the image has been clicked
I have try one other thing who works properly, but creating a really simple form and by giving a class attribute to jquery instead of id.
And that works..
The form who does not works ( i would like it to works :) )
<form action="ajax/uploadimage.php" method="post" enctype="multipart/form-data" >
<div class="card-body">
<!-- Single -->
<div class="dropzone dropzone-single mb-3" data-toggle="dropzone" data-dropzone-url="http://">
<div class="custom-file">
<input id="file-upload" type="file" name="fileToUpload" class="custom-file-input" multiple required>
<label class="custom-file-label" for="file-upload">Choose file</label>
</div>
<div class="dz-preview dz-preview-single">
<div class="dz-preview-cover">
<img class="dz-preview-img" src="..." alt="..." data-dz-thumbnail>
</div>
</div>
</div>
<center><input type="submit" class="btn btn-primary" id="file-submit" value="<?php echo TXT_DASHBOARD_MODIFIER; ?>"></center>
</div>
</form>
The jquery who does not works
<script type="text/javascript">
$(function() {
$('#file-submit').on('click', function() {
var file_data = $('#file-upload').prop('files')[0];
if(file_data != undefined) {
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
type: 'POST',
url: 'ajax/uploadimage.php',
contentType: false,
processData: false,
data: form_data,
success:function(response) {
if(response == 'success') {
alert('File uploaded successfully.');
} else if(response == 'false') {
alert('Invalid file type.');
} else {
alert('Something went wrong. Please try again.');
}
$('#file-upload').val('');
}
});
}
return false;
});
});
</script>
The form who works :
<form>
<input type="file" name="image" class="image" required>
<input type="submit" name="submit" class="submit" value="Submit">
</form>
The jquery who works :
<script type="text/javascript">
$(function() {
$('.submit').on('click', function() {
var file_data = $('.image').prop('files')[0];
if(file_data != undefined) {
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
type: 'POST',
url: 'ajax/uploadimage.php',
contentType: false,
processData: false,
data: form_data,
success:function(response) {
if(response == 'success') {
alert('File uploaded successfully.');
} else if(response == 'false') {
alert('Invalid file type.');
} else {
alert('Something went wrong. Please try again.');
}
$('.image').val('');
}
});
}
return false;
});
});
</script>
I would like to solve the undefined error..
Thanks for help :)

Can't receive a correct response when posting to same page with AJAX

I'm trying to post to same page and retrieve results with AJAX:
Ajax call:
$(document).ready(function() {
$("#createaccount").click(function(){
console.log("Clicked");
console.log(document.getElementById("textbox").value);
$.ajax({
type: "POST",
data: {'textAreaInput': document.getElementById("textbox").value},
success: function (data) {
if(data.status == "1") {
alert("we having a working script");
} else {
alert("Oops, script is a no go");
}
}
});
});
});
Form:
<form method="post" action='' class='form-horizontal' enctype='multipart/form-data' id='startform'>
<textarea id="textbox"></textarea>
<button class="btn btn-primary col-lg-12 col-xs-12 col-md-12" name="createaccount" id="createaccount" type="button">Create account</button>
</form>
PHP handler:
<?php
if (isset($_POST['textAreaInput'])){
$result = array("status" => "1");
echo json_encode($result);
exit;
}
?>
I always receive a Oops, script is a no go as an alert, so it seems that something is wrong, but i'm not fully sure at which part. Am i handling it wrong or posting it in the wrong way?
Here is test.php:
<?php
if (isset($_POST['textAreaInput'])){
$result = array("status" => "1");
echo json_encode($result);
exit;
}
?>
<form method="post" action='' class='form-horizontal' enctype='multipart/form-data' id='startform'>
<textarea id="textbox"></textarea>
<button class="btn btn-primary col-lg-12 col-xs-12 col-md-12" name="createaccount" id="createaccount" type="button">Create account</button>
</form>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#createaccount").click(function(){
console.log("Clicked");
console.log(document.getElementById("textbox").value);
$.ajax({
type: "POST",
data: {'textAreaInput': document.getElementById("textbox").value},
dataType: 'json',
success: function (data) {
if(data.status == "1") {
alert("we having a working script");
} else {
alert("Oops, script is a no go");
}
}
});
});
});
</script>

serialized form not sending ajax

I'm having trouble to send a serialized form through ajax to a php file. I can see the string on the client side, but on the server side I receive an empty array.
I'm trying to save the form data into a database, but a I can't seem to find a way to separate every input, and show it in my php file after I sent with ajax.
JavaScript
$(function() {
//twitter bootstrap script
$("button#guardar").click(function(e) {
//var info = $('#myform').serialize();
var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
alert(info);
window.location.href = "solicitudesProc.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
<form class="contact" id="myform" method="post" name='alta'>
<div class="modal-body">
<div class="row">
<div class="col-md-2">
<label>Solicitante</label>
<input type="text" class="form-control pull-right" name='solicitante' maxlength="20" required />
</div>
<div class="col-md-2">
<label>Fecha Emision</label>
<input type="text" class="form-control pull-right" name='fechaEmision' maxlength="20" />
</div>
</div>
<div class="row">
<div class="col-md-2">
<label>Area Solicitante</label>
<input type="text" class="form-control pull-right" name='area' maxlength="20" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar" name='guardar' class="btn btn-danger pull-right" value="guardar">Generar</button>
</div>
</form>
server side solicitudesProc.php
<?php $info = $_POST;
echo $_POST["solicitante"]; print_r($_POST); ?>
Do not change location
Cancel the submit
I strongly suggest you either remove the form OR wire up the submit event:
$(function() {
$("form.contact").on("submit", function(e) {
e.preventDefault(); // stop the submit
var info = $(this).serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
console.log(info);
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
I maked it work by doing this changes:
change the form action to the php file im sending.
<form action="solicitudesProc.php" class="contact" id="myform" method="post" name='alta' >
and my ajax changed to:
var info = $('#myform').serialize();
//var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: form.attr("action"),
data: $("#myform input").serialize(),
success: function(data){
//console.log(info);
window.location.href = "solicitudes.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data){
alert("failure");
}
});
});
});
Thanks for your help!

How do I add my csrf token to my jQuery call?

My server generates a csrfToken, which is inserted into the following element:
<input type="hidden" name="_csrf" value="{{_csrfToken}}">
The {{_csrfToken}}, is used for templating, but at run time is replaced at the server with the actual token.
<div class="formContainer">
<form class="form-horizontal signupform" role="form" action="/process?form=signupform" method="POST">
<input type="hidden" name="_csrf" value="{{_csrfToken}}">
<div class="form-group">
<label for="fieldName" class="col-sm-2 control-label">Name</label>
<div class="col-sm-4">
<input type="text" class="form-control"
id="fieldName" name="name">
</div>
</div>
<div class="form-group">
<label for="fieldEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-4">
<input type="email" class="form-control" required id="fieldName" name="email">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-4">
<button type="submit" class="btn btn-default">Register</button>
</div>
</div>
</form>
</div>
{{#section 'jquery'}}
<script>
$(document).ready(function(){
$('.signupform').on('submit', function(evt){
evt.preventDefault();
var action = $(this).attr('action');
var $container = $(this).closest('.formContainer'); $.ajax({
url: action,
type: 'POST',
success: function(data){
if(data.success){ $container.html('<h2>Thank you!</h2>');
}else{
$container.html('There was a problem.');
}
},
error: function(){
$container.html('There was a problem.');
}
});
});
});
</script>
{{/section}}
How do I update my jQuery call to include the token ? Right now it is generating errors because the token is not included...
Try this, you did not post anything in fact. I did not test it, if it fails, maybe you should collect data manually.
<script>
$(document).ready(function(){
$('.signupform').on('submit', function(evt){
evt.preventDefault();
var action = $(this).attr('action');
+ var payload = $(this).serializeArray()
var $container = $(this).closest('.formContainer'); $.ajax({
url: action,
type: 'POST',
+ data: payload,
success: function(data){
if(data.success){ $container.html('<h2>Thank you</h2>');
}else{
$container.html('There was a problem.');
}
},
error: function(){
$container.html('There was a problem.');
}
});
});
});
</script>
though it looks like it's a duplicate post still as far as answer is concerned this is how you should do check this SO post
and I am writing the code for you here
<script>
$(document).ready(function(){
$('.signupform').on('submit', function(evt){
evt.preventDefault();
var action = $(this).attr('action');
var $container = $(this).closest('.formContainer');
var token = $('input[name="_csrf"]').attr('value')
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('Csrf-Token', token);
}
});
$.ajax({
url: action,
type: 'POST',
success: function(data){
if(data.success){ $container.html('<h2>Thank you!</h2>');
}else{
$container.html('There was a problem.');
}
},
error: function(){
$container.html('There was a problem.');
}
});
});
});
</script>

Categories

Resources