Ajax multiple response - ajax

I need to fetch the names using mysql query for which I'm trying to send some values via ajax to php.
Js file:
var dataselect = 'catg='+ $('#catg_list').val() + '&brand='+ $('#brand_list').val(); // get data in the form manual
$.ajax({
type="POST",
url:"check.php"
data: dataselect,
success: function(data) {
alert (data);
}
});
check.php file
<?php
include(database connection);
$catg_list= $_POST['catg'];
$brand_list= $_POST['brand'];
if ($catg_list!="") {
$catg_query = mysql_query("SELECT name FROM categories WHERE id='$catg_list'");
if ($catg_query) {
while ($row_catg=mysql_fetch_assoc($catg_query)) {
echo $row_catg['name'];
}
}
}
if ($brand_list!="") {
$brand_list = mysql_query("SELECT name FROM brand WHERE id='$brand_list'");
if ($brand_list) {
while ($row_brand=mysql_fetch_assoc($brand_list)) {
echo $row_brand['name'];
}
}
}
?>
Problem is I need to display both the above names separately in . Is it possible? I am very much new to ajax. Any help would be great.
Thanks

You should be sending your data back in JSON format. You can send back a JSON object, which is like an associative array in PHP. You could use this php code:
<?php
include(database connection);
$catg_list= $_POST['catg'];
$brand_list= $_POST['brand'];
$results = array('categories' => array(), 'brands' => array());
if ($catg_list!="") {
$catg_query = mysql_query("SELECT name FROM categories WHERE id='$catg_list'");
if ($catg_query) {
while ($row_catg=mysql_fetch_assoc($catg_query)) {
$results['categories'][] = $row_catg['name'];
}
}
}
if ($brand_list!="") {
$brand_list = mysql_query("SELECT name FROM brand WHERE id='$brand_list'");
if ($brand_list) {
while ($row_brand=mysql_fetch_assoc($brand_list)) {
$results['brands'][] = $row_brand['name'];
}
}
}
echo json_encode($results);
?>
Then, in your javascript success function, your data variable will be an object with two fields, each containing an array.
{
categories: [],
brands: []
}
You can access them by iterating over data.categories and data.brands.
Lastly, do not use SQL statements with data straight from your $_POST array. You have to sanitize that.
js
var dataselect = 'catg='+ $('#catg_list').val() + '&brand='+ $('#brand_list').val(); // get data in the form manual
var x, y;
$.ajax({
type="POST",
url:"check.php"
data: dataselect,
success: function(data) {
var x = data.categories[0];
var y = data.brand[0];
}
});

Related

Unable to read filelist object in Laravel controller from vue

I'm creating an application where user is filing up a form with possibility to send multiple files along
In vue.js I'm creating formData with an array of files and with an object with the rest of inputs fields. I'm posting that with Axios.
In request in Laravel controller I can't access my filelist-object.
I can see the
$request->My_Array,
but I can read the data store inside
I have tried to use loops also I have try :
$request->all();
$request->file('files');
My input
<input class="browse" V-on::change="onImageChange" type="file">
My vue.js component
onImageChange(event) {
this.files.push(event.target.files);
},
submit(e) {
e.preventDefault();
let currentObj = this;
const fd = new FormData();
for (let i = 0; i < this.files.length; i++) {
fd.append('IoFiles[]', this.files[i]);
}
console.log(this.files);
fd.append('IoFiles', this.files);
fd.append('fields', JSON.stringify(this.fields));
axios.post('/io',
fd,
{headers: {'Content-Type': 'multipart/form-data'}})
.then(function (response) {
currentObj.output = response.data;
})
.catch(function (error) {
currentObj.output = error;
});
},
My Laravel controller
public function store(Request $request)
{
if ($request->IoFiles) {
$medias = $request->IoFiles;
foreach ($medias as $image) {
return $image->getClientOriginalName();//That give me an error
}
}
}
There are a couple of issues with your code.
Firstly, V-on::change="onImageChange" should be:
v-on:change="onImageChange"
Please note:
the lowercase v for v-on
the single :
Alternatively, you could write #change="onImageChange".
Secondly, event.target.files returns a FileList not a single file so you need to change your onImageChange code to the following be able to get the file itself:
onImageChange(event) {
this.files.push(event.target.files[0]); //Note the [0] after files
},

submit form if don't have error

i am using ajax for send active form by this function
public function Link()
{
$id=$this->params['id'];
$url=$this->params['url'];
$dviId=$this->params['divId'];
$url=Yii::$app->urlManager->createAbsoluteUrl($url);
$js2="$('#".$id."').on('click', function() { $.ajax({url: '".$url."',type: 'POST',success : function(res){ $('#".$dviId."').html(res);}});});";
$view = $this->getView();
AjaxAsset::register($view);
if ($js2 !== '') {
$view->registerJs($js2);
}
return ;
}
And want to show error if any happened else send form
There is a plugin in jquery to do client side validation if you are using javascript and want to do initial validation of the form.
http://jqueryvalidation.org/
Also you can use "required" attribute in your text tags to do some intial checks. More can be found here:
http://www.w3schools.com/tags/att_input_required.asp
Hope this helps a bit.
You can also set enableAjaxValidation to true in your form.
There is an example in the docs about that (see the controller part).
public function Link()
{
$id=$this->params['id'];
$url=$this->params['url'];
$dviId=$this->params['divId'];
if(isset($this->params['confirm'])) {
$confirm = "if(confirm('".$this->params['confirm']."')){";
$endConfirm = "}";
}
else
{
$confirm = "";
$endConfirm = "";
}
$url=Yii::$app->urlManager->createAbsoluteUrl($url);
$js2="$('#".$id."').on('click', function() {".$confirm."$.ajax({url: '".$url."',type: 'POST',beforeSend: function(){ $('body').addClass('wait');},complete: function(){ $('body').removeClass('wait');},success : function(res){ $('#".$dviId."').html(res);}});".$endConfirm."});";
$view = $this->getView();
AjaxAsset::register($view);
if ($js2 !== '') {
$view->registerJs($js2);
}
return ;
}

Bootstrap Typeahead with AJAX source (not working)

I'm trying to implement a search bar dropdown using bootstrap v3.0.0 with typeahead.js.
My search bar will take a student's firstname and lastname. I'm using a MYSQL database which consists of a table called practice with afirstname, alastname, aid as columns. The search bar should not only contain the firstname and lastname in the dropdown, but also the id associated with it in a second row. I've read all the examples on the typeahead.js page and I'm unable to do it with ajax call.
Below is the code of my index.php
JS
<script type="text/javascript">
$(document).ready(function() {
$('.cr.typeahead').typeahead({
source: header: '<h3>Select</h3>',
name: 'accounts',
source: function (query, process) {
return $.getJSON(
'localhost/resultly/source.php',
{ query: query },
function (data) {
return process(data);
});
});
});
</script>
HTML:
<body>
<div class="container">
<br/><br/>
<input type="text" name="query" class="form-control cr typeahead" id="firstname" />
<br/><br/>
</div>
</body>
Code for source.php : This should return the firstname and lastname from my database in the form of a json string or object?
<?php
$query = $_POST['query'];
try {
$conn = new PDO('mysql:host=localhost;dbname=practice','root','');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM actualtable WHERE afirstname LIKE '%($query)%'");
$stmt->execute();
}
catch (PDOException $e) {
echo 'ERROR:' . $e->getMessage();
}
foreach ($stmt as $row) {
$afirstname[] = $row['afirstname'];
$alastname[] = $row['alastname'];
}
echo json_encode($afirstname);
echo json_encode($alastname);
?>
result:
http://oi41.tinypic.com/50moi1.jpg
Nothing shows up. I've tried adding a prefetch:
prefetch: {
url: 'localhost/resultly/source.php',
filter: function(data) {
r1 = [];
for (var i = 0; i < data.length; i++) {
r1.push({
value: data[i].afirstname,
tokens: [data[i].afirstname, data[i]alastname],
afirstname: data[i].afirstname,
alastname: data[i].alastname,
template: '<p>{{afirstname}} - {{alastname}}</p>',
});
}
return r1;
}
}
Please do provide a solution or an example which I could refer.
Update:
The source.php should return a list of json encoded data. I debugged by looking at the output that the source.pho created. What I did wrong was whenever I was supposed to put a url I did localhost/source.php instead of just source.php.
Solution provided by Bass Jobsen works and now I have run into another problem.
I'm using
if(isset($_POST['query']))
{ $q_uery = $_POST['query'];
$query = ucfirst(strtolower($q_uery))};
to take the user's data and use it for searching logic
$stmt = $conn->prepare("SELECT * FROM actualtable WHERE afirstname LIKE '%($query)%'");
The updated source.php is http://pastebin.com/T9Q4m10g
I get an error on this line saying Notice: Undefined variable: stmt I guess the $query is not being initialized. How do I get this to work. Thanks.
Update 3
I used prefetch: instead of 'remote:' that did all the matching.
Your return is not correct:
echo json_encode($afirstname);
echo json_encode($alastname);
See for example Twitter TypeAhead.js not updating input
Try echo json_encode((object)$stmt);, see: typeahead.js search from beginng
Update
I tried echo json_encode((object)$stmt);still doesn't work.
Do you use any kind of debugging? What does? source.php return? Try to follow the steps from
typeahead.js search from beginng without the filter.
html:
<div class="demo">
<input class="typeahead" value="" type="text" spellcheck="off" autocomplete="off" placeholder="countries">
</div>
javascript:
$('.typeahead').typeahead({
remote: 'http://testdrive/source.php?q=%QUERY',
limit: 10
});
php (source.php):
<?php
$people = array();
$people[] = array("lastname"=>"Inaw",
"firstname"=>"Dsajhjkdsa");
$people[] = array("lastname"=>"Dsahjk",
"firstname"=>"YYYsgbm");
$people[] = array("lastname"=>"Dasjhdsjka",
"firstname"=>"JHJKGJ");
$datums = array();
foreach($people as $human)
{
$datums[]=(object)array('value'=>$human['firstname'],'tokens'=>array($human['firstname'],$human['lastname']));
}
echo json_encode((object)$datums);
This should work
update2
Thanks, it worked. How do I display 2 or more 'value'?
add some values to your datums in source.php:
foreach($people as $human)
{
$datums[]=(object)array
(
'value'=>$human['firstname'],
'tokens'=>array($human['firstname'],$human['lastname']),
'firstname'=>$human['firstname'],
'lastname'=>$human['lastname']
);
}
firstname and lastname now are field you csn use in your templates
Add a template and template engine to your javascript declaration:
$('.typeahead').typeahead({
remote: 'http://testdrive/source.php?q=%QUERY',
limit: 10,
template: [
'<p>{{firstname}} - {{lastname}}</p>'
].join(''),
engine: Hogan
});
The above make use of https://github.com/twitter/hogan.js. You will have to include the template engine by javascript, for example:
<script src="http://twitter.github.io/typeahead.js/js/hogan-2.0.0.js"></script>
It is working for me. please follow below step.
Please add below Js and give proper reference.
bootstrap3-typeahead
--- Ajax Call ----
$("#cityId").keyup(function () {
var al = $(this).val();
$('#cityId').typeahead({
source: function (valuequery, process) {
var states = [];
return $.ajax({
url: http://localhost:4000/GetcityList,
type: 'POST',
data: { valueType: "", valueFilter: valuequery },
dataType: 'JSON',
success: function (result) {
var resultList = result.map(function (item) {
states.push({
"name": item.Value,
"value": item.Key
});
});
return process(states);
}
});
},
});
});
---- Cs Code ---
public JsonResult SearchKeyValuesByValue(string valueType, string valueFilter)
{
List<KeyValueType> returnValue = SearchKeyValuesByValue(valueType, valueFilter);
return Json(returnValue);
}
Auto suggest of Bootstrap typehead will get accept only "name" and "value" so create reponse accordinly

AJAX Form will only either show success message OR post data to database not both

I am using Codeigniter as my framework and have a simple contact form. This uses the form helper and i have used AJAX and a fallback in the controller if AJAX is not present.
At the moment, my code with only either show the success message from the ajax form OR post the data to the database depending on if i change them around in the controller - my error messages work fine.
I am confused to how it will not both post and show success message - i think i may be missing something in my controller or AJAX request?
Here is my code as a guidance and if anyone can spot anything that would be great as it's getting on my nerves now!
*The code i am posting now lets the data be posted into the database. When i move the post data elements below this -> return $this->output->set_output(json_encode($respond)); It doesn't post to the database but shows the success message and vice versa.
CONTROLLER,
// if ajax request
if($this->input->is_ajax_request()) {
$respond = array();
if($this->form_validation->run() == FALSE) {
$respond['result'] = 'false';
$respond['error_message'] = $error_message;
$respond['errors'] = validation_errors();
// set individual errors - for warning classes
$respond['first_name_error'] = form_error('first_name');
$respond['country_error'] = form_error('country');
$respond['email_error'] = form_error('email');
$respond['message_error'] = form_error('message');
} else {
$respond['result'] = 'true';
$respond['success_message'] = $success_message;
// add contact message to the database
$this->contact_model->insert_contact_message($curr_lang, $this->input->post('first_name'), $this->input->post('country'), $this->input->post('email'), $this->input->post('phone'), $this->input->post('message'));
}
return $this->output->set_output(json_encode($respond));
} else {
// if ajax request failed - use CI
if($this->form_validation->run() == FALSE) {
$data['error_message'] = $error_message;
$data['errors'] = validation_errors();
} else {
// add contact message to the database
$this->contact_model->insert_contact_message($curr_lang, $this->input->post('first_name'), $this->input->post('country'), $this->input->post('email'), $this->input->post('phone'), $this->input->post('message'));
$data['success_message'] = $success_message;
}
}
// set field labels
$data['first_name'] = $first_name;
$data['country'] = $country;
$data['email'] = $email;
$data['phone'] = $phone;
$data['message'] = $message;
// initialize view name
$data['content'] = $page;
// load the view
$this->load->view('template', $data);
}
AJAX
$('#submit').click(function(e) {
e.preventDefault();
// send the form data to the controller
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data: $('form').serialize(),
dataType: 'json',
success: function(respond) {
if(respond.result === 'false'){
// function to add warning class
function add_error(response, field){
if(response){
$(field).addClass('warning');
}
}
// add warning classes - doing this individually as some inputs have more than one error message
add_error(respond.first_name_error, 'input[name="first_name"]');
add_error(respond.country_error, 'input[name="country"]');
add_error(respond.email_error, 'input[name="email"]');
add_error(respond.message_error, 'textarea');
// post all errors to the view
var error_msg = respond.error_message + respond.errors;
$('#error_message').html(error_msg);
}
if(respond.result === 'true'){
// empty the form
$('#error_message').empty();
$('form').find("input[type=text], textarea").val('');
// set the success message
var success_msg = respond.success_message;
$('#success_message').html(success_msg).fadeOut(6000);
}
}
});
return false;
});
It's likely because you aren't parsing the JSON response so your if statements will never be true (as respond.result is probably evaluating to 'undefined').
In your Ajax respond.result === true or false not 'true' or 'false'. You just need to remove the quotes because it is a Boolean not a string.

Ajax.request not working

I am sorting a list using scriptaculous, i can't get the ajax request part to work.
This is my code:
<script type="text/javascript">
Sortable.create("images_list", {
onUpdate: function() {
var list = Sortable.serialize("images_list");
alert(list);
new Ajax.Request('processor.php', {
method: 'post',
parameters: { data: list }
});
}
});
I Have alerted out the serialize string, this part is working fine:
images_list[]=18&images_list[]=19&images_list[]=21&images_list[]=22&images_list[]=20
So the sorting is working fine, however the data string doesn't seem to be available in the processor.php
<?php
//Connect to DB
require_once('connect.php');
parse_str($_POST['data']);
for ($i = 0; $i < count($images_list); $i++) {
$id = $images_list[$i];
mysql_query("UPDATE images SET ranking = '$i' WHERE id = '$id'");
}
?>
Any ideas why the data is not getting posted? I have tested to see if the processor.php page is actualy being invoked, and it is.
Thank you
When method = 'post', you need to use "postBody" instead of "parameters" for having parameters posted to your server side script

Resources