Display new row inserted after ajax callback - php

Here there is my code which insert a row in ajax, it's working perfectly.
I need to display the new row that the user inserted inside my select multiple without reload the page but i don't know how to do ..
Thank you for you help
Ajax call :
$('#insertForm').on('click', function(){
var form_user = $('input[name=form_user]').val();
var form_intitule = $('input[name=form_intitule]').val();
var form_organisme = $('input[name=form_organisme]').val();
var form_date = $('input[name=form_date]').val();
var form_benefice = $('textarea[name=form_benefice]').val();
var form_dispositif = $('#form_dispositif').val();
var form_entpro_ActionAutre = $('input[name=entpro_ActionAutre]').val();
$.ajax({
type: "GET",
url: "lib/function.php?insertForm="+insertForm+"&form_user="+form_user+"&form_intitule="+form_intitule+"&form_organisme="+form_organisme+"&form_date="+form_date+"&form_benefice="+form_benefice+"&form_dispositif="+form_dispositif+"&form_entpro_ActionAutre="+form_entpro_ActionAutre,
dataType : "html",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + '--' + textStatus + '--' + errorThrown);
},
success:function(data){
}
});
});
My select multiple in function.php :
$displayFormation = $bdd->prepare('SELECT * FROM FORMATION WHERE form_id_user = :idSalarie ORDER BY form_date DESC');
$displayFormation->bindParam(':idSalarie', $_POST['idSalarie']);
$displayFormation->execute();
$data['formation'] .='
<div class="form-group">
<label for="nomSalarie" class="col-sm-1 control-label" id="nameSelect">Formations</label>
<div class="col-sm-11">
<select name="listeFormation[]" id="listeFormation" class="form-control" multiple>';
while($ligne = $displayFormation->fetch()){
$data['formation'] .='<option value="'. $ligne['form_id'].'">'.$ligne['form_intitule']. " [" . $ligne['form_organisme'] . "]". " [Année : " . dateAnglaisVersFrancaisAnnee($ligne['form_date']) . "]" . " [Bénéfices : " . $ligne['form_benefice'] . "]" . " [Dispositif : " . $ligne['form_dispositif'] . "]".'</option>';
}
$data['formation'] .='
</select>
</div>
</div>';

I am going to make some guesses and also some suggestions. Without knowing what your resulting data is going to be, it's hard to answer fully.
My working example and tests: https://jsfiddle.net/Twisty/053q24dh/
Here is the JQuery I would advise:
$('#insertForm').on('click', function() {
var form_user = $('input[name=form_user]').val();
var form_intitule = $('input[name=form_intitule]').val();
var form_organisme = $('input[name=form_organisme]').val();
var form_date = $('input[name=form_date]').val();
var form_benefice = $('textarea[name=form_benefice]').val();
var form_dispositif = $('#form_dispositif').val();
var form_entpro_ActionAutre = $('input[name=entpro_ActionAutre]').val();
$.ajax({
type: "GET",
url: "lib/function.php",
data: {
"insertForm": insertForm,
"form_user": form_user,
"form_intitule": form_intitule,
"form_organisme": form_organisme,
"form_date": form_date,
"form_benefice": form_benefice,
"form_dispositif": form_dispositif,
"form_entpro_ActionAutre": form_entpro_ActionAutre,
},
dataType: "html",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + '--' + textStatus + '--' + errorThrown);
},
success: function(data) {
// Asumming the page returns the following HTML, or something similar:
// <option value="9">Title [Organize] [Année : 02/02/16] [Bénéfices : 1] [Dispositif : 1]</option>
$("#listeFormation").append(data);
}
});
});
Again, this assumes that the HTML that is being returned to data is a single option tag to be appended to the select object. It looks like your PHP in the Post is looking for POST and your ajax is making a GET, so I am assuming they are different PHP Scripts. If they are not, you need to make sure the PHP knows how to respond properly and is not sending back too much data.
Also, I noticed that insertForm is not defined in this code snippet. If it's defined globally, that's fine, otherwise you need to define it within the scope of this function.

Related

ajax php create associative array then return sql results

So far I do not see how to use solutions posted from my search of "ajax php create associative array then return sql results" - need help: my submit button calls jQuery.ajax that posts select data to a PHP url; then my retriever.php file [msSQL] queries a table and returns multiple records. I want to then return the array back to my jQuery.ajax success function, and parse the returned data - and populate rows of a DataTables HTML table. here is the jQuery.ajax from caller.php:
jQuery('#submit').click(function() {
jQuery.ajax({
url: "https://domain/projects/current/retrieve.php",
//contentType: "application/json",
data: {fy: jQuery('#fy_select').val(), lpid: jQuery('#lp_select').val(), next_year: jQuery('#fy_select').val()+1 },
//dataType: "json",
type: 'post',
success: function(data, XMLHttpRequest){
//alert(data.length);
//alert(JSON.parse(data));
//alert(data[0]);
//jQuery('#activity').text("[" + JSON.parse(data)[0] + "] " + JSON.parse(data)[1]);
jQuery.each(data, function () {
jQuery('#activity').text("[" + JSON.parse(data)[0] + "] " + JSON.parse(data)[1]);
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
return false;
});
pardon comments i left in my code, for if you see something i've tried that can be salvaged let me know; otherwise i hope they are not distracting. i simply need to query the db and get results, stuff them into an array and return it to ajax, then parse the activity, name from the sql result. now the retrieve.php code. thx in advance as always!:
<?php
include(MSS_DB);
//get vars from jQuery .ajax post - lpid and fy:
if ($_POST['lpid'] != null && $_POST['fy'] != null ){
$lpid = $_POST['lpid'];
$fy = $_POST['fy'];
$next_year = $_POST['next_year'];
$fund_info_get = "select activityid, name from activity_table where office= " . $office . " and approveddate > '" . $fy . "-06-30' order by activityid desc";
$get_fund_result = mssql_query($fund_info_get);
$data_array = array();
//$data_array = mssql_fetch_array($get_fund_result);
while($row = mysql_fetch_assoc($get_fund_result)){
$data_array = array('activity_id' => '$row['activityid']', 'activity_name' => '$row['name']');
//$data_array [] = $row; //tried this from another post.
}
$rowcount=mssql_num_rows($get_fund_result); //for alexander this returns 11, correct.
/*while($row = mysql_fetch_array($get_fund_result)){
$table_data[]= arrsay("id=>" = '"$row['activityid']"', "name=>" = '"$row['name']"');
}*/
//$result = "lpid/fy/next_year/get_fund_result: " . $lpid . "/" . $fy . "/" . $next_year . "/" . $fund_info_get . "";
}else{
// either of the values doesn't exist
$result = "No Data Was Sent !";
}
//echo $rowcount;
//echo json_encode($table_data);
//echo $data_array;
echo json_encode($data_array);
//echo $result;
thx, All for Your input! it helped me go forward. a brief description of my solution might help you see how each of you helped:
goal: jQuery.ajax calls someurl.php, gets mssql query data into an array, returns the json_encode array. back in jQuery.ajax success, parse through the json data. here are the operative features of each file to show the solution:
callerfile.php:
jQuery('#submit').click(function() {
jQuery.ajax({
url: "https://fabrik.smartstartinc.net/ncpcphp/activity-mgmt2.0/porc_get_activities.php",
data: {fy: jQuery('#fy_select').val(), lpid: jQuery('#lp_select').val(), next_year: jQuery('#fy_select').val()+1 },
dataType: "json",
type: 'post',
success: function(data, XMLHttpRequest){
console.log(data); //shows json: [{"activity_id":11111,"activity_name":"Community Cleanup"}, etc
jQuery.each(data, function(index, value){
console.log(data[index].activity_id);
console.log(data[index].activity_name);
//these show the id, the name.
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
return false;
});
the PHP file that returns the json array, retrieve.php:
$fund_info_get = "select activityid, name from cpy_activity where lpid= " . $lpid . " and approveddate > '" . $fy . "-06-30' order by activityid desc";
$get_fund_result = mssql_query($fund_info_get);
$data_array = array();
while($row = mssql_fetch_assoc($get_fund_result)){
$data_array[] = array('activity_id' => $row['activityid'], 'activity_name' => $row['name']);
}
}else{
// either of the values doesn't exist
$result = "No Data Was Sent !";
}
echo json_encode($data_array);
once i used JSON.stringify and saw format of the data, i was able to start drilling into how to display it. thx again!

JSON values not showing properly

I wrote a php script which accept POST request from ajax and give the response back. All working fine. But the receiving string split letter by letter I can't understand what is the reason.
Here is my AJAX code,
$("#btn").click(function(){
console.log($("#search_bar").val());
var dataV;
var htmlText = '';
var containerbootsrap = '';
var filename = '';
var index_no;
$.ajax({
type: "POST",
crossDomain: true,
url: "http://localhost:8090/ontology/setText",
data: $("#search_bar").val(),
contentType: 'text/plain',
// dataType: "json",
success: function( data, textStatus, jQxhr ){
console.log('data');
console.log(data);
for( var item in data) {
console.log ("item: " + item);
console.log ("data: " + data[item]);
index_no = data[item];
// htmlText += '<div class="div-conatiner">';
// htmlText += '<p class="p-name"> Name: ' + data[item] + '</p>';
// htmlText += '<img class="imageload" src="' + data[item] + '" />';
// htmlText += '</div>';
// filename = data[item].replace(/^.*[\\\/]/, '')
$.ajax({
data: 'index_no=' + index_no,
url: 'retrivedata.php',
method: 'POST', // or GET
dataType: 'json',
success: function(msg) {
console.log(msg);
for(var item in msg){
console.log ("item: " + item);
console.log ("data: " + msg[item]);
}
$('#home').hide();
containerbootsrap += '<div class = "container" id="search_container">';
containerbootsrap += '<div class = "row homepage">';
containerbootsrap += '<div class = "col-md-5 col-md-offset-3">';
containerbootsrap += '<a href="#" class="thumbnail">';
containerbootsrap += '<img class="imageload" src="' + msg + '" />';
containerbootsrap += '<h3 id="video_name"> ' + filename + ' </h3>'
containerbootsrap += '</a>';
containerbootsrap += '</div>';
containerbootsrap += '</div>';
containerbootsrap += '</div>';
$('body').append(containerbootsrap);
}
});
// $.post('retrivedata.php', { num: 5 }, function(result) {
// alert(result);
// });
// $('#home').hide();
}
// $('body').append(containerbootsrap);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( jqXhr );
alert(jqXhr)
}
});
});
php code is below
<?php
$index_no = $_POST["index_no"];
// echo $index_no * 2;
include('dbConnection.php');
$query = mysql_query("SELECT * FROM video_data WHERE index_no = $index_no");
while ($row = mysql_fetch_assoc($query)) {
$imagePath = $row['thumbnail_url'];
$videoPath = $row['video_url'];
// echo $imagePath;
// echo $videoPath;
echo json_encode($imagePath);
}
?>
I need the output as : 'imagepath'
but it is giving the output as split letter by letter.
here is the real output
Output
but i need the output in one line. like /video_frames/bb/frame136.jpg
please help me to figure out where I am going wrong.
Well, in the php code where you're returning the value you need to specify an array not an string. The variable there $imagePath seems to be a string. You can do something like this.
echo json_encode(array('result' => $imagePath));
This will give you your result in the 'result' key. You can parse it and use it.
You need to parse the returned JSON string into an array. One way to do it is by adding data = $.parseJSON(data) in the ajax success callback (highlighted below). I was able to recreate the same thing you're seeing and adding this line fixed it. Hope this helps. parseJSON()
...
success: function( data, textStatus, jQxhr ){
console.log('data');
console.log(data);
data = $.parseJSON(data);
for( var item in data) {
console.log ("item: " + item);
console.log ("data: " + data[item]);
index_no = data[item];
...
Better way to check the type of value in variable you are getting first like
data = '{"name": "Bhushan"}' //string value
data = {name: "Bhushan"} //object value
//for testing you can use either, this will make it unbreakable for this context
if(typeof(data) == 'string')
{
data = JSON.parse(data)
}
//rest of code
This will give your module good stability otherwise you may get json parse unexpected token o.

Javascript vairables empty unless I debug code

I have a function which makes a ajax call and gets a list of vehicle make.
var car_make_list_target_id = 'car_make';
var make_year_list_select_id = 'years';
var car_model_list_target_id = 'car_model';function get_car_model(){
var car_model_initial_target_html = '<option value="">--Select Model--</option>';
//Grab the chosen value on first select list change
var selectvalue = $('#car_make').val();
alert('first alert ' + selectvalue);
var yearvalue = $('#' + make_year_list_select_id).val();
//Display 'loading' status in the target select list
$('#' + car_model_list_target_id).html('<option value="">Loading Car Models</option>');
if(selectvalue === ""){
//Display initial prompt in target select if blank value selected
$('#' + car_model_list_target_id).html(car_model_initial_target_html);
} else{
//Make AJAX request, using the selected value as the GET
$.ajax({
url: 'get_model.php?make=' + selectvalue + '&year=' + yearvalue,
success: function(output){
//alert(output);
$('#' + car_model_list_target_id).html(output);
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.status + " " + thrownError);
}
});
}
I also have a php if loop to see is session isset. Now I want to display these values within the drop down list if the session is set.
if(isset($_SESSION['vehicle_info'])){
echo '<script>'
.'$("#states option[value=' . $_SESSION['vehicle_info']['state'] . ']").attr("selected","selected");'
.'$("#years option[value=' . $_SESSION['vehicle_info']['year'] . ']").attr("selected","selected");'
. ' $("#years").prop("disabled", false);'
. ' $("#car_make").prop("disabled", false);'
. ' $("#car_model").prop("disabled", false);'
. 'get_car_make();//This works'
. 'get_car_model();//This does not work unless I debug javascript'
. '</script>';
}
The issue is unless I set a breakpoint within the get_car_model on the following lines
var selectvalue = $('#car_make').val();
alert('first alert ' + selectvalue);
the var selectvalue is blank, but if I leave the breakpoint it will alert the value of the option and will display correctly. I have been beating my head for the last 4 hours and I have not been able to figure this out. Is this normal browser behavior or am I missing something? Any input will be great.

How to pass an array from PHP using AJAX

I'm having some issues displaying an array which I created in a PHP file. The response data in question is data["vessel"]
I have some jQuery:
j$('select[name=vessel]').change(function(e) {
var tour_ID = j$('select[name=tour]').val();
var trip_Date = j$('input[name=trip_Date]').val();
var data = {
"action": "Count_Vessels",
"trip_Date": trip_Date,
"tour_ID":tour_ID
};
data = j$(this).serialize() + "&" + j$.param(data);
j$.ajax({
type: "POST",
dataType: "json",
url: "../include/booking_Modify.php",
data: data,
success: function(data) {
//console.log("vessel stack: " + data["vessel"][0]);
var arr=JSON.parse(data["vessel"]);
console.log("vessel stack: " + arr[0]);
console.log("Form submitted successfully.\nReturned json: " + data["json"]);
},
error: function (request) {
console.log(request.responseText);
}
});
});
The PHP:
function count_Vessels(mysqli $conn, $trip_Date, $tour_ID){
$return = $_POST;
$vessel_Stack = array();
$vessel_Query = "SELECT * FROM Vessel";
if(!$vessel_Results = $conn->query($vessel_Query)){
die('There was an error running the query [' . $conn->error . ']');
}
while( $vessel_Row = $vessel_Results->fetch_assoc() ){
$vessel_Stack[$vessel_Row['ve_ID']] = $vessel_Row['vessel_Name'];
}
$return['vessel'] = $vessel_Stack;
$return["json"] = json_encode($return);
echo json_encode($return);
}
when I display data["json"] in console, I get Returned json: {"vessel":{"1":"Thriller","2":"Jammin","3":"Thunderstruck","4":"Wildthing","6":"Joyride"}
Which is awesome, but I don't know how to do that using the data["vessel"] Any help would be greatly appreciated.
I solved my own riddle. Because data["vessel"] is an array, I had to loop through it. Doing so like this worked:
j$.each(data["vessel"], function(key, val) {
console.log('index ' + key + ' value ' + val);
});

Image AJAX search not working in Safari

I have a live image search that uses AJAX and an SQL query to find images with a name the same as the users input on a text field. I thought it was working fine until I tested in Safari, and it does literally nothing.
I'm not too sure why not even an error is returned in Safari, does anyone know of an issue in Safari that might be stopping it from working?
jQuery:
var input = $('.image-search');
var value;
var append = $(".results-append");
var loadUrl = '/stock-image-search.php';
var results = $('.results');
var resultsDiv = '<div class="results-heading"><h2>Results for "<span class="results-for"></span>"</h2></div>';
var resultsFor;
var nothingFound = '<div class="nothing-found"><br /><span>No results found.</span></div>'
// on keyup
input.on("keyup", function() {
// remove everything that was there
$('.results-append').remove();
results.empty();
$("#temp_load").remove();
value = input.val();
append.prepend(resultsDiv);
resultsFor = $('.results-for');
resultsFor.html($(this).val());
// ajax the results!
$.ajax({
type: "GET",
data: {
nameLike: value
},
dataType: "html",
url: templateDir + loadUrl,
beforeSend: function() {
append.hide().append('' +
'<div id="temp_load" class="search-loader">' +
'<img src="' + templateDir + '/img/load.GIF" />' +
'</div>'
).fadeIn(200);
},
success: function(data) {
$("#temp_load").fadeOut(200);
// fix for fast typers
results.empty();
var data = $(data);
if (data.length) {
results.append(data);
} else {
results.append(nothingFound);
}
},
error: function(jqXHR, textStatus, errorThrown) {
$("#temp_load").fadeOut(200).remove();
console.log(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
});
PHP function:
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php' );
global $wpdb;
if( isset($_GET['nameLike']) && strlen($_GET['nameLike']) > 1 ) :
$search = $_GET['nameLike'];
$results = $wpdb->get_results( $wpdb->prepare("
SELECT ID
FROM $wpdb->posts
WHERE $wpdb->posts.post_status = 'inherit'
AND $wpdb->posts.post_mime_type != ''
AND ( $wpdb->posts.post_author = 1 OR $wpdb->posts.post_author = 3 )
AND $wpdb->posts.post_title LIKE %s
", '%' . like_escape($search) . '%'
), ARRAY_A);
foreach ($results as $result) : ?>
<?php
$image = wp_get_attachment_image( $result[ID], array(200, 150) );
?>
<div class="grid-1-4 clearfix">
<div class="stock-image-select clearfix" data-id="<?php echo $result[ID]; ?>">
<?php echo $image; ?>
</div>
</div>
<?php endforeach;
else : ?>
<div class="grid-10">Your search needs to be at least 2 characters long.</div>
<?php endif; ?>
If anyone can see a glaring error, please let me know :)
Try something like this
$(document).ready(function() {
$('input[name="search_field"]').keyup(function(e){
$(this).text;
//process your search
});
});
When you detect a key was raised then take the text and do the search.

Categories