Here i'm doing a JSONP request, that will get an object literal passed into the callback function.
My Issue:
1.From the filename.php i'm passing two different array's like :
echo $_GET['jsoncallback'] . '(' . json_encode($manufacturers). ');';
echo $_GET['jsoncallback'] . '(' . json_encode($Stock). ');';
2.I'm receiving only one array as output at a time.
3. i need the both array .
function onLoad(){
var output = $('#product');
$.ajax({
url:'filename.php',
data : {type : 'details'},
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success:function(data){
$.each(data, function(c,prdetail){
if(prdetail.field_name=='' || prdetail.field_name==undefined )
{
var firstdata= '<h2 >'+prdetail.field_name1+ '</h2>';
output.append(firstdata);
}
else
{
var secondata ='<h2 >'+prdetail.field_name2+ '</h2>';
output.append(secondata);
}
});
}
});
}
FILENAME.PHP
if($status=1)
{
$manufacturers_sql = mysql_query('select * FROM tablename');
$rowcount = mysql_num_rows($result);
$records = array();
$row = mysql_fetch_assoc($result);
$records[] = $row;
echo $_GET['jsoncallbacks'] . '(' . json_encode($records) . ');';
}
else
{
$manufacturers_sql = mysql_query('select * FROM tablename');
$rowcount = mysql_num_rows($result);
$records = array();
$row = mysql_fetch_assoc($result);
$records[] = $row;
echo $_GET['jsoncallbacks'] . '(' . json_encode($records) . ');';
}
Try
$response = array();
$response['manufacturers'] = $manufacturers;
$response['Stock'] = $Stock;
echo $_GET['jsoncallback'] . '(' . json_encode($response). ');';
Related
I have a page which is used to search the users. If I searched an existing user, the page will redirect to my wanted page. If the user is not existing, a message must be shown. But for me the message is not showing. I know may be this is a simple error, but it's not working for me. I am using Laravel 5.8.
Error is:
Undefined offset: 0
in ClientsController.php (line 344)
at HandleExceptions->handleError.
Here is my controller:
public function getMerchantDetails() {
$user = $_GET['user'];
$mid = $_GET['mid'];
$activity = "User $user has searched this merchant";
//This is for Activity Log Capturing. Added user variable
DB::insert("INSERT INTO activitylog (mid,activity) values ('$mid','$activity')");
//Activity ends here
$mobile = $_GET['mobile'];
$email = $_GET['email'];
$m = '';
if ($mobile != '') {
$m = " AND primary_number = '" . $mobile . "' ";
}
$e = '';
if ($email != '') {
$e = " AND email = '" . $email . "' ";
}
$i = '';
if ($mid != '') {
$i = " AND mid = '" . $mid . "' ";
}
if ($m == '' && $e == '' && $i == '') {
// print_r($m);
// die();
return response()->json(array('data' => ''), 200);
} else {
$res = DB::select(DB::raw("SELECT * FROM clients WHERE 1=1 " . $m . $e . $i . " LIMIT 1"));
if (!$res) {
//$res_config = DB::select( DB::raw("SELECT * FROM configuration WHERE code = 'PERL_SEARCH_MERCHANT'") );
$perl_path = DB::select(DB::raw("SELECT * FROM configuration WHERE code = 'PERL_PATH'"));
$perl_output = exec($perl_path[0]->description . ' -merchant_id ' . $mid . ' -mobile ' . $mobile . ' -email ' . $email);
$r = json_decode($perl_output, true);
if ($r['status'] == 'success') {
if ($r['id'] != '') {
$res = DB::select(DB::raw("SELECT * FROM clients WHERE id = " . $r['id']));
} else {
$res[0]['id'] = '';
}
}
}
return response()->json(array('data' => $res[0]), 200); (line 344)
}
}
My Ajax code:
$.ajax({
"url": '{!! route('clients.fetchMerchantDetails') !!}',
async: true,
type: "GET",
data: {
mobile: mobile,
email: email,
mid: mid,
user:userid
},
success: function (response) {
var data = response.data
if(data.id!=''){
clientEditUrl = clientEditUrl.replace(':id', data.id);
window.location = clientEditUrl;
}else{
$('.searchOutputDiv').html('<h3>No merchant found!</h3>');
}
}
});
I have a case of wanting to create a div element based on the element div obtained from json response I checked in the console data successfully passed to view blade, the error is to fail add new element div based on json response obtained. Can anyone help?
my code
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
foreach ($list as $row) {
$val = array();
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}
AJAX
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (data) {
alert(data);
$('#potonganku').html(data);
},
error: function (request, status, error) {}
});
});
blade
<div id="potonganku" class="form-group row"> </div>
Best way in that case is to build markup on the client side. Return raw JSON data from controller, and then build HTML via JS.
Controller:
public function getIDpotongan($id)
{
return response()->json([
'data' => PotonganPenggajianModel::where('nip', $id)
->select('jenis_potongan', 'some_field')
->get(),
]);
}
JS
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
var buildHTML = function (data) {
var html = '';
for (i in data) {
html += '<h3>' + data[i].jenis_potongan + '</h3>';
// someting with data[i].some_field
}
return html;
};
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (response) {
$('#potonganku').html(buildHTML(response.data));
},
error: function (request, status, error) {}
});
});
You're creating a new empty $val = array(); array for every foreach. lets put it outside.
So your Controller would be:
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
$val = array();
foreach ($list as $row) {
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}
I checked if file exists using Input::hasFile('File'), and it returns true and successfully got file's binary.
But Input::file('File')->getClientOriginalExtension() returns empty string.
Here's my controller
public function ConfirmWrite()
{
if (!Session::has('id')) {
return '0:Please log in.';
}
$Data = Request::all();
$Data['uid'] = Session::get('id');
$Data['mid'] = 0;
var_dump(Input::file('File')->getClientOriginalExtension());
return '1';
if (Input::hasFile('File')) {
$file = Input::file('File');
$rules = ['File' => 'mimes:jpeg,bmp,png,jpg|max:10000'];
$validator = Validator::make(['File' => $file], $rules);
if ($validator->fails()) {
return '0:Check your File.';
}
$Data['Thumbnail'] = $file->getClientOriginalExtension();
$destinationPath = 'images/post/thumbnail/';
$Content = Post::SaveContent($Data);
if($Data['Share'] == 'true'){
$fb = FacebookHelper::WithToken(Session::get('FbToken'));
$Link = URL::to('/post').'/'.$Content;
$fb->ShareLink($Link);
}
$upload_success = $file->move($destinationPath, $Content . '.' . $Data['Thumbnail']);
echo "asdfasdfasdf : ".$Data['Thumbnail'];
if ($upload_success) {
UsefulHelper::ImageResizing($destinationPath, $Content . '.' . $Data['Thumbnail'], 320, 'small');
UsefulHelper::ImageResizing($destinationPath, $Content . '.' . $Data['Thumbnail'], 700, 'medium');
UsefulHelper::ImageResizing($destinationPath, $Content . '.' . $Data['Thumbnail'], 1920, '');
foreach (explode(',', $Data['Tag']) as $tag) {
HashTag::SaveHashTag($tag, 'post', $Content);
}
return '1:' . $Content;
} else {
return '0:Somethings wrong';
}
} else {
$Content = Post::SaveContent($Data);
if($Data['Share'] == 'true'){
$fb = FacebookHelper::WithToken(Session::get('FbToken'));
$Link = URL::to('/post').'/'.$Content;
$fb->ShareLink($Link);
}
foreach (explode(',', $Data['Tag']) as $tag) {
HashTag::SaveHashTag($tag, 'post', $Content);
}
return '1:' . $Content;
}
}
And below code is Front-end Ajax code.
var fData = new FormData;
GlobalVar.Thumbnail == '' ? '' : fData.append('File', DataURLtoBlob(GlobalVar.Thumbnail));
fData.append('Title', $('.contents-details').find('h1').html());
fData.append('Subtitle', $('.contents-details').find('h2').html());
fData.append('Content', $('#post-editor').froalaEditor('html.get'));
fData.append('Align', EditorAlign);
fData.append('Tag', Tag);
fData.append('Share',GlobalVar.FBShare);
$.ajax({
url: '{{ URL::to('/post/write') }}',
type: 'post',
processData: false,
enctype: "multipart/form-data",
contentType: false,
cache: false,
data: fData,
headers: {
'X-CSRF-Token': '{{ csrf_token() }}',
},
success: function (result) {
var Check = $.trim(result).split(':');
$('.submit-loading').css('display', 'none');
if (Check[0] == '1') {
checkUnload = false;
location.href = '{{ URL::to('post') }}/' + Check[1];
} else {
console.log(result);
Warning(Check[1]);
}
},
});
I can't find where is bug code and mistake I made. Please help me. This make me mad.
The getClientOriginalExtension method returns the extension of the actual file uploaded some-image.pdf, this is not considered a safe value. Instead you could best use guessExtension.
The guessExtension method uses the actual mime type and returns the related file type.
I tried many times but it does not work as I expect to. I have a form submit a company name back to wordpress ajax to query AD in order to get a list of users. However, everytime I hit submit button, it just loads the homepage of the website. Please look at and show me the incorrect point in my code
Here is the code in function.php
function load_scripts() {
wp_enqueue_script('jquery');
wp_register_script('directory_script',get_template_directory_uri().'/js/directory.js',array('jquery'));
wp_enqueue_script('directory_script');
wp_register_script('directory1_script',get_template_directory_uri().'/js/directory1.js',array('jquery'));
wp_enqueue_script('directory1_script');
}
add_action ('wp_enqueue_scripts','load_scripts');
// buildDirectory function
function buildDirectory () {
$Company = $_GET["companyname"];
$ad = "ad1.p.local";
$result1;
exec("ping -n 3 " . $ad, $output, $result1);
if ($result1 != 0) {
$ad = "ad2.p.local";
exec("ping -n 3 " . $ad, $output, $result1); }
elseif ($result1 != 0) {
$ad = "ad3.p.local";
exec("ping -n 3 " . $ad, $output, $result1); }
//else { echo "Unable to get contact"; }
$ldap_connection = ldap_connect($ad);
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3) or die("Unable to set LDAP protocol version");
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0);
$result;
$ldap_password = "abc";
$ldap_username = "cde";
$bind = ldap_bind($ldap_connection, $ldap_username, $ldap_password);
//$Company = "Patrick Industries";
//if (TRUE === $bind)
// {echo "Binding is successful<br />";}
//else {echo "Binding is unsuccessful<br />";}
if (TRUE === $bind) {
$ldap_base_dn = "DC=p,DC=local";
$search_filter = "(&(objectCategory=person)(objectClass=user)(company=$Company))";
$attributes = array();
$attributes[] = 'givenname';
$attributes[] = 'mail';
$attributes[] = 'samaccountname';
$attributes[] = 'sn';
$attributes[] = 'telephonenumber';
$attributes[] = 'company';
$result = ldap_search($ldap_connection, $ldap_base_dn, $search_filter, $attributes);
if (FALSE !== $result) {
$entries = ldap_get_entries($ldap_connection, $result);
// echo "<br />Found " . $entries["count"] . " entries <br />";
echo "<h4>List of contacts:</h4><br />";
echo "<table><tr>
<th style='font-weight:bold;font-size:16px;width:150px'>Name</th>
<th style='font-weight:bold;font-size:16px;width:120px'>Phone</th>
<th style='font-weight:bold;font-size:16px;width:220px'>Email</th>
<th style='font-weight:bold;font-size:16px;width:160px'>Company</th>
</tr><tr>";
$count1 = 0;
for ($x=0; $x<$entries['count']; $x++){
if (!empty($entries[$x]['givenname'][0]) &&
!empty($entries[$x]['mail'][0]) &&
!empty($entries[$x]['samaccountname'][0]) &&
!empty($entries[$x]['telephonenumber'][0]) &&
!empty($entries[$x]['sn'][0]))
{ echo "<td>". $entries[$x]['givenname'][0] . " " . $entries[$x]['sn'][0] . "</td>";
echo "<td>". $entries[$x]['telephonenumber'][0] . "</td>";
echo "<td>" . $entries[$x]['mail'][0] . "</td>";
echo "<td>". $entries[$x]['company'][0] . "</td></tr>";
$count1++; }
// { $user = $entries[$x]['givenname'][0] . " " . $entries[$x]['sn'][0] . " , " . $entries[$x]['telephonenumber'][0] . " , " . "" . $entries[$x]['mail'][0] . "" . " , " . $entries[$x]['company'][0] . " .<br />";}
}
// echo "There are " . $count1 . " contacts";
echo "</table>";
}
}
die();
}
add_action('wp_ajax_bDirectory','buildDirectory');
add_action('wp_ajax_nopriv_bDirectory','buildDirectory');
Here is js file
// Have to include in .js file
var $j = jQuery.noConflict();
var ajaxurl = "http://<ip>/wordpress/wp-admin/admin-ajax.php";
// build directory through form submission
$j("#company").submit(function(){
//var cname = $j("#cname").val();
var str = $(this).serialize();
$j.ajax({
url: ajaxurl,
type: "GET",
data: { action: "bDirectory", "cname": str },
success: function(html) {
$j("#company").replaceWith(html);
$j("#load").hide();
}
});
});
Here is HTML code
<form id="company" action="#">
<input id="cname" name="companyname" type="text"/>
<button type="submit">Submit</button>
</form>
You have to prevent the form from being submitted "the normal way":
$j("#company").submit(function(e){
e.preventDefault(); // Prevents the form default action to be triggered
var str = $(this).serialize();
$j.ajax({
url: ajaxurl,
type: "GET",
data: { action: "bDirectory", "cname": str },
success: function(html) {
$j("#company").replaceWith(html);
$j("#load").hide();
}
});
});
EDIT
In functions.php you use $_GET["companyname"]; but in your javascript you send data: { action: "bDirectory", "cname": str },, this should be corrected before anything.
I am trying to perform ajax post in laravel. I have a controller "show_freeCars" awich gets some values from ajax post and performs the query to return the results. I have this:
public function show_freeCars() {
$starttime = Input::get('starttime');
$endtime = Input::get('endtime');
$enddate = Input::get('enddate');
$startdate = Input::get('startdate');
$classes = Input::get('classes');
$free_cars = DB::select('SELECT * FROM cars WHERE id NOT IN (select distinct c.id from cars as c '
. 'left join rentals as r on c.id = r.vehicle '
. 'where STARTTIME="' . $startdate . ' ' . $starttime . '" '
. 'AND ENDTIME="' . $enddate . ' ' . $endtime . '" '
. 'AND (r.status="REZERVATION" OR r.status="CHECK_OUT") '
. 'order by c.id) AND class= "' . $classes . '" ');
if (Request::ajax()) {
$response_values = array(
'success' => 1,
'values' => $free_cars,
);
return Response::json($response_values);
} else {
dd('error');
}
}
and javascript
jQuery('#form-reservation').submit(function()
{
var startdate = $('input[name$="startdate"]').val();
var starttime = $('input[name$="starttime"]').val();
var enddate = $('input[name$="enddate"]').val();
var endtime = $('input[name$="endtime"]').val();
var classes = $('input[name$="classes"]').val();
var url = $(this).attr("action");
jQuery.ajax({
url: url,
type: "post",
data: {
startdate: startdate,
starttime: starttime,
enddate: enddate,
endtime: endtime,
classes: classes
},
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
}
})
.done(function(data)
{
$('#cars_table').empty()
if (data.success === 1)
{
var arr = data.values;
alert(arr);
}
else {
window.location = data.redirect_to;
}
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('Invalid Data');
});
return false;
});
It alerts an empty. But if i remove the lines $classes = Input::get('classes'); and AND class= "' . $classes . '" ' from controller it shows the results. The query is ok because I tested it with dd($free_cars) and it displays the list of cars. Just something is messed with ajax return values. Why it returns null?