I have created a script that takes 2 post codes and returns the distance, if the distance is less than 4 miles it returns a success message, if it is over 4 miles it returns another message. It should also throw an error if the form field is empty.
I'd love to be able to return the data without refreshing the page but so far i can't seem to get the ajax request working, it just doesn't do a anything at all.
jQuery isn't my fortè i pieced this together by searching online.
$(document).ready(function () {
$('#postcode-form').submit(function (event) {
event.preventDefault();
$('.help-block').remove(); // remove the error text
var formData = {
'destination': $('input#destination').val()
};
$.ajax({
type: 'POST',
url: 'includes/postcode-finder.php',
data: formData,
dataType: 'json',
encode: true
}).done(function (data) {
if (!data.success) {
if (data.errors.destination) {
$('#destination-group').append('<div class="help-block">' + data.errors.destination + '</div>');
}
} else {
$('#postcode-form').append('<div class="alert alert-success">' + data.message + '</div>');
}
})
});
});
and the php code:
$bakery = 'DH12XL';
$destination = $_POST['destination'];
$errors = [];
$result = [];
if(empty($destination))
{
$errors['postcode'] = 'Postcode is required';
}
if(!empty($errors))
{
$data['success'] = false;
$data['errors'] = $errors;
}
else
{
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$bakery&destinations=$destination&mode=bicycling&language=en-EN&sensor=false&units=imperial";
$google = #file_get_contents($url);
$result = json_decode($google, true);
$distance = $result['rows'][0]['elements'][0]['distance']['text'];
$many_miles = str_replace(' mi', '', $distance);
if($many_miles > 4.0)
{
$data['message'] = 'Collection only for this postcode';
}
else
{
$data['message'] = 'Good news, we deliver!';
}
$data['success'] = true;
echo json_encode($data);
}
You're using jQuery 1.4.4, which doesn't return Promises from $.ajax and therefore the .done() function isn't available.
You have two options:
Update jQuery (ensure you test anything else that's leaning on it if you do, though!)
Or use the success parameter instead:
$.ajax({
type: 'POST',
url: 'includes/postcode-finder.php',
data: formData,
dataType: 'json',
encode: true,
success: function (data) {
// do stuff
}
});
From the docs:
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the
Promise interface, giving them all the properties, methods, and
behavior of a Promise (see Deferred object for more information).
Related
I'm very new with Ajax and I need help to store the data from an Ajax request into an array. I looked at answers here at the forum, but I'm not able to solve my problem.The Ajax response is going into $('#responseField').val(format(output.response)) and I'm want store "output.response" into an array that can be used outside of the Ajax. I tried to declare a variable outside of the Ajax and call it later, but without success. I'm using $json_arr that should get the data. How do I do to get the data from the Ajax and store it in a variable to be used outside of the Ajax? This variable will an array that I can access the indexes.
function sendRequest(postData, hasFile) {
function format(resp) {
try {
var json = JSON.parse(resp);
return JSON.stringify(json, null, '\t');
} catch(e) {
return resp;
}
}
var value; // grade item
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) { //data= retArr
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
data = $.parseJSON(output.response)
$json_arr=$('#responseField').val(format(output.response));
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
}
window.alert($json_arr);
let promise = new Promise(function(resolve, reject) {
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) { //data= retArr
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
data = $.parseJSON(output.response)
resolve(format(output.response));
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
});
promise.then(
function(result) { /* you can alert a successful result here */ },
function(error) { /* handle an error */ }
);
The issue is you are calling asynchronously.
You call the alert synchronously, but it should be called asynchronously.
A little snippet to help you see the difference:
// $json_arr initialized with a string, to make it easier to see the difference
var $json_arr = 'Hello World!';
function sendRequest() {
$.ajax({
// dummy REST API endpoint
url: "https://reqres.in/api/users",
type: "POST",
data: {
name: "Alert from AJAX success",
movies: ["I Love You Man", "Role Models"]
},
success: function(response){
console.log(response);
$json_arr = response.name;
// this window.alert will appear second
window.alert($json_arr);
}
});
}
sendRequest();
// this window.alert will appear first
window.alert($json_arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
My code is about submitting a multipart form, through $.ajax, which is successfully doing it & upon json_encode in submit.php , its giving me this :
{"success":"Image was submitted","formData":{"fb_link":"https:\/\/www.google.mv\/",
"show_fb":"1",
"filenames":[".\/uploads\/homepage-header-social-icons\/27.jpg"]}}
Can someone explain me, in submit.php, how can i extract values from formData, to store in mysql table ? I have tried, so many things including :
$fb_link = formData['fb_link'];
$show_fb = formData['show_fb'];
and
$arr = json_encode($data);
$fb_link=$arr['fb_link'];
and
$fb_link = REQUEST['fb_link'];
$show_fb = REQUEST['show_fb'];
but, nothing seems to work ? Any Guesses ?
Thanks
update :
JS code on parent-page is :
$(function()
{
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
$('form#upload_form').on('submit', uploadFiles);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
// Catch the form submit and upload the files
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
//var data = new FormData($(this)[0]);
$.ajax({
url: 'jquery_upload_form_submit.php?files=files',
type: 'POST',
data: data,
//data: {data, var1:"fb_link" , var2:"show_fb"},
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
function submitForm(event, data)
{
// Create a jQuery object from the form
$form = $(event.target);
// Serialize the form data
var formData = $form.serialize();
// You should sterilise the file names
$.each(data.files, function(key, value)
{
formData = formData + '&filenames[]=' + value;
});
$.ajax({
url: 'jquery_upload_form_submit.php',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log('SUCCESS: ' + data.success);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
},
complete: function()
{
// STOP LOADING SPINNER
}
});
}
});
UPDATE CODE OF - submit.php :
<?php
// Here we add server side validation and better error handling :)
$data = array();
if(isset($_GET['files'])) {
$error = false;
$files = array();
$uploaddir = './uploads/homepage-header-social-icons/';
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename($file['name']))) {
$files[] = $uploaddir . $file['name'];
//$files = $uploaddir . $file['name'];
}
else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your image-files') : array('files' => $files);
}
else {
$data = array(
'success' => 'Image was submitted',
'formData' => $_POST
);
}
echo json_encode($data);
?>
If you're using POST method in ajax, then you can access those data in PHP.
print_r($_POST);
Form submit using ajax.
//Program a custom submit function for the form
$("form#data").submit(function(event){
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = new FormData($(this)[0]);
$.ajax({
url: 'formprocessing.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(returndata);
}
});
return false;
});
You can access the data on PHP
$json = '{"countryId":"84","productId":"1","status":"0","opId":"134"}';
$json = json_decode($json, true);
echo $json['countryId'];
echo $json['productId'];
echo $json['status'];
echo $json['opId'];
If you want to access file object, you need to use $_FILES
$profileImg = $_FILES['profileImg'];
$displayImg = $_FILES['displayImg'];
This problem is different in terms that :
1. Its sending MULTIPLE files, to upload
2. Contains a SELECT
3. Contains an INPUT
So, images are serialized & sent via GET . And, rest FORM data is being sent via POST. So Solution is :
var data = new FormData($(this)[0]);
inside : function uploadFiles(event){}
And in submit.php :
print_r($_POST);
print_r($_GET);
die();
This will give you both values. Then comment these & as per the Code, make these changes :
$filename_wpath = serialize($files);
$fb_link = $_POST['fb_link'];
$show_fb = $_POST['show_fb'];
$sql = "INSERT INTO `tblbasicheader`(fldFB_image, fldFB_link, fldHideShow)
VALUES('$filename_wpath','$fb_link','$show_fb')";
mysqli_query($db_conx, $sql);
Works like Charm ! :)
I am new to cakephp and trying to implement AJAX . I have a view add.ctp in which I have written the following lines :
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = "http://localhost/testpage/officenames/get_office_names_by_catagory/";
$.ajax({
type: "GET",
url: url_to_call,
data = data,
//dataType: "json",
success: function(msg){
alert(msg);
}
});
}
});
And the function get_office_names_by_catagory() within OfficenamesController.php is:
public function get_office_name_by_catagory($type = '') {
Configure::write("debug",0);
if(isset($_GET['type']) && trim($_GET['type']) != ''){
$type = $_GET['type'];
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
return 'Hello !';
}
But unfortunately, its not alerting anything ! Whats wrong ?
Could be caused by two issues:
1) In your js snippet, you are querying
http://localhost/testpage/officenames/get_office_names_by_catagory/.
Note the plural 'names' in get_office_names_by_category. In the PHP snippet, you've defined an action get_office_name_by_catagory. Note the singular 'name'.
2) You may need to set your headers appropriately so the full page doesn't render on an AJAX request: Refer to this link.
I think, you have specified data in wrong format:
$.ajax({
type: "GET",
url: url_to_call,
data = data, // i guess, here is the problem
//dataType: "json",
success: function(msg){
alert(msg);
}
});
To
$.ajax({
type: "GET",
url: url_to_call,
data: { name: "John", location: "Boston" }, //example
success: function(msg){
alert(msg);
}
});
You should specify the data in key:value format.
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = "http://localhost/testpage/officenames/get_office_name_by_catagory/"+office_id;
$.ajax({
type: "GET",
url: url_to_call,
success: function(msg){
alert(msg);
}
});
}
});
In your action
public function get_office_name_by_catagory($type = '') {
$this->autoRender = false;
Configure::write("debug",0);
if(!empty($type)){
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
echo 'Hello !';
exit;
}
See what I have done is I have changed your request to function get_office_name_by_catagory, as there is one paramenter $type is already defined in the function, so if I have the request by /get_office_name_by_catagory/2 then you will find value in $type in action.
So no need to use $_GET and rest everything is fine!
Try this,
remove type from ajax and try.
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = yourlink +office_id;
**$.ajax({
url: url_to_call,
success: function(msg){
alert(msg);
}
});**
}
});
In your action
public function get_office_name_by_catagory($type = '') {
$this->autoRender = false;
Configure::write("debug",0);
if(!empty($type)){
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
echo 'Hello !';
}
My ajax call
I make an ajax call to check if the e-mail address is already used to participate. The php-file returns 0 when it is not used and 1 if it is already used. When it is used it'll make an error label to say so.
This works perfectly in Chrome, Safari, Internet Explorer. But is a complete pain in the ass in Firefox. It checks and gives the correct response, but after 5 seconds it gives a timeout.
I have another ajax call to put all the data in the database and it has the exact same problem.
What do I do wrong?
function controleerDeelnemerEmail(){
var emailVal = $('#email').val();
$.ajax( {
type: 'POST',
url:'?page=home&action=check',
dataType:'text',
data: {'email':emailVal},
success: function( data ){
data = parseInt(data);
if(data == 1){
if( $(".emailerror").length == 0 ){
var error = "<label for='email' generated='true' class='error emailerror' style=''>Dit e-mailadres wordt al gebruikt</label>"
$(error).insertBefore( $('#email') );
}
}
}
})
}
Server Side
public function check(){
if(!empty($_POST)){
$content = $this->deelnemerDAO->controleerDeelnemerEmail( $_POST['email'] );
if( $content == 1 ){
echo 1;
}else{
echo 0;
}
exit();
}
}
You should add an error callback to see if the answer returned is one.
A wrong type can be considered as an error by ajax.
function controleerDeelnemerEmail() {
var emailVal = $('#email').val();
$.ajax({
type: 'POST',
url:'?page=home&action=check',
dataType:'text',
data: {
'email': emailVal
}
}).done(function (data) {
// equivalent to success callback
data = parseInt(data);
if (data == 1) {
if ($(".emailerror").length === 0) {
var error = $("<label>", {
'for': 'email',
'generated': 'true',
'class': 'error emailerror'
}).text("Dit e-mailadres wordt al gebruikt").insertBefore($('#email'));
}
}
}).fail(function (response, status) {
alert('fail');
});
}
I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);