how to display array passed via ajax in html - javascript

This is my ajax:
$("#submit").on("click",function()
{
$("#add_car_form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "text",
url: "add_car_submit.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html("<br />JSON: " + data );//this outputs
{"car_name":";ll","car_maker":"njk","car_type":"nkj","passanger":"1","rate":["89","67","45","34","23"],"action":"test"}
}
});
document.getElementById("add_car_form").reset();
return false;
});
});
I simply echo from php script like this: echo $return["json"]; and it will output like this:
{"car_name":";ll","car_maker":"njk","car_type":"nkj","passanger":"1","rate":["89","67","45","34","23"],"action":"test"}
How do append to a div in html table form like this?
Car Name: name
Car Maker: maker
......

try this in your success function
data = jQuery.parseJSON( data ); //parse data if this is text other wise use data directly. hope this is a text param in your case.
var out = '<table>';
$.each(data, function( key, value ) {
out += '<tr><td>'+key+': '+ value +'</td></tr>';
});
out += '</table>';
//append out to your div
$(".the-return").html(out);

You should not create a form submit handler inside a click handler as it could create multiple listeners for single click event.
I think you could just encode the data use json_encode in the server side then, accept the response as json in the client using dataType: 'json' then
$("#submit").on("click", function () {
var $form = $("#add_car_form")
var data = {
"action": "test"
};
data = $form.serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "add_car_submit.php", //Relative or absolute path to response.php file
data: data,
success: function (data) {
$(".the-return").html("Car Name" + data.car_name + '<br />Car Maker' + data.car_maker); //Add more properties here
}
});
document.getElementById("add_car_form").reset();
return false;
});

Related

Unable to send multiple data parameters with jQuery AJAX

I am trying to send values to other page Using Ajax
But i am unable to receive those values , i don't know where i am wrong
here is my code
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var dataString1 = "fval="+fval;
alert(fval);
var sval = document.getElementById('country').value;
var dataString2 = "sval="+sval;
alert(sval);
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: "{'data1':'" + dataString1+ "', 'data2':'" + dataString2+ "'}",
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
in alert i am getting those value but in page 'getmoreinfo.php' i am not receiving any values
here is my 'getmoreinfo.php' page code
if ($_POST) {
$country = $_POST['fval'];
$country1 = $_POST['sval'];
echo $country1;
echo "<br>";
echo $country;
}
Please let me know where i am wrong .! sorry for bad English
You are passing the parameters with different names than you are attempting to read them with.
Your data: parameter could be done much more simply as below
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var sval = document.getElementById('country').value;
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: {fval: fval, sval: sval},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
Or cut out the intermediary variables as well and use the jquery method of getting data from an element with an id like this.
<script type="text/javascript">
function get_more_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: { fval: $("#get_usecompny").val(),
sval: $("#country").val()
},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
No need to create 'dataString' variables. You can present data as an object:
$.ajax({
...
data: {
'fval': fval,
'sval': sval
},
...
});
In your PHP, you can then access the data like this:
$country = $_POST['fval'];
$country1 = $_POST['sval'];
The property "data" from JQuery ajax object need to be a simple object data. JQuery will automatically parse object as parameters on request:
$.ajax({
type: "POST",
url: "getmoreinfo.php",
data: {
fval: document.getElementById('get_usecompny').value,
sval: document.getElementById('country').value
},
success: function(html) {
$("#get_more_info_dt").html(html);
}
});

How to save the data into database in jquery and display upon the screen using web api

I want to add the values inot the database but I am not to able to do that.
var Array;
$(document).ready(function ()
{
$.ajax({
url: '../api/Emp/GetAll',
type: 'Get',
cache: false,
datatype: 'json',
success: function (text) {
Array = text.Table;
var List = JSON.stringify(text);
for (var i = 0; i < data.length; i++) {
var Id = Array[i].id;
var Name =Array[i].name;
var city = Array[i].city;
$('#table body').append('<tr><td>' + Id + '</td><td><input type="text" value="' + Name + '" id="txt' + Id + '" /></td><td>' + city + '</td> </tr>');
}
}
})
If you need to put it back into the database you just need to reverse the process.
Use post for your type and send the data back with ajax to a php script page that inserts the data into your database.
You can edit the data on the php page before you insert it into the database or you can edit the data with javascript then send it back to php page.
Create an ajax post
$.ajax({
type: "post",
datatype: "json",
url: "insertPage.php",
data: {dataNameHere: editedDataGoesHere},
success: function(data){
alert("SUCCESS");
},
error: function(e){
alert("ERROR");
}
});
And then in your PHP:
$obj = $_POST['dataNameHere'];
and insert it into your database like you normally would.

jQuery reading multiple XML files and remove duplicates when inserting into HTML for Display

I have a total of 4 XML files in same format representing 4 different categories of project contents. However some projects does have more than 1 category.
I want to merge all 4 XML files using jQuery and display all projects contents in a single page within a , but due to the fact that some projects have more than 1 category, the displayed results show duplicates of project contents.
How do I remove duplicates within the combined extracted XML files?
Here is my jQuery Code:
XMLLIST = {
//general settings
xml1: 'xml/structural_steel.xml?' + Math.random(0,1), //solve ie weird caching issue
xml2: 'xml/building_work_id.xml?' + Math.random(0,1), //solve ie weird caching issue
xml3: 'xml/shear_stud_welding.xml?' + Math.random(0,1), //solve ie weird caching issue
xml4: 'xml/custom_solution.xml?' + Math.random(0,1), //solve ie weird caching issue
appendTo: '#list', //set the id/class to insert XML data
init: function () {
//jQuery ajax call to retrieve the XML file
$.ajax({
type: "GET",
url: XMLLIST.xml1,
dataType: "xml",
success: XMLLIST.parseXML
});
$.ajax({
type: "GET",
url: XMLLIST.xml2,
dataType: "xml",
success: XMLLIST.parseXML
});
$.ajax({
type: "GET",
url: XMLLIST.xml3,
dataType: "xml",
success: XMLLIST.parseXML
});
$.ajax({
type: "GET",
url: XMLLIST.xml4,
dataType: "xml",
success: XMLLIST.parseXML
});
}, // end: init()
parseXML: function (xml) {
//Grab every single ITEM tags in the XML file
var data;
data = $('item', xml).get();
var i = 1;
//Loop through all the ITEMs
$(data).each(function () {
//Parse data and embed it with HTML
XMLLIST.insertHTML($(this));
i++;
});
}, // end: parseXML()
insertHTML: function (item) {
//retrieve each of the data field from ITEM
var url = item.find('url').text();
var image = item.find('image').text();
var title = item.find('title').text();
var html;
//Embed them into HTML code
html = '<div class="item">';
html += '<img src="' + image + '"><br>';
html += '<span class="contentsubtitle">' + title + '</span><br><br>';
html += '</div>';
//Append it to user predefined element
$(html).appendTo(XMLLIST.appendTo);
}, // end: insertHTML()
}
//Run this script
XMLLIST.init();
I hope my code is correct. Had no data to test with, but I think the idea of it should be a bit more clear.
edited: Now working, version after receiving xml test-data
<html>
<head>
<title>asdasd</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
</head>
<body>
<div id="list">
</div>
<script>
XMLLIST = {
dataToLoad: [
'test.xml'
],
loadedData: [],
appendTo: '#list',
rand: function() {
return new Date().getTime();
},
loadData: function(file) {
$.ajax({
type: "GET",
url: file + "?" + XMLLIST.rand(),
dataType: "xml",
success: XMLLIST.parseXML,
error: function(r) {
console.error(r);
}
});
},
init: function () {
XMLLIST.dataToLoad.forEach(function(file) {
XMLLIST.loadData(file);
});
},
parseXML: function (xml) {
var data = $('item', xml).get();
$(data).each(function (i, value) {
var $value = $(value),
item = {
url: $value.find('url').text(),
image: $value.find('image').text(),
title: $value.find('title').text()
};
if (!XMLLIST.itemIsInList(item)) {
XMLLIST.loadedData.push(item);
XMLLIST.insertHTML(item);
}
});
},
itemIsInList: function(item) {
var hits = XMLLIST.loadedData.filter(function(value){
return XMLLIST.compareItem(item, value);
});
return hits.length > 0
},
compareItem: function(item1, item2) {
return item1.url === item2.url && item1.image === item2.image && item1.title === item2.title;
},
insertHTML: function (item) {
var html = '<div class="item">';
html += '<img src="' + item.image + '"><br>';
html += '<span class="contentsubtitle">' + item.title + '</span><br><br>';
html += '</div>';
$(html).appendTo(XMLLIST.appendTo);
}
};
XMLLIST.init();
</script>
</body>
</html>
You have a list, where you push your objects to. This list has a checkFunction "itemIsInList". Additionally you need a seperate check-function "compareItem", because indexOf won't work with objects
Managed to modify my original script by adding a masterArr for comparison of duplicated data received accross the 4 XMLs.
Here's the codes:
XMLLIST = {
//general settings
xml1: 'xml/structural_steel.xml?' + Math.random(0,1), //solve ie weird caching issue
xml2: 'xml/building_work_id.xml?' + Math.random(0,1), //solve ie weird caching issue
xml3: 'xml/shear_stud_welding.xml?' + Math.random(0,1), //solve ie weird caching issue
xml4: 'xml/custom_solution.xml?' + Math.random(0,1), //solve ie weird caching issue
appendTo: '#list', //set the id/class to insert XML data
//end general settings
masterArr: [],
init: function () {
//jQuery ajax call to retrieve the XML file
$.ajax({
type: "GET",
url: XMLLIST.xml1,
dataType: "xml",
success: XMLLIST.parseXML
});
$.ajax({
type: "GET",
url: XMLLIST.xml2,
dataType: "xml",
success: XMLLIST.parseXML
});
$.ajax({
type: "GET",
url: XMLLIST.xml3,
dataType: "xml",
success: XMLLIST.parseXML
});
$.ajax({
type: "GET",
url: XMLLIST.xml4,
dataType: "xml",
success: XMLLIST.parseXML
});
}, // end: init()
parseXML: function (xml) {
//Grab every single ITEM tags in the XML file
var data;
data = $('item', xml).get();
var i = 1;
//Loop through all the ITEMs
$(data).each(function () {
//Check if masterArr[] already contains a duplicate of the item by checking using the XML label <image> or any other value/label that is unique.
//Insert into masterArr[] if not duplicate and publish HTML if not duplicate.
var string1 = $(this).find('image').text();
if( jQuery.inArray(string1, XMLLIST.masterArr) == -1){
XMLLIST.masterArr.push(string1);
//Parse data and embed it with HTML
XMLLIST.insertHTML($(this));
};
//If it reached user predefined total of display item, stop the loop, job done.
//if (i == XMLLIST.display) return false;
i++;
});
}, // end: parseXML()
insertHTML: function (item) {
//retrieve each of the data field from ITEM
var url = item.find('url').text();
var image = item.find('image').text();
var title = item.find('title').text();
var html;
//Embed them into HTML code
html = '<div class="item">';
html += '<img src="' + image + '"><br>';
html += '<span class="contentsubtitle">' + title + '</span><br><br>';
html += '</div>';
//Append it to user predefined element
$(html).appendTo(XMLLIST.appendTo);
}, // end: insertHTML()
}
//Run this script
XMLLIST.init();

detect which button has been clicked and submit with ajx

I need help getting a value of a clicked button and send this information using AJAX. the two scripts work individually. but i need the "buttonvalue" to be passed to AJAX "data" value "action". what i am using is below.
$("document").ready(function(){
$(".js-ajax-php-json").on("click", "button[name=mysqljob]", function (){
var buttonvalue = $(this).attr("value");
alert(buttonvalue);
});
$(".js-ajax-php-json").submit(function(){
var data = {"action": buttonvalue};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "phpVars/ajaxUpload.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html(
data["form"]
);
// alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
I would prevent the form from submitting do what you want then post the data via an ajax call. Try the following:
$("document").ready(function(){
$(".js-ajax-php-json").on("click", "button[name=mysqljob]", function (e){
e.preventDefault();
var buttonvalue = $(this).attr("value");
var data = {"action": buttonvalue, "formData": $(this).serialize() + "&" + $.param(data) };
$.ajax({
type: "POST",
dataType: "json",
url: "phpVars/ajaxUpload.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html(
data["form"]
);
// alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
Not tested.

How to correctly post data with ajax into div?

Script:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").ajax({
type: "POST",
url: "BlockEditor/build.php",
data: 'block_id=' + id + '&building=' + building + '&nick=' + nick,
cache: false,
success: function(response)
{
alert("Record successfully updated");
$.load("#BuildedBox")
}
});
}
build.php:
include_once("$_SERVER[DOCUMENT_ROOT]/db.php");
$block_id = $_GET['block'];
$building = $_GET['building'];
$nick = $_GET['nick'];
echo"$block_id - $building - $nick";
index.php:
<a href=\"#\" onClick=\"buttonBuild(k152, digger, Name);\" >[BUILD]</a>
<div id="BuildedBox"></div>
seems my script wont work. what i have done wrong?
check this out
function buttonBuild(id, building, nick)
{
$.ajax({
type: "POST",
url: "BlockEditor/build.php",
data: 'block_id=' + id + '&building=' + building + '&nick=' + nick,
cache: false,
success: function(response)
{
alert("Record successfully updated");
/***************/
$("#BuildedBox").html(response);
/***************/
}
});
}
var weightd = $("#weight").val();
var user_id = 43;
$.ajax({
type: "POST",
url:"<?php bloginfo('template_directory')?>/ajax/insert.php",
data: { weight:weightd,user_ids:user_id},
success:function(result){
$("#result1").html(result);
});
<div id="result1">Result div</div>
change $.load("#BuildedBox") to $("#BulderBox").html(response).
When you ask the script for data via ajax, the data provided gets into the "response" variable. As you want to write this data into the div, you must use the ".html" method.
Easier using "load" in this way:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").load("BlockEditor/build.php?block_id=" + id + "&building=" + building + "&nick=" + nick);
}
The "load" method loads data from the server and writes the result html into the element: https://api.jquery.com/load/
EDIT:
As #a-wolff says in the comment, to use POST in load, you should construct like this:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").load("BlockEditor/build.php",{
block_id:id,
building:building,
nick:nick
});
}

Categories