pass arrays and variables from jquery to php at the same time - php

I want to pass arrays and other variables from jquery code to php using post request but I don't know how to pass arrays and variables at the same time.
I tried this code:
var new_location_name = "";
var new_location_id = "";
var old_location_name = [];
var selected_name = [];
var selected_id = [];
var user = '<?php echo $current_user ;?>';
$(document).ready(
$("#transfer").click(function(){
$.ajax({
type: "POST",
url: "update.php",
data: "username="+user+"&new_location_name="+new_location_name+"&new_location_id"+new_location_id+"&"+{ old_location_name : old_location_name }+"&"+{ selected_name : selected_name }+"&"+{ selected_id : selected_id },
});
return false;
});
});

Create an object, serialize it and send it:
var obj = {
key1: 'value1',
key2: ['one','two','three'],
key3: {
key3_0: 'value3_0'
}
}
var jsonData = JSON.stringify(obj);
$.ajax({
method: "POST",
url: "update.php",
data: jsonData
});

JQuery Data:
data:
{
username: user,
new_location_name: new_location_name,
new_location_id: new_location_id,
old_location_name: old_location_name,
selected_name : selected_name,
selected_id : selected_id
}
In your PHP Script
<? $oldLocationName = $_REQUEST['old_location_name']; ?>
and so on.

You can pass multiple parameters as arrays or strings the same. The left hand side of the data is the value that the API is expecting as the parameter name.
var new_location_name = "";
var new_location_id = "";
var old_location_name = [];
var selected_name = [];
var selected_id = [];
var user = '<?php echo $current_user ;?>';
$(document).ready(
$("#transfer").click(function(){
$.ajax({
type: "POST",
url: "update.php",
data: {username: user,
new_location_name: new_location_name,
old_location_name: old_location_name
}
});
return false;
});
});
You can read more in this question: Pass Multiple Parameters to jQuery ajax call

Try this snippet
var array = [];
$.ajax({ url: 'update.php',
data: {'array' : array},
type: 'post',
dataType:'json',
success: function(output) {
alert(output);
},
error: function(request, status, error) {
alert("Error");
}
});

First time Check file, this script must be in .php file, not .js file;

Related

serializeArray not sending the data

This is a sample of the php and javascript.
<form id="image-comment" method="post" action="includes/insert_image_comment.php">
<textarea id="comment-area" name="comment-area"></textarea>
</form>
// javascript
$("#image-comment").submit(function(event) {
event.preventDefault();
var action_url = event.currentTarget.action;
var id = 4;
var params = $("#image-comment").serializeArray();
params.push({imageid: id});
$.ajax({
url: action_url,
type: 'post',
data: params,
success: function(data) {
alert(data);
}
});
});
// insert_image_comment.php
echo $get_image = $_POST['imageid'];
$comment = $_POST['comment-area'];
When echoing $_POST['imageid'] i get an error 'Undefined index: imageid'.
When echoing $_POST['comment-area'] it's ok.
Why one works and the other not?
Thanks
Try to use the format that serializeArray uses: Example:
$("#image-comment").submit(function(event) {
event.preventDefault();
var id = 4;
var params = $("#image-comment").serializeArray();
params.push({name: 'imageid', value: id}); // this one
$.ajax({
url: document.URL,
type: 'POST',
data: params,
success: function(data) {
alert(data);
}
});
});

Longpolling : Sending extra variable

I am doing a simple longpolling using jquery and php.. It's going on great.. but when I am sending and extra variable.. then the longpolling is not showing the current value that it's supposed to show... My code is below..
The one which is working :
function getContent(time)
{
var queryString = {'time': time};
$.ajax(
{
type: 'GET',
url: 'test.php',
data: queryString,
success: function(data){
var obj = jQuery.parseJSON(data);
$('#response').html(obj.data_from_file);
getContent(obj.time);
},
error : function(){
getContent(time);
}
}
);
}
$(document).ready(function(){
getContent();
});
The one which is working on page refresh.. but longpolling is not happening...
function getContent(time)
{
var name = '<?php echo $name; ?>';
var queryString = {'time': time, 'name':name};
$.ajax(
{
type: 'GET',
url: 'test.php',
data: queryString,
success: function(data){
var obj = jQuery.parseJSON(data);
$('#response').html(obj.data_from_file);
getContent(obj.time);
},
error : function(){
getContent(time);
}
}
);
}
$(document).ready(function(){
getContent();
});
PHP side...
while (true) {
$last_ajax_call = isset($_GET['time']) ? (int)$_GET['time'] : null;
$name = $_GET['name'];
//rest of the code...............
}
else{
sleep(1);
continue;
}

How to use jquery VALUE in an ajax success function

I cannot use value div name in fourth-last line
I want to use div name in Ajax function in $("divname").html(data);
$('.edit').click(function() {
var object = $(this);
var rowvalue = object.attr('id');
var rowvalue_array = rowvalue.split('_');
var id = rowvalue_array[1];
var comment = $('#comment_'+id).val();
var divname = '#'+id;
var varData = 'id='+id+'&comment='+comment;
console.log(varData);
$.ajax ({
type: "POST",
url: "edit_field.php",
data: varData,
success: function(data) {
$("divname").html(data);
}
});
return false;
});
Use the following code..
$.ajax ({
type: "POST",
url: "edit_field.php",
data: varData,
success: function(data) {
$(divname).html(data);
}
});
Please replace your line as below :
$(divname).html(data);
remove quata (")
divname is variable
or you can use as below :
$("#"+id).html(data);
Try this:
$.ajax ({
type: "POST",
url: "edit_field.php",
data: varData,
success: function() {
$("divname").html($(this).data);
}
});
Why are you accessing the element by id when u have the element.....try
$(object).html(data);

How to pass mutiple values from ajax to php file

I have 3 values stored in 3 seperate DIV tags and i want it to pass via ajax to php file. I have working code and stuck in passing all values to php file. Any ideas hoe to do it.
This is my js code:
$('#button').click(function(){
var slider_value = $('#slider_value').text();
var slider1_value = $('#slider1_value').text();
var slider2_value = $('#slider2_value').text();
$.ajax({
url:'placeDetailSend.php',
type: 'POST',
data: 'slider_value='+slider_value,
success: function(data){
$('#test').html(data);
}
});
});
and this it my php file:
<?php
if (isset($_POST['slider_value'])||($_POST['slider1_value'])){
echo $slider_value = $_POST['slider_value'];
echo $slider1_value = $_POST['slider1_value'];
}?>
Values are seperated by & as in a URL:
data: 'slider_value='+slider_value+'&slider1_value='+slider1_value+'&slider2_value='+slider2_value,
jQuery Code:
$('#button').click(function(){
var slider_value = $('#slider_value').text();
var slider1_value = $('#slider1_value').text();
var slider2_value = $('#slider2_value').text();
$.ajax({
url:'placeDetailSend.php',
type: 'POST',
data: {var1: slider_value, var2: slider1_value,var3:slider2_value },
success: function(data){
$('#test').html(data);
}
});
});
Use This php code for fetching values
<?php
echo $_POST['var1'];
echo $_POST['var2'];
echo $_POST['var3'];
?>
$('#button').click(function(){
var slider_value = $('#slider_value').text();
var slider1_value = $('#slider1_value').text();
var slider2_value = $('#slider2_value').text();
$.ajax({
url:'placeDetailSend.php',
type: 'POST',
data: {slider: [slider_value, slider1_value, slider2_value]},
success: function(data){
$('#test').html(data);
}
});
});
And in php file,
<?php
if (isset($_POST['slider'])){
$slider_value = $_POST['slider'];
echo '<pre>' . print_r($slider_value) . '</pre>';
}
?>
Try,
data: 'slider_value='+slider_value+'&slider1_value='+slider1_value+'&slider2_value='+slider2_value;
OR
data:{slider_value:slider_value,slider1_value:slider1_value,slider2_value:slider2_value}
You will get more about jquery ajax here
You are only passing one div value in the datastring. Pass all the values like this:-
$('#button').click(function(){
var slider_value = $('#slider_value').text();
var slider1_value = $('#slider1_value').text();
var slider2_value = $('#slider2_value').text();
$.ajax({
url:'placeDetailSend.php',
type: 'POST',
data: 'slider_value='+slider_value + '&slider1_value='+slider1_value + '&slider2_value='+slider2_value,
success: function(data){
$('#test').html(data);
}
});
});
$.ajax({
url:'placeDetailSend.php',
type: 'POST',
data: {
'slider_value': slider_value,
'slider_value1': slider_value1,
'slider_value2': slider_value2
},
success: function(data){
$('#test').html(data);
}
});
});
Firstly, you could store your data differently (in an array) like so:
var slider_values = new Array();
silder_values.push($('#slider_value').text(),$('#slider_value2').text(),$('#slider_value3').text());
And then, you can simply pass this array as a data object to the ajax request like so:
$.ajax({
url:'placeDetailSend.php',
type: 'POST',
data: {'slider_values': slider_values},
success: function(data){
// Do whatever here
}
});
});
However, if you use this method, you must be sure to loop through the $_POST['slider_values'] in PHP as it is now an array not a string. This is pretty simple:
foreach($_POST['slider_values'] as $value){
// Write the current value
echo $value
}

Print json from mysql

Hi all I have a site developed in codeigniter.
In some function I have to retrieve data from mysql and print the result in javascript because is an ajax call.
Thi is my php function to retrieve data:
public function getCityByNameOnly($name) {
$query = $this->db->query('SELECT * FROM city WHERE name LIKE "%'.$name.'%" ');
$city = array();
foreach ($query->result() as $row)
array_push($city, $row);
return json_encode($city);
}
}
And this is my ajax call:
$('#ricerca-ajax').keyup(function(){
var val = $(this).val();
if (val.length>2){
var site_url_city ="<?php echo(site_url('/city/get_city_by_text')); ?>";
$.ajax({
url: site_url_city,
type: "POST",
data: {search: val},
dataType: "text",
success: function(data) {
console.log(data);
for(var i=0;i<data.length;i++)
{
$('#msgid').append(data[i].name_en + '<br> ');
}
}
});
}
})
I append the result into a div but is always undefined.
This is the console.log of my created json:
{"id":"125","name_it":"Lèsina (Hvar)","name_en":"Hvar","nation_id":"23","region_id":"0","active":"1"},{"id":"127","name_it":"Trogir (Traù)","name_en":"Trogir","nation_id":"23","region_id":"0","active":"1"},{"id":"1088","name_it":"Città del Capo","name_en":"Cape Town","nation_id":"101","region_id":"0","active":"1"}]
How to print this json into my success function in javascript?
Thanks
change the datatype:"json" in the ajax will solve the issue
$('#ricerca-ajax').keyup(function(){
var val = $(this).val();
if (val.length>2){
var site_url_city ="<?php echo(site_url('/city/get_city_by_text')); ?>";
$.ajax({
url: site_url_city,
type: "POST",
data: {search: val},
dataType: "json",
success: function(data) {
console.log(data);
for(var i=0;i<data.length;i++)
{
$('#msgid').append(data[i].name + '<br> ');
}
}
});
}
})

Categories