Ajax returns all expected html result from php code, except the javacript and jQuery inside the "script" tags
var frm = $('#cell');
frm.submit(function (ev) {
$.ajax({
type: "POST",
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (html) {
//Create jQuery object from the response HTML.
var $return=$(html);
//Query the jQuery object for the values
var oneval = $return.filter('#cellWidthSlider').html();
alert(oneval);
$("#cellWidthDiv").html(oneval);
}
});
ev.preventDefault();
});
I have tried to append to head, but the jQuery code would execute only - before the elements.
var $response=$(html);
$("head").append($response);
var oneval = $response.filter('#cellWidthSlider').html();
As much as I've been afraid of JSON, it was actually much simpler than I thought and it really took me only around 3 hours to get the general understanding, feeling good, now so so much started to look familiar in ajax and jQuery:)
So The changes I've done...
Instead of generating js within external php I have created array with values e.g.:
$result = array(
array(
'prevCellId' => $prevCellId,
'prevCellWidth' => $prevCellWidth,
'thisCellId' => $latestCellId,
'thisWidth'=>$thisWidth,
'thisRowId' => $thisRowId,
'thisRowOrder' => $thisRowOrder,
'maxWidth' => $maxWidth,
'prevCellRowOrder' => $prevCellRowOrder));
echo json_encode($result);
Then, after long search I've managed to implement json values in my jQuery function:
$.getJSON( "cellWidth.php", function( json ) {
$.each(json, function(i, item) {
$('#slider').slider({ max:''+item.maxWidth+'',min: 10,step: 5, value:''+item.thisWidth+'', slide: handleSliderChange, stop: sendNew});
var $slider = $("#slider").slider({ max:''+item.maxWidth+'',min: 10,step: 5, value:''+item.thisWidth+''});
})
})
So simply used keyword "item." + "names of arrays" to "echo" / "use values" within jQuery - in this case this is a jQuery slider :))
Related
In PHP I can do things like this:
echo "<div>".$myvariable."</div>";
Which will print out my variable with div's in HTML for its tags. However recently, I needed to do a ajax call using jquery. I'm somewhat familiar with ajax but I don't use it much. Anyways, I run the ajax code, it prints the data into my HMTL element box like I wanted, however, the div tags are printed and displayed along with the content itself!
The entire return data is pretty much 1 long string, rather than the PHP parsing my data like I want it to. Where did I go wrong? Why is it only returning 1 long string?
PHP CODE:
<?php
require 'database.php';
$meal = $_POST['meals'];
$meal_q = "SELECT item
FROM meal_ingredients
WHERE meal_name='$meal'
ORDER BY item";
$meal_c = $conn->query($meal_q);
while ($row = $meal_c->fetch_assoc()){
$view_ingredient = $row['item'];
echo "<div>".$view_ingredient."</div>";
};
?>
JQUERY CODE:
if($('body').hasClass('CreateMealPage')){
$('tr').on('click', function(e){
$('#sidebar').animate({right: '-200px'}, 500);
var meals = $(this).find('.meals').text();
$.ajax({
method: "POST",
url: 'meal_list.php',
data: {meals: meals},
success: function(data) {
var sidebar = document.getElementById('sidebar');
sidebar.innerHTML = "";
sidebar.append(data);
}
});
});
};
WHAT IS RENDERED ON SCREEN:
<div>ingredientname</div>
<div>ingredientname</div>
<div>ingredientname</div>
RATHER THAN:
ingredientname
ingredientname
ingredientname
just replace
sidebar.innerHTML = "";
sidebar.append(data);
with
sidebar.innerHTML = data;
To answer your comment you can use append with following in jquery
$(sidebar).append($(data))
so jquery's append needs to be used, instead of append, from dom api, which takes a node element only in arguments. If you still need to use append of dom api, use something like:
sidebar.append(document.createRange().createContextualFragment(data))
Add dataType: "html" to the properties in your $.ajax() call, like this:
$.ajax({
method: "POST",
url: 'meal_list.php',
dataType: "html",
data: {meals: meals},
success: function(data) {
var sidebar = document.getElementById('sidebar');
sidebar.innerHTML = "";
sidebar.append(data);
}
});
This will inform the call to expect HTML data to be returned in the response body.
I'm new to stackoverflow (as a member at least) and I have a question.
I'm also new to PHP by the way.
Thing is:
I want to dynamically fill a second dropdown list with entries based on a first dropdown list (I want to show cities based on a selected province).
I managed to get the selected province to an external PHP file with an AJAX call in Javascript.
But when I include the external PHP file in my original PHP file, the variable of the external file is undefined.
The AJAX call is fired with an onchange event on the first dropdown menu.
And maybe you can also help with how I use that variable to get the right content in the second dropdown. I've used a multidimensional Array for that.
HTML:
echo('<select name="provincie" id="provincie" onchange="ProvinciePHP()">');
foreach ($provincie as $provincies){
echo ("<option> $provincies </option>");
}
echo ('</select>');
echo('<select name="stad" id="stad"> </select>')
PHP ARRAY:
$provincie = array(
'Selecteer een provincie',
'Drenthe',
'Flevoland',
'Friesland',
'Gelderland',
'Groningen',
'Limburg',
'Noord-Brabant',
'Noord-Holland',
'Overijssel',
'Utrecht',
'Zeeland',
'Zuid-Holland',
);
$stad = array(
'Drenthe' => array("Assen", "Emmen", "Hoogeveen", "Meppel"),
'Flevoland' => array("Almere", "Biddinghuizen", "Dronten", "Lelystad"),
'Friesland' => array("Heerenveen", "Joure", "Leeuwarden", "Sneek"),
'Gelderland' => array("Apeldoorn", "Arnhem", "Nijmegen", "Zutphen"),
'Groningen' => array("Delfzijl", "Groningen", "Stadskanaal", "Veendam"),
'Limburg' => array("Maastricht", "Roermond", "Sittard", "Venlo"),
'Noord-Brabant' => array("Breda", "Den Bosch", "Eindhoven", "Tilburg"),
'Noord-Holland' => array("Alkmaar", "Amsterdam", "Haarlem", "Hilversum"),
'Overijssel' => array("Deventer", "Enschede", "Hengelo", "Zwolle"),
'Utrecht' => array("Amersfoort", "Breukelen", "Utrecht", "Zeist" ),
'Zeeland' => array("Goes", "Middelburg", "Terneuzen", "Vlissingen"),
'Zuid-Holland' => array("Alphen a/d Rijn", "Den-Haag", "Rotterdam", "Schiedam"),
);
function getProvincie(){
var provincie = $('#provincie option:selected').val();
$.ajax({
type: "POST",
url: "getprovincie.php",
data: {data: provincie},
success: function(data) {
alert(data);
$('#stad').css('display','inline');
},
error: function(data) {
}
});
}
//PHP page to where the AJAX call points:
<?php
$resultaat = $_POST['data'];
echo($resultaat);
So, I have the following ajax call:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'html',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data);// Need changes
});
Then my php:
function rhmain_tag() {
// 1. Getting wp tag list:
$args = array(
'orderby' => 'count',
'order' => 'DESC'
);
$tags = get_tags($args);
foreach ( $tags as $tag ) {
echo $tag->term_id;
}
//2. Getting "another.php" file
$template_part_path = 'page-parts/another_php';
get_template_part($template_part_path);
exit;
}
add_action('wp_ajax_ajax_call', 'ajax_call');
add_action('wp_ajax_nopriv_ajax_call', 'ajax_call');
As you can see, in the php function, there are two separate thing going on.
Getting tag list passed onto the js as variable.
echo $tag->term_id; shows a number like this "16508164981650616502165031650416505165071650116520." So, somehow I need to put comma in between each term id (not sure how) so it looks like this : "16508,16498,16506,16502,16503,16504,16505,16507,16501,16520"
Then I need to pass these values to js to be used as a variable (not sure how)
another_php file is passed onto js (Works fine).
Questions:
How to do I add "comma" in between the tag term_id?
How do I pass these tag values to js?
EDIT: Using json_encode to pass data
PHP
function rhmain_tag() {
$template_part_path = 'page-parts/another_job';
$return_data['another_job'] = get_template_part($template_part_path);
$return_data['tag_id'] = '16498';
echo json_encode($return_data);
exit;
}
add_action('wp_ajax_rhmain_tag', 'rhmain_tag');
add_action('wp_ajax_nopriv_rhmain_tag', 'rhmain_tag');
JS:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'html',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data.another_php);
var tag_list = data.tag_id;
});
Using json_encode to send an array containing both data that you require front end you then need to make the following changes to your ajax function.
Change the dataType to json
Access the data as data.another_php and data.tag_id
The full ajax:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'json',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data.another_php);
var tag_list = data.tag_id;
});
To add the comma in between you could use a variable to store instead of echo'ing immediately. Like this :
$args=array(
'orderby'=>'count',
'order'=>'DESC'
);
$tags = get_tags($args);
$tag_list = "";
foreach ( $tags as $tag ) {
$tag_list += $tag->term_id + ",";
}
// Now trim the last comma
$tag_list = rtrim($tag_list, ",");
echo $tag_list;
I'm noob, and i recently knew about Ajax, so dont worry if my question seems idiot.
I tried to do that, but i had no success, but i will explain what i tried to do:
I have one draggble box with some words, and everytime that i drag some elements to a certain place, i want to record this transition into my database.
So, i did that in Ajax:
UPDATE
$(document).ready(function() {
$(".event").draggable();
$(".drop").droppable({
drop: function(event, ui) {
var id = ui.draggable.attr("id");
var targetid = event.target.id ;
$.ajax( {
type: 'post',
url: "new.php",
data : { 'day' : '3' },
success: function( response ) {
alert( response );
}
});
}
});
});
New file:
function eventTransition($day){
$day = $_POST['day'];
$insert="INSERT INTO events (event_day) VALUES (".$day.")";
mysql_query($insert);
}
eventTransition($day);
I tried to automatically put a value to the day variable.
Please try this in php file and reply if this helps you
function eventTransition($day){
$insert="INSERT INTO events (event_day) VALUES (".$day.")";
mysql_query($insert);
}
$day = $_POST['day'];
eventTransition($day);
You cannot call a PHP function directly using Ajax. A(n over-)simplified new.php file may look like the following:
$day = $_REQUEST['day'];
$insert="INSERT INTO events (event_day) VALUES (".$day.")";
mysql_query($insert);
In your ajax call you must specify:
dataType: 'json'
As #baxri advises, add an error handler.
I have two tables, has-many relationship,
in the master add.ctp, allow user to upload 0~5 files(file path information are stored in details table)
I want to dynamically display attachment(detail) form in the master/add.ctp
1, user choose number of files want to upload from dropdown list,
echo $this->Form->input('attachments', array( 'options' => array(1, 2, 3, 4, 5),'empty' => '(choose one)', 'onchange' => 'showNumber(this.value)'));
then forloop
{
echo $this->Form->input('attachment_path', array('type'=>'file','label' =>'Attachment, Maximum size: 10M'));
}
//but I don't know how to capture this.value, I know Javascript can not pass value to php.
or user click 'add another attachment' link, then detail form shows up.
How to achieve this function, any help would be appreciated.
I have read this article:
Assign Javascript variable to PHP with AJAX
and get same error: the variable is undefined
Edit:
http://cakephp.1045679.n5.nabble.com/Adding-fields-to-a-form-dynamically-a-complex-case-td3386365.html
'For each field use a default name with [] at the end (which will make
it stack like a array) example: data[][book_id] after the fields have
been submitted'
Where should I place the []?
I think you should use Ajax for this.
Simply create an ajax call on select.change() and then a method in the controller that returns the necessary info.
You can return an array of data using echo json_encode(array('key' => 'value')) directly on your controller (or better in a custom view) and access it with Javascript:
success: function(data) {
alert(data.key);
}
Edit...
In your javascript use something like...
$('select').change(function(e) {
var select = $(this);
$.ajax({
type: "POST",
dataType: "json",
url: "/attachments/youraction",
data: { data: { id: select.find(":selected").val() } },
success: function(data) {
for (i in data) {
var input = $('<input>', {type: "file", label: data[i].Attachment.label})
$('form.your-form').append(input);
}
}
})
});
Then in "Yourcontroller" create "youraction" method:
<?php
class AttachmentsController extends AppController
{
public function youraction()
{
if (!$this->RequestHandler->isAjax() || !$this->RequestHandler->isPost() || empty($this->data['id']))
{
$this->cakeError('404');
}
// Do your logic with $this->data['id'] as the select value...
$data = $this->Attachment->find('all', array('conditions' => array('id' => $this->data['id'])));
// ....
// then output it...
echo json_encode($data);
// This should be done creating a view, for example one named "json" where you can have there the above echo json_encode($data);
// Then..
// $this->set(compact('data'));
// $this->render('json');
}
}
It's more clear now?? If you have doubts about ajax + cakephp you should do a search on the web, where you will find a lot of tutorials.
I use this approach to achieve this function. (finally got it :))
http://ask.cakephp.org/questions/view/foreach_loop_with_save_only_saving_last_member_of_array
Yes, AJAX can do lots of things, to me, it's very hard to understand the logic in a day..
Anyway, Thanks again.