I would like to onsubmit, fetch the positioning of all the divs on the page and return the ids of the divs and the absolute positioning values.
This is the result I get in the console of how the array looks:
[Object { name="app1", coord="10,10"}, Object { name="app2", coord="60,10"}]
One, am I populating the array correctly? Two, how can I print it and return a string via result?
HTML page:
var apps = $(".block"),
positions = [];
$.each(apps, function (index, app) {
var positionInfo = $(app).position();
var input = $(this).attr('id');
var lines = input.split('_');
var appname = lines[0];
positions.push({value: appname + "," + positionInfo.top + "," + positionInfo.left});
console.log(appname + ":" + positionInfo.top + ":" + positionInfo.left);
});
$.ajax({
type: 'post',
cache: false ,
url: 'result_savechange.php',
data: {result:positions},
success: function(resp) {
$('#mainCanvas').html(''); // Clear #content div
$('#mainCanvas').append(resp);
}
});
PHP page:
<?php
$string = '';
foreach($_POST["result"] as $position){
$string .= $position['value'];
}
echo $string;
?>
There's no reason to use JSON here. It's overkill for this scenario. Just do this:
$.ajax({
type: 'post',
cache: false ,
url: 'result_savechange.php',
data: {result: positions},
success: function(resp) {
alert(resp);
}
});
Then in PHP, $_POST["result"] will be an array.
foreach($_POST["result"] as $position){
echo $position['name'];
echo $position['coord'];
}
Related
I am trying to make an ajax call on click on anchor tag dynmically generated from $.each loop for a JSON response.
For Information : #records is my table and .update is the class of anchor tag in that table.
Please be informed that the table is generated dynamically.
Now the problem is that my ajax call is returning nothing even i have checked it error: but no response received. I have tried alerting my var data just before the ajax call and it worked.So the problem starts from the ajax call. Moreover, my server side code is running fine.
// Update existing customers
$("#records").on('click', ".update", function() {
var data = '?'+ $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php",
data: data,
success: function(response) {
console.log(response);
}
});
});
Thanks in advance.
For reference below is the code that generates the table.
// Function to make datagrid
function getRecords() {
$.getJSON("viewcustomers.php", function(data) {
var items = [];
var xTd = '';
var xTr = '';
$.each(data, function(key, val) {
var c = 0;
var id = 0;
$.each(val, function(key1, val1) {
if (c == 0)
{
id = val1;
}
c++;
xTd += '<td>' + val1 + '</td>';
});
xTd += '<td>Edit</td>';
xTd += '<td>Delete</td>';
xTr = '<tr>' + xTd + '</tr>';
items.push(xTr);
xTd = '';
xTr = '';
});
$("#records").append(items);
});
}
Updated the server side code:
page url : localhost/hotel/viewcustomers.php
/**
* Fetch single row for the purpose of update / delete.
*/
if(isset($_GET['update'])){
$customer = new Customers;
$Id = $_GET['update'];
$customer_single = $customer->View_Single_Customer($Id);
echo json_encode($customer_single);
unset($customer);
}
This line is not used the right way var data = '?'+ $(this).attr('id');
Change it like this: var my_id = $(this).attr('id');
Then update the line data: data with data : {id:my_id}
Complete code :
$("#records").on('click', ".update", function() {
var my_id = $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php",
data : {id : my_id},
success: function(response) {
console.log(response);
}
});
});
Or do it like this:
$("#records").on('click', ".update", function() {
var param = '?id='+ $(this).attr('id'); /*notice that I have added "id=" */
$.ajax({
type: "GET",
url: "viewcustomers.php" + param,
/* remove the data attribute */
success: function(response) {
console.log(response);
}
});
});
Modify it as
$("#records").on('click', ".update", function() {
var request = '?id='+ $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php" + request,
success: function(response) {
console.log(response);
}
});
});
I am posting this questions due to the previous one being so long (It might create confusion if I cut parts up in it). I made the question more simple in this post :).
jQuery code:-
function op_prof(id) {
var attr_u_search = $(".u_search").attr('id');
var dataString = 'u_search=' + attr_u_search;
alert(dataString);
$.ajax({
type: "POST",
url: '/script/profile.php',
data: dataString,
cache: false,
success: function(data) {
$('#ui_profile').show();
$('#ui_profile').html(data);
location.hash = 'profile' + 'id=' + dataString;
$(".searchbox").val('');
$("#usr_suggest").hide();
}
});
};
PHP:-
echo "<tr id='" . $id . "' class='u_search' height='40px' onclick='javascript:op_prof(1)'><td width='40px'><img class='avatar' src='$avater' /></td><td>" . $fname_ . " " . $lname_ . "</td></tr>";
}}
I am having trouble retrieving the ID of each div (each one has a unique ID). It seems that the jQuery captures the ID of the div on top (the first div) instead of capturing the IDs of all the divs.
Screen shots:-
http://prntscr.com/118dhv
http://prntscr.com/118dus
P.S: I am 100% sure that there is an error in the jQuery :-> prntscr.com/118eb5
Try to modify the on-click attribute of tr
From this:
onclick='javascript:op_prof(1)
To this:
onclick='javascript:op_prof(this)'
And the js to this:
function op_prof(obj) {
var attr_u_search = obj.id;
....
Since you're using jQuery already, here's a full jQuery solution:
$("tr.u_search").on("click", function() {
var attr_u_search = $(this).attr('id');
var dataString = 'u_search=' + attr_u_search;
alert(dataString);
$.ajax({
type: "POST",
url: '/script/profile.php',
data: dataString,
cache: false,
success: function(data) {
$('#ui_profile').show();
// $('#ui_profile').html(data);
location.hash = 'profile' + 'id=' + dataString;
$(".searchbox").val('');
$("#usr_suggest").hide();
}
});
};
Is first param of 'ob_prof' always = 1?
javascript:op_prof(1)
The attr() method sets or returns attributes and values of the selected elements.
When this method is used to return the attribute value, it returns the value of the FIRST matched element.
use $.each()
api.jquery.com/jQuery.each/
function DoAjax( args )
{
var formData = "?" + $("form[name=" + args.formName + "]").serialize();
$.ajax({
type: "POST",
url: args.url + formData,
data: {
request: args.request
},
success: function (data) {
alert(data);
args.callback.html(data);
},
error: function (a, b, c) {
alert("error: " + a + ", " + b + ", " + c + ".");
}
});
return false;
}
I need to pass in a custom bit of data to my php script called "request" which will denote which process to run on the php page... but I also want to serialize any other form fields on my form. Is this the correct way of doing it (add the serialize to the end of the URL) because I just cannot seem to get anything from my PHP $_POST["whatever"]
EDIT:::///
<?php
$request = $_POST[ "request" ];
if( isset( $request ) )
{
require_once( "includes.php" );
function LogInWithClientCred()
{
$username = CheckIsset( "username" );
$password = CheckIsset( "password" );
echo $_REQUEST["username"];
echo $_GET["username"]; // echos correctly the username.. but I want it to be post data instead!
Please ignore the security awesomeness, it is pseudo for your purpose.
Combine formData and your additional data into one string.
var formData = $("form[name=" + args.formName + "]").serialize() + "&request=" + args.request;
$.ajax({
url: args.url,
data: formData,
type: "POST",
...
})
I am not too sure If i got ur question well, But I think you are appending the form data to URL and using POST in ajax.
Can you try
$_REQUEST["whatever"] to see what you are getting
EDIT
After seeing the commnets I think I now got it
function DoAjax( args )
{
var formData = $("form[name=" + args.formName + "]").serialize();
$.ajax({
type: "POST",
url: args.url,
data: {
request: args.request,
formData:formData
},
success: function (data) {
alert(data);
args.callback.html(data);
},
error: function (a, b, c) {
alert("error: " + a + ", " + b + ", " + c + ".");
}
});
return false;
}
Now $_POST[formData] should work
Edit
see this as well
github.com/maxatwork/form2js
acctually i am not familier much with jquery.. i got this jquery script this is passing variables to the file which is showing data in json format.. but here i'm unable to show that data..plz see this piece of code
$(document).ready(function() {
var globalRequest = 0;
$('#search').bind('keyup', function(event) {
if (event.keyCode == 13) {
searchAction();
}
});
$('#search-link').bind('click', function(event) {
searchAction();
});
var searchAction = function() {
var value = $('#search').val();
var cat = $('#category').val();
var country = $('#country').val();
var page = $('#page').val();
var resultContainer = $('#results');
if (value.length < 3 && globalRequest == 1) {
return;
}
_gaq.push(['_trackEvent', 'Search', 'Execute', 'Page Search', value]);
globalRequest = 1;
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: "q="+value+"&category="+cat+"&country="+country+"&page="+page,
success: function(data){
globalRequest = 0;
resultContainer.fadeOut('fast', function() {
resultContainer.html('');
console.log(data.length);
for (var x in data) {
if (!data[x].price)
data[x].price = 'kA';
if (!data[x].img)
data[x].img = 'assets/images/no.gif';
var html = '<div class="res-container">';
html += '<h2>'+data[x].Title+'</h2>';
html += '<img src="'+data[x].img+'">';
html += '<h3>Price: '+data[x].price+'</h3>';
html += '</div>';
resultContainer.append(html);
}
resultContainer.fadeIn('fast');
});
}
});
};
});
in search.php data is in simple echo.. how to get data from search.php and show here..
sorry for bad english
First,
you shouldn't concatenate your parameters but use a hashmap:
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: {
q : value,
category : cat,
country : country,
page : page }
As your method is (type: 'GET'), just use the ($_GET[param] method) in the php file
<?php
$value = htmlentities($_GET['q']);
$category = htmlentities($_GET['category ']);
$country = htmlentities($_GET['country ']);
In the js callback function, this is how you log the whole response ('something' is a tag) :
success: function(data){
var $xml = $(data);
console.log($xml); // show the whole response
console.log($xml.find('something')); // show a part of the response : <something>value</something>
});
It is a bit hard to understand what your problem is but my guess is that you need to json encode the data before echoing it back in search.php.
simplified example......
eg.
<?php
$somevar = $_GET['a']
$anothervar = $_GET['b']
//Do whatever
$prepare = array('a'=>$result1,'b'=>$result2) //etc..
$json = json_encode($prepare);
echo $json;
exit();
?>
Then you can access the results in the javascript with:
success: function(data){
var obj = $.parseJSON(data);
alert(data.a);
$("#some_element").html(data.b);
}
is it possible to pass the link value of a hyperlink to ajax?
I'm quite new in this branch so maybe I'm doing actually wrong
so I would like to achieve the following:
echo '<ul><li class="all">alle</li>';
foreach(range('a','z') as $i):{
echo '<li class = "searchAbc"><a class="button" href="#"/>'.$i.'</a></li> </ul>';
}
endforeach;
than the ajax
function ajax_abc() {
var url = 'index.php?option=com_glossary&task=abc';
var abc= $(this).attr('href');
// data = 'format=raw'+ '&'+'val=' + $("#search").val();
data = 'val=' + abc + '&' + 'format=raw';
$(document).ready(function(){
function showLoader(){
$('.search-background').fadeIn(200);
}
function hideLoader(){
$('#sub_cont').fadeIn(1500);
$('.search-background').fadeOut(200);
};
$(" li.edit a").click(function(){
ajax_redirect();
});
$(".searchBtn").click(function() {
ajax_search();
});
$('#search').keyup(function(e) {
if(e.keyCode === 13) {
ajax_search();
}
});
function ajax_search(search) {
var url = 'index.php?option=com_glossary&task=getvalues';
data = 'val=' + $("#search").val() + '&' + 'format=raw';
$('#sub_cont').fadeIn(1500);
showLoader();
$.ajax({
type: "GET",
url: url,
data: data,
success: function(data) {
hideLoader();
$('div.default_order').hide;
$('#sub_cont').html(data);
}
}); // ajax
}
function ajax_abc(abc) {
var url = 'index.php?option=com_glossary&task=abc';
data = 'val=' + abc + '&' + 'format=raw';
//... Add jQuery.load() codes here ...
$.ajax({
type: "GET",
url: url,
data: data,
success: function(data) {
hideLoader();
$('div.default_order').hide;
$('#sub_cont').html(data);
}
}); // ajax
}
$(".stripeMe tr").mouseover(function(){$(this).addClass("over");}).mouseout(function(){$(this).removeClass("over");});
$(".stripeMe tr:even").addClass("alt");
});
do you mean something like this?
$('a.button', 'li.searchAbc').click(function(){
var url = 'index.php?option=com_glossary&task=abc';
var abc = $(this).attr('href');
var ajaxParam = {
val: abc,
format: 'raw'
};
$.post(url, ajaxParam, function(result){
//process result
});
// or using GET
/*
$.get(url, ajaxParam, function(result){
//process result
});
// */
return false;
})
note: attribute href of your <a> tag is '#'.
Ok try something like the following
Change
echo '<li class = "searchAbc"><a class="button" href="#"/>'.$i.'</a></li> </ul>';
to
echo '<li class = "searchAbc"><a class="button" href="#" onClick="ajax_abc(\''.$i.'\')"/>'.$i.'</a></li> </ul>';
Then put in your javascript
function ajax_abc(abc) {
var url = 'index.php?option=com_glossary&task=abc';
data = 'val=' + abc + '&' + 'format=raw';
//... Add jQuery.load() codes here ...
}
In my case this worked form me !!
function deleteImage(data1,data2){
$.ajax({
type: "POST",
url: "remove_unwanted_files.php",
data: "nameImage="+data1+"&idImage="+data2,
success: function(msg){
alert( "Data Saved: " + data1 + " " + data2);
//Code for Anything you want
}
});