jquery select adding extra rows [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a small ajax call:
$.ajax({
type:'POST',
dataType: 'json',
url: 'inc/getfunctions.php?q='+l_id+'&func=load_po',
success:function(data){
//alert ('hi');
if (data.po_num) {
$('#po_num_s').append($('<option>').text('Select a PO').attr('value', 0));
var po_num = data.po_num;
var $subType = $("#po_num_s");
$.each(data, function () {
$subType.append($('<option></option>').attr("value", data.l_id).text(data.po_num));
});
}
}
});
it is apending 2 rows :
<'option value="11">112212<'/option>
<'option value="11">112212<'/option>
is the output
Thanks in advance

The $.each function will take an array or an object and iterate over its items, while providing the item key and value as parameters to the callback. Like so:
$.each(["aaaa", "bb", "ccc"], function(key, value){
console.log(value.length);
});
// Will output:
// 4
// 2
// 3
But you aren't using the each-loop for something useful, as you don't receive any item in the callback function. The only reason you're getting as few as 2 lines is that your data object only has 2 keys in it. Try adding another property to data at the same place as your commented alert, like so:
......
success:function(data){
//alert ('hi');
data.foo = "bar"
if (data.po_num) {
......
and watch the each-loop go three rounds.

Related

JSON encode no output [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I've tried to look up different ways to get this json to output correctly but im not sure if im accessing the right variable in php/or the success function value.pTitle as well as how to I get the access to the other value out such as artTitle im failing somewhere not sure where or why.UPDATE fixed the php file added and an array $data[].
this is my php code.
$sqlPAQuery = "SELECT pTitle, GROUP_CONCAT(artTitle) AS
artTitle
FROM p
JOIN art ON art.pId = p.pId
GROUP BY pTitle";
if ($result=mysqli_query($conn,$sqlPAQuery))
{
$data = [];
while ($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$data[] = $row;
}
echo json_encode($data);
}
This is the outcome from the php encode of row:
[{"pTitle":"ent","artTitle":"11,12"},{"pTitle":"pro","artTitle":"10"},{"pTitle":"sports","artTitle":"1,13"}]
This is the html code:
<h3>Output: </h3>
<div id="output"></div>
<script id="source" language="javascript" type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: 'Data.php',
data: "",
dataType: 'json',
success: function(data)
{
$.each(data, function(index, value) {
var pageTitle = value.pTitle; //get name
$('#output').append("<b>pageTitle: </b>"+pageTitle+"<br/>");
}
});
});
Output should be:
pageTitle: ent
pageTitle: pro
pageTitle: sport
FIXED THE PHP FILE WORKS
If you want to proces the json like that this is what you need to do:
if ($result=mysqli_query($conn,$sqlPAQuery)) {
$data = [];
while ($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$data[] = $row;
}
echo json_encode($data);
}

How to handle JSON object in php [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I figure it out to create a JSON object in jquery
function form2JSON(form){
var info_ser = $('#'+form).serialize();
var data = info_ser.split('&');
var output = {};
$.each( data, function( i, l ){
var data_input = l.split('=');
output[data_input[0]] = data_input[1];
});
return output;
}
But now in PHP I dont know how to handle the JSON.... ?
$.ajax({
type: "POST",
url: "./modelo/.php",
data: {
act: 'mc',
ent: 'modelos',
json: jsonobject
},
dataType: 'json',
cache: false
}).done(function(data) {});
Then you can access your data in php by:
json_decode($_POST['json']);
You actually forgot to add a key in data for your jsonobject.

Send variable From PHP to AJAX [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a php page called posts.php, this page just select all from a database table named posts and display them. Down the page I have a textarea named post. When I press the submit button the AJAX script will send the text from textarea to a page called insert.php. This insert.php gets the submited text and insert it into posts table. How can I do this and how can I upload the posts.php when I have inserted a post into posts table.
Example:
User 123 writes a message in the textarea. He presses submit button. AJAX sends the post to insert.php. Insert.php inserts the post into posts tabel. Posts.php shows the message.
You can do it very easily! Here's a very simple example.
func.js
$(document).on("click", ".submitBtn", function() {
var textareaVal = $(".textarea").val();
$.ajax({
type: "POST",
url: "insert.php",
dataType: "text",
data: { postVar: textareaVal },
success: function(data) {
$(".resultDiv").load("posts.php");
}
});
});
insert.php
// You have to pay attention to AJAX can only invite your file!
if (!empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest") {
if (isset($_POST["postVar"])) {
$var = sanitize($_POST["postVar"]); // You need sanitize the data!
// Insert into your table...
}
}
In your posts.php, SELECT datas from your table, but only select the data, without „HTML container”! Your JS file load this datas on your resultDiv box.
I'm not certain why you would need to do this via ajax, but:
$( "#myForm" ).submit(function( event ) {
$.ajax({
type: 'post',
url: '../insert.php' ,
data: { value1: document.getElementById('textarea').value },
success: function () {
alert("yay!");
}
});
});

Append .php json to javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have this json result from my site 'www.example.com/jsonresult.php'
{
1: {
item_id: "Balls",
item2: "2",
item3: "3",
item4: "4"
}
}
How do i append it in my jquery mobile javascript at
$.ajax({
url: forecastURL,
jsonCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.log(json);
$("#current_temp").html('here');
$("#current_summ").html('and here');
},
error: function(e) {
console.log(e.message);
}
});`
please help, thanks.
This is how I did it:
$("#ul").html(myvar['1'].item_id);
Have a look at this JSFiddle here

Why does this AJAX success callback never run? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've been stuck 2 days on the TutsPlus - jQuery in 30 Days exercises... lesson 26
Why does my ajax success function refuse to log the results to the console?
What happens instead is index.php simply echoes the text onto the webpage itself.
It's like some syntax problem is preventing the success callback from even running at all.
The rest of the code works (it does not rely on this particular callback), but I don't want to proceed until I find out what's wrong.
var Actors = {
init: function( config ) {
this.config = config;
this.bindEvents();
},
bindEvents: function() {
this.config.letterSelection.on('change', this.fetchActors);
},
fetchActors: function() {
var self = Actors;
$.ajax({
url: 'index.php',
type: 'POST',
data: self.config.form.serialize(),
dataType: 'json',
success: function(results) {
console.log(results);
}
});
}
};
Actors.init({
letterSelection: $('#q'),
form: $('#actor-selection')
})
and here's my index.php page...
<?php
require 'functions.php';
if ( isset($_POST['q']) ) {
connect();
$actors = get_actors_by_last_name( $_POST['q'] );
echo 'index returning your call with ' . $_POST['q'];
// echo json_encode($actors); return;
}
include 'views/index.tmpl.php';
?>
When specifying a dataType, such as 'json', the entire response needs to conform to that type.
By including additional output, such as:
echo 'index returning your call with ' . $_POST['q'];
The response won't be valid JSON and jQuery will error when attempting to parse it.

Categories