Reputation: 3182
I want to save user email
to database when he clicks the subscribe button. But when I enter email and click the subscribe button it passes an empty array!
Subscribe form code:
<form id="cx-subscribe-user">
<input type="text" name="email" id="email" placeholder="Enter Your Email" />
<button type="submit" id="subscribe-button">Subscribe</button>
</form>
Js code:
$('#cx-subscribe-user').on('click', function (e) {
e.preventDefault();
var email = $('#email').val();
$.ajax({
type: "GET",
url: "subscribe-the-user.php",
processData: false,
dataType: 'json',
data: {email: email},
success: function(data) {
console.log('saved scucess');
}
});
});
In subscribe-the-user.php
file I'm trying to var_dump the request but it's printing empty array:
var_dump($_GET);exit;
In var_dump I receive this empty array
array(0) {}
Upvotes: 2
Views: 470
Reputation: 72289
The problem is you are using an onclick()
event on the <form>
object, so as soon as you click in email input field to add some data, form onclick()
event is fired and the ajax request will happen without any data in the email
field hens submitting an empty email
parameter to the PHP.
Change form onclick()
to button click()
or form submit()
$('#subscribe-button').on('click', function (e) {
Also remove processData: false,
[based on documentation:- jQuery ajax documentation]
processData (default: true) Type: Boolean By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
Upvotes: 2
Reputation: 6637
remove the processData
, as documentation states, it will mess up your request
processData (default: true)
Type: Boolean
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false. https://api.jquery.com/jQuery.ajax/
Upvotes: 5
Reputation: 390
You can do that using POST
method
$('#cx-subscribe-user').on('click', function (e) {
e.preventDefault();
var email = $('#email').val();
$.ajax({
type: "POST",
processData: false,
dataType: 'json',
data: {email: email},
url: "subscribe-the-user.php",
success: function(data) {
console.log('saved success');
}
});
});
Upvotes: 1
Reputation: 5202
Emails need some encoding before send your request
$.ajax({
url: "ajax.php",
type:'get',
data: { email: encodeURIComponent(email)},
dataType: 'json',
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
Upvotes: 1