how i must using if for this angularjs and php code - javascript

I want to make one if for doing if array result was success alart somethings in
this code: if( data.status == 'success'){ is not working!!
it was with one = but result of one = is alwase 200 , I want to check status array if was success alert ...
I testthis code: data.data.statusin other place with just one array and this code work but when i use data.data.status in bottom codes its not working !!
angularjs function code :
$scope.book = function(){
if( $scope.cabs[$scope.active_cab].intialkm >= $scope.trip_distance) {
$scope.trip_rate = $scope.cabs[$scope.active_cab].intailrate ;
}else{
var init_rate = $scope.cabs[$scope.active_cab].intailrate ;
var std_rate = ( $scope.trip_distance - $scope.cabs[$scope.active_cab].intialkm ) * $scope.cabs[$scope.active_cab].standardrate ;
$scope.trip_rate = round_num( parseFloat(init_rate) + parseFloat(std_rate) );
}
$rootScope.user_data = JSON.parse( localStorage.getItem('user_data') );
var link = 'book_cab';
var post_data = {
'user_name' : $rootScope.user_data.User_name,
'token' : $rootScope.user_data.token,
'transfertype' : "Point to Point Transfer" ,
'book_date' : $scope.book_date ,
'pickup_area' : $scope.start_box.location,
'drop_area' : $scope.end_box.location,
'taxi_type' : $scope.selected_cab.cartype,
'km' : $scope.trip_distance,
'amount' : $scope.trip_rate
}
WebService.show_loading();
var promise = WebService.send_data( link,post_data);
promise.then(function(data){
$ionicLoading.hide();
if( data.status == 'success'){
alertPopup = $ionicPopup.alert({
title: '<p class="text-center color-yellow">'+$filter('langTranslate')("SUCCESS",$rootScope.appConvertedLang['SUCCESS'])+'</p>',
template: '<p class="text-center color-gery">'+$scope.trip_distance+' KM</p>'+
'<p class="text-center color-gery"> ₹ '+$scope.trip_rate+'</p>'
});
animateMyPop();
}else{
window.alert(response.data);
window.alert(response.status);
}
});
}
php webservice :
public function book_cab(){
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$request->uneaque_id = 'CMC'.strtotime(date('m/d/Y H:i:s'));
$myDate = new DateTime();
$myDate->setTimestamp( strtotime( $request->book_date) );
$time = $myDate->format("H");
if( $time >= 22 || $time <= 6){
$request->timetype = 'night';
}else{
$request->timetype = 'day';
}
$request->book_date = $myDate->format("m/d/Y");
$request->pickup_time = $myDate->format("h:i a");
$request->token = $this->extract_token( $request->token );
var_dump($request );
$finresult = array( 'status' => 'success',
'message' => 'Successfully registered',
'code' => 'registered'
);
print json_encode($finresult);
$this->model_web_service->book($request);
}
and model_web_service:
function book( $request ){
$table = 'bookingdetails';
$insert_data = array(
'username' => $request->token,
'uneaque_id' => $request->uneaque_id,
'purpose' => "Point to Point Transfer",
'pickup_date' => $request->book_date,
'pickup_time' => $request->pickup_time,
'drop_area' => $request->drop_area,
'pickup_area' => $request->pickup_area,
'taxi_type' => $request->taxi_type,
'status' => "Booking",
// 'item_status' => "Pending",
'timetype' => $request->timetype,
'amount' => $request->amount,
'km' => $request->km
);
$this->insert_table($insert_data, $table);
}
i want to change if for read php status array (success)
plz help me for fixing this code

Related

WordPress callback function is called twice

i have been developing a WordPress plugin that has a form that sends some data to a Database.
My problem is that every time i click the submit button the callback runs twice, and the information that appears in my database is duplicated.
My jQuery code is:
$("#submit_btn").click( function (event) {
event.preventDefault();
let uuid = uuidv4()
let form_serialize = $("form").serializeArray();
let dataForm = {
"id": uuid,
'submitId': uuid
}
$.each(form_serialize, function (i, field) {
dataForm[field.name] = field.value
});
$.ajax({
url: ccandidates.ajax_url,
type: "POST",
crossDomain: true,
cache: false,
data: {
security: candidates.ajax_nonce,
action: 'SendToFormApi',
data: dataForm
},
dataType: 'json',
success: function (data, status, xhttp) {
// event.preventDefault();
if (data === true) {
window.location = candidates.merci_page_url;
} else {
window.location.href = candidates.error_page_url;
$("form").trigger('reset')
}
},
}
);
});
Callback function
function SendToFormApi_callback()
{
$formRandyValues = $_POST['data'];
$virtualagencyApiEmail = new virtualagencyApiEmail();
$result = $virtualagencyApiEmail->NyFormApi($formRandyValues);
$response = $virtualagencyApiEmail->NyFormApiCall($result,$formMyValues['id']);
$code = wp_remote_retrieve_response_code($response);
// if code 503 == service unavailable
// if code 401 == auth fail
// if code 400 == object fail
// if code 201 == success response
if ($code === 201) {
echo json_encode(true);
wp_die();
} else {
echo json_encode(false);
wp_die();
}
}
add_action('wp_ajax_SendToFormApi', 'SendToFormApi_callback', 1);
add_action('wp_ajax_nopriv_SendToFormApi', 'SendToFormApi_callback', 1);
public function NyFormApi($params): array
{
$uuidId = $params['id'] ?? $this->getUid();
$position_criteria_object = new Position_Criteria();
$position_criteria_object->type = 'string';
$position_criteria_object->label = 'besoin';
$position_criteria_object->question = 'votre_besoin';
$position_criteria_object->answer = $params['votreBesoin'];
$position_criteria_object->value = $params['votreBesoin'];
$origin_object = new Position_Criteria();
$origin_object->type = 'string';
$origin_object->label = 'origin';
$origin_object->question = 'candidature_oringin';
$origin_object->answer = 'My form';
$origin_object->value = 'My form';
$secteur_object = new Position_Criteria();
$secteur_object->type = 'string';
$secteur_object->label = 'secteur';
$secteur_object->question = 'secteur';
$secteur_object->answer = $params['secteur'];
$secteur_object->value = $params['secteur'];
$region_object = new Position_Criteria();
$region_object->type = 'string';
$region_object->label = 'region';
$region_object->question = 'region';
$region_object->answer = $params['region'];
$region_object->value = $params['region'];
$metier_object = new Position_Criteria();
$metier_object->type = 'string';
$metier_object->label = 'metier';
$metier_object->question = 'metier';
$metier_object->answer = $params['metier'];
$metier_object->value = $params['metier'];
$talent_object = new Talent();
$talent_object->id = $uuidId;
$talent_object->firstName = $params['firstName'];
$talent_object->lastName = $params['lastName'];
$talent_object->email = $params['email'];
$talent_object->phone = $params['phone'];
if(empty($params['qualificationCode'])){
$qualificationCode = "none";
} else {
$qualificationCode = $params['qualificationCode'];
}
return array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode($this->keyEncoded)
),
'body' => array(
'id' => $uuidId, //$params['id'], // str
'workTeamId' => $params['postClient'], // str
'priority' => 1, // int
'positionCriteria' => array(
$position_criteria_object,
$origin_object,
$secteur_object,
$region_object,
$metier_object
), // [{...},{...},...]
'occupationCode' => $qualificationCode, // str,
'occupationLabel' => $params['qualification'], // str
'talent' => $talent_object, // { key = value, ... }
)
);
}
public function MyFormApiCall($params, $id)
{
$url = $this->apiPathRandy . "/" . $id;
return wp_remote_post($url, $params);
}
// Get an RFC-4122 compliant globaly unique identifier
private function getUid(): string
{
$data = PHP_MAJOR_VERSION < 7 ? openssl_random_pseudo_bytes(16) : random_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // Set version to 0100
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // Set bits 6-7 to 10
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
After reading and trying some solutions that i found, no of them work in my case.
Thank you for your help.
(note: there are some vars names that were changed for privacy)
I would remove all javascript from the form and do
if ($code === 201) {
header("location: merci.html");
wp_die();
} else {
header("location: erreur.html");
wp_die();
}

How to add load more to get custom query data using ajax(WordPress)?

I am trying to load more posts from custom query loop in WordPress, I have created custom post type "Businesses" and want to load "More Businesses" on click of load more button.
I am using Visual Composer shortcode to add the content of Businesses. I have successfully created load more button to get more businesses but it's appending data inside mentioned "id" and also outside that id. I am not able to detect the issue.
Here is my code:
In functions.php I have added this localized script::
wp_localize_script( 'test-script', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => __('No older posts found', 'test'),
'page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
));
my main.js file code contains ajax call as follows::
function load_posts(data, button, wrapper, max_page, load_more_txt ="View All"){
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: data,
beforeSend : function ( xhr ) {
button.text('Loading...');
},
success: function(data){
if( data ) {
button.text( load_more_txt ).prev().before(data);
ajax_posts.page++;
wrapper.append(data);
if ( ajax_posts.page == max_page ) {
button.remove();
}
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
I have called this function on document.ready ::
$("#more_posts").on("click",function(){
var el = $("#more_posts");
// Disable the button.
el.attr("disabled",true);
var business_category = el.data('business_category');
var business_location = el.data('business_location');
var business_industry = el.data('business_industry');
var post_count = el.data('post_count');
var offset = el.data('offset');
var max_page = el.data('max_page');
//shortcode enable/disable options value
var show_business_review = el.data('show_business_review');
var show_features = el.data('show_features');
var show_buy_giftcard = el.data('show_buy_giftcard');
var show_book_online_button = el.data('show_book_online_button');
var enable_coupon_discount = el.data('enable_coupon_discount');
var show_get_free_cleaning_btn = el.data('show_get_free_cleaning_btn');
data = {
'business_category': business_category,
'business_location': business_location,
'business_industry': business_industry,
'post_count': post_count,
'offset': offset,
'page': ajax_posts.page,
'show_business_review': show_business_review,
'show_features': show_features,
'show_buy_giftcard': show_buy_giftcard,
'show_book_online_button': show_book_online_button,
'enable_coupon_discount': enable_coupon_discount,
'show_get_free_cleaning_btn': show_get_free_cleaning_btn,
'action': 'more_post_ajax'
}
var wrapper = $("#marketplace-businesses");
var loadMoreTxt = "View All";
// call load more posts function
load_posts(data, el, wrapper, max_page, loadMoreTxt);
});
After this I have added function to get ajax data and load new posts::
function more_post_ajax(){
header("Content-Type: text/html");
$business_category = (isset($_POST['business_category'])) ? $_POST['business_category'] : '';
$business_location = (isset($_POST['business_location'])) ? $_POST['business_location'] : '';
$business_industry = (isset($_POST['business_industry'])) ? $_POST['business_industry'] : '';
$post_count = (isset($_POST['post_count'])) ? $_POST['post_count'] : 2;
$page = (isset($_POST['page'])) ? $_POST['page'] + 1 : 1;
$offset = (isset($_POST['offset'])) ? $_POST['offset'] : '';
// shortcode enable disable options
$show_business_review = (isset($_POST['show_business_review'])) ? $_POST['show_business_review'] : true;
$show_features = (isset($_POST['show_features'])) ? $_POST['show_features'] : true;
$show_buy_giftcard = (isset($_POST['show_buy_giftcard'])) ? $_POST['show_buy_giftcard'] : true;
$show_book_online_button = (isset($_POST['show_book_online_button'])) ? $_POST['show_book_online_button'] : true;
$enable_coupon_discount = (isset($_POST['enable_coupon_discount'])) ? $_POST['enable_coupon_discount'] : true;
$show_get_free_cleaning_btn = (isset($_POST['show_get_free_cleaning_btn'])) ? $_POST['show_get_free_cleaning_btn'] : true;
if($business_category != "") {
$args = array(
'tax_query' => array(
'relation' => 'AND',
array('taxonomy' => 'business_location', 'field' => 'slug', 'terms' => array($business_location)),
array('taxonomy' => 'business_industry', 'field' => 'slug', 'terms' => array($business_industry)),
array('taxonomy' => 'business_category', 'field' => 'slug', 'terms' => $business_category)),
);
} else {
$args = array(
'tax_query' => array(
'relation' => 'AND',
array('taxonomy' => 'business_location', 'field' => 'slug', 'terms' => array($business_location)),
array('taxonomy' => 'business_industry', 'field' => 'slug', 'terms' => array($business_industry)),
),
);
}
$args['post_type'] = 'business';
$args['posts_per_page'] = $post_count;
$args['post_status'] = 'publish';
$updated_offset = (($page - 1) * $post_count);
$args['offset'] = $updated_offset;
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) :
while ($loop -> have_posts()) : $loop->the_post(); $post_id = get_the_ID();
$out .= '<div class="businesses-wrap-content mb-10">';
$out .= '<div class="d-flex">';
$out .= '<div class="content-wrap pr-15"><div class="business-title"><h5 class="text-dark mb-2">'.get_the_title().'</h5>';
$out .= '</div></div>'; // content-wrap pr-15 closed
$out .= '</div>'; // d-flex closed
$out .= '</div>';
endwhile;
endif;
wp_reset_postdata();
die($out);
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
Now it gives output as::
--appended data
<div id="marketplace-businesses">
--appended data
</div>
On click of load more button, it shows output two times, one is outside the wrapper div and another one as the last child of wrapper div.
How can I show load more data only as the last child of wrapper div? What I have done wrong here?
I have used button.text( load_more_txt ).prev().before(data); and it will duplicate data for me. Now I just used button.text( load_more_txt ); to display button text after loading. Check this function now.
function load_posts(data, button, wrapper, max_page, load_more_txt ="View All"){
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: data,
beforeSend : function ( xhr ) {
button.text('Loading...');
},
success: function(data){
if( data ) {
//button.text( load_more_txt ).prev().before(data);
button.text( load_more_txt );
ajax_posts.page++;
wrapper.append(data);
if ( ajax_posts.page == max_page ) {
button.remove();
}
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
This resolves my problem.

ajax send data based on checkbox value

I need to send ajax requests with checkbox values (on each click/check). I have three lists with checkboxes, each list filters the data returend from php (with mysql AND condition):
$('body').on('click', '.click, :checkbox, .pag_link', function() {
var self = this;
// radio buttons
if ($('#res_prop').is(':checked')) {
var use = $('#res_prop').val();
}
else if ($('#com_prop').is(':checked')) {
var use = $('#com_prop').val();
}
else {
$('p.error').show();
die();
}
//checkboxes from each list have the same class, is this ok?
if ($(self).is(':checkbox')) {
$(self).on('change', function() {
if ($(self).prop('class') == 'filter1' || $('.filter1').is(':checked')) {
if ($('.filter1').is(':checked'))
var type = $(self).val(); // maybe should be an array
else var type = null;
} else var type = null;
if ($(self).prop('class') == 'filter2' || $('.filter2').is(':checked')) {
if ($('.filter2').is(':checked'))
var status = $(self).val(); // maybe should be an array
else var status = null;
} else var status = null;
if ($(self).prop('class') == 'filter3' || $('.filter3').is(':checked')) {
if ($('.filter3').is(':checked'))
var bhk = $(self).val(); // maybe should be an array
else var bhk = null;
} else var bhk = null;
});
}
else {
var type = status = bhk = null;
}
if ($(self).is('.pag_link')) {
if ($(self).text() == '«')
var page = (parseInt($('.active').text()) - 1);
else if ($(self).text() == '»')
var page = (parseInt($('.active').text()) + 1);
else
var page = parseInt($(self).text());
}
else {
var page = 1;
}
$.ajax({
method: 'POST',
url: '/search',
data: {
'do': getUrlParameter('do'),
'use': use,
'type': type,
'status': status,
'bhk': bhk,
'city': $('select[name="city"]').val(),
'zone': $('select[name="zone"]').val(),
'page': page
}
}).done(function(data) {
if ($( '#search' ).is(':visible'))
$( '#search' ).hide();
if ($(self).is(':checkbox')) {
alert('should work');
var new_content = $(data).find( '#scroll-to-list' );
$( '#scroll-to-list' ).replaceWith( new_content );
}
else {
var new_content = $(data).find( '#search-filters, #scroll-to-list' );
$( '#results' ).html( new_content );
$( 'html, body' ).animate({
scrollTop: $( '#scroll-to-list' ).offset().top
}, 1000);
}
});
});
I'm looking on each click/check to do the ajax request and print the new results (relying on server is performance-wise?). If checked, the variable gets the value and is sent, if unchecked the variable gets null. The search.php script handles the mysql Select query (with ifs adding the AND conditions to the query).
I just have 1 example in the db but the checkboxes script is not working (or the mysql select query is not including the and condition, i think the problem is in the jquery, the php script is fine).
$use = isset( $_POST['use'] ) ? (int) $_POST['use'] : ''; // int AJAX
$filter_type = isset( $_POST['type'] ) ? (int) $_POST['type'] : ''; // int AJAX
$filter_status = isset( $_POST['status'] ) ? (int) $_POST['status'] : ''; // int AJAX
$filter_bhk = isset( $_POST['bhk'] ) ? (int) $_POST['bhk'] : ''; // int AJAX
$filter_city = isset( $_POST['city'] ) ? (int) $_POST['city'] : 0; // int AJAX
$filter_zone = isset( $_POST['zone'] ) ? (int) $_POST['zone'] : 0; // int AJAX
$page_number = isset( $_POST['page'] ) ? (int) $_POST['page'] : ''; // int AJAX
if ($filter_type != NULL || $filter_type != '') {
$filter_type = 'AND t2.type = ' . $filter_type;
} else $filter_type = NULL;
if ($filter_status != NULL || $filter_status != '') {
$filter_status = 'AND t2.status = ' . $filter_status;
} else $filter_status = NULL;
if ($filter_bhk != NULL || $filter_bhk != '') {
$filter_bhk = 'AND t2.bhk = ' . $filter_bhk;
} else $filter_bhk = NULL;
if ($filter_city > 0) {
$filter_city = 'AND t2.city = ' . $filter_city;
$filter_zone = NULL;
if ($filter_zone > 0) {
$filter_zone = 'AND t2.zone = ' . $filter_zone;
}
} else $filter_city = $filter_zone = NULL;
if ($stmt = $mysqli->prepare(' SELECT t1.id, t2.*
FROM ' . $table . ' t1 // not from get/post
INNER JOIN property t2 ON t2.id = t1.id
WHERE t2.use = ?
' . $filter_type
. $filter_status
. $filter_bhk
. $filter_city
. $filter_zone . '
LIMIT ?, ?')) {
$stmt->bind_param('iii', $use, $start, $limit);
$stmt->execute();
I just found this JQuery method .serialize()... and it changed my life :)
$('body').on('click', '.click, :checkbox, .pag_link', function() {
var self = this;
if (!$(':radio').is(':checked')) {
$('p.error').show();
die();
}
var data = $('input, select').serializeArray(),
mode = getUrlParameter('do'),
page = 1;
if ($(self).is('.pag_link')) {
if ($(self).text() == '«')
page = (parseInt($('.active').text()) - 1);
else if ($(self).text() == '»')
page = (parseInt($('.active').text()) + 1);
else
page = parseInt($(self).text());
}
data.push({ name : 'do', value : mode});
data.push({ name : 'page', value : page});
alert($.param(data));
$.ajax({
method: 'POST',
url: '/search',
data: $.param(data)
}).done(function (data) {
if ($( '#search' ).is(':visible'))
$( '#search' ).hide();
if ($(self).is(':checkbox')) {
var new_content = $(data).find( '#scroll-to-list' );
$( '#scroll-to-list' ).replaceWith( new_content );
}
else {
var new_content = $(data).find( '#search-filters, #scroll-to-list' );
$( '#results' ).html( new_content );
$( 'html, body' ).animate({
scrollTop: $( '#scroll-to-list' ).offset().top
}, 1000);
}
});
});
Hope it helps someone.

Jquery file uploading JSON empty error

I'm following these videos (https://www.youtube.com/watch?v=Be-GSVO7PGQ&index=9&list=PLfdtiltiRHWHCzhdE0N1zmeFHlEuqxQvm) to create a jquery upload page to my website.
I get the following error on Chrome:
Uncaught SyntaxError: Unexpected end of input
And I get the following error on Firefox Firebug:
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
Currently, my code looks like this:
upload.php:
<form action="upload_process.php" method="post" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend><h3>Upload files</h3></legend>
<input type="file" id="file_upload" name="file_upload[]" required multiple>
<input type="submit" id="submit_upload" name="submit_upload" value="Upload">
<div class="bar">
<span class="bar-fill" id="pb"><span class="bar-fill-text" id="pt">40%</span></span>
</div>
<div id="uploads" class="uploads">
Uploaded files will appear here.
</div>
</fieldset>
</form>
<script src="js/upload.js"></script>
<script>
document.getElementById('submit_upload').addEventListener('click', function(e) {
e.preventDefault();
var f = document.getElementById('file_upload'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files: f,
progressBar: pb,
progressText: pt,
processor: 'upload_process.php',
finished: function(data) {
console.log(data);
},
error: function() {
console.log('not working');
}
});
});
</script>
upload.js
var app = app || {};
(function(o) {
"use strict";
var ajax, getFormData, setProgress;
ajax = function(data) {
var xmlhttp = new XMLHttpRequest(), uploaded;
xmlhttp.addEventListener('readystatechange', function() {
if (this.readyState === 4) {
if (this.status === 200) {
uploaded = JSON.parse(this.response);
console.log(uploaded);
}
if (typeof o.options.finished === 'function') {
o.options.finished(uploaded);
}
} else {
if (typeof o.options.error === 'function') {
o.options.error(uploaded);
}
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source) {
var data = new FormData(), i;
for(i = 0; i < source.length; i = i + 1) {
data.append('file[]', source[i]);
}
data.append('ajax', true);
};
setProgress = function(value) {
};
o.uploader = function(options) {
o.options = options;
if (o.options.files !== undefined) {
ajax(getFormData(o.options.files.files));
}
};
}(app));
and my upload_process.php
<?php
//require_once('core/init.php');
header('Content-Type: application/json');
$uploaded = [];
$allowed = ['mp4', 'png', 'bmp', 'mp3', 'txt'];
$succeeded = [];
$failed = [];
if (!empty($_FILES['file_upload'])) {
foreach($_FILES['file_upload']['name'] as $key => $name) {
if ($_FILES['file_upload']['error'][$key] === 0) {
$temp = $_FILES['file_upload']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() . '.' . $ext;
if (in_array($ext, $allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
$succeeded[] = array(
'name' => $name,
'file' => $file
);
$db = new DB();
$user = new User();
$units = new Units();
$size = filesize("uploads/" . $file);
$formattedSize = $units->formatSizeUnits($size);
$db->insert('files', array(
'user_id' => $user->data()->id,
'name' => $name,
'size' => $formattedSize,
'address' => 'uploads/' . $file . '',
'created' => date('Y-m-d H:i:s'),
'type' => $ext
));
/*Redirect::to('index');
Session::flash('');*/
} else {
$failed[] = array(
'name' => $name
);
}
}
}
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeeded' => $succeeded,
'failed' => $failed
));
}
}
I know that the problem is propably that this:
uploaded = JSON.parse(this.response);
this.response returns nothing.
I just can't figure out why it returns nothing.

Jquery ajax function fails with no reason

I have a web based mobile android application. I built it with php + jquery + mysql. An ajax code fails but no reason. Therefore it returns 'Try again'. Unfortunately I can not debug it in the application. Here is the code:
$('.get-order-button').live('click', function() {
var musteritel = $('#musteritel').val(), musteriad = $('#musteriad').val(), musteriadres = $('#musteriadres').val(), musterinotu = $('#siparisnotu').val(), odemesekli =$('#odemesekli option:selected').val() ;
if(musteritel != ''){
$.ajax({
type : 'POST',
url : '/enfes/temp-order-sent.php', timeout: 10000,
cache : false,
data : 'musteritel='+musteritel+'&musteriadres='+musteriadres+'&musterinotu='+musterinotu+'&odemesekli='+odemesekli+'&musteriad='+musteriad,
dataType : 'json',
beforeSend : function() {
showDialog('Yükleniyor...')
},
whileLoading: function(xhr) {
if (xhr && xhr.readyState != 4)
xhr.abort()
}
}).always(function() {
closeDialog()
}).fail(function() {
showToastShort('Try again.');
}).done(function(r) {
if(r.s==1){
$.each(r.u, function( index, value ) {
unsetMyCookie(index);
});
$('#detail').remove();
$('.basket-added-btn span').text('0');
basketStatus = 0;
showToastLong(r.m);
window.location.hash = 'home';
}else
showToastShort(r.m);
});
}
return false
});
And here is the php code:
<?php
session_start();
include_once 'class.render.php';
include_once 'class.order.php';
$kendim = new render();
if(isset($_SESSION["id"]) && isset($_POST['musteritel'])) {
$kendiId = $_SESSION["kendiId"];
$uniqueIdentifier = $_SESSION["uniqueIdentifier"];
if(isset($_COOKIE)){
$order = new order();
$musteritel = $order->validTel($_POST['musteritel']);
$musteriad = $order->cleanStr($_POST['musteriad']);
$musteriadres = $order->cleanStr($_POST['musteriadres']);
$musterinotu = $order->cleanStr($_POST['musterinotu']);
$odemesekli = $order->cleanStr($_POST['odemesekli']);
$return = array('s' => 0, 'm' => 'Siparis gonderilemedi. Bilgilerinizi kontrol ediniz.');
$ordersent = $order->addOrder($musteritel, $musteriad, $musteriadres, $musterinotu, $odemesekli);
if($musteritel == "") {
$return = array('s' => 1, 'm' => 'Telefon numaranızı hatalı girdiniz.');
} else {
if($ordersent){
$return = array('s' => 1, 'm' => 'Siparisiniz bize ulasmistir.', 'u' => $order->basket);
}else
$return = array('s' => 0, 'm' => 'Siparis gonderilemedi. Bilgilerinizi kontrol ediniz.');
}
}else
$return = array('s' => 0, 'm' => 'Siparis sepetiniz bos.');
}else
$return = array('s' => 0, 'm' => 'Telefon numaranızı yazmalisiniz.');
echo json_encode($return);
?>
Why does it fail?

Categories

Resources