I have a form that contains several of the following types of elements
<input type="hidden" name="selected_models[]" value="1">1</td>
<input type="hidden" name="selected_models[]" value="2">2</td>
<input type="hidden" name="selected_models[]" value="3">3</td>
<input type="hidden" name="selected_models[]" value="4">4</td>
I am trying to pass this array, along with all my other form data to a jQuery $.post function, but I can't access the data in php correctly.
I've tried to pass it using the following (jQuery):
var _data = { models: $('input[name="selected_models[]"]').serialize() }
and then access it in PHP using:
$models = $_POST['models'];
just for the purpose of trying to check the data, I pass this variable to the ajax response, and log it back to the console using:
Php
$response = jseon_encode(
array(
'success' => true,
'models' => json_encode($models)
)
);
and
JS
console.log(JSON.parse(response.models)
Which outputs the following:
selected_models%5B%5D=37&selected_models%5B%5D=51&selected_models%5B%5D=57
so, honestly now I'm just stuck with how to loop through those values in php so I can actually do something with them. Ideally, I would be able to do something like:
Php
foreach ( $models as $model ) {
$id = $model.selected_models
// Do more stuff
}
But this isn't working. What am I doing wrong?
I ended up solving this in jQuery and passing a parsed value to PHP, instead:
var uniqueModels = [];
if ( document.getElementById('acInheritFromVehicle').checked ) {
var models = jQuery( 'input[name="selected_models[]"]:checked');
var modelIDs = [];
//console.log(models);
models.each(function() {
if( jQuery.inArray( ))
modelIDs.push( jQuery(this).val() );
});
uniqueModels = unique(modelIDs);
uniqueModels = jQuery.grep( uniqueModels, function(value) {
return value != 0
});
//console.log(uniqueModels);
}
You were doing it correctly, just some minor PHP tweaks and you would have got it. Once you serialize your data and sent to PHP you can always check what that array looks like by using print_r($models) function.
To loop through your $models array, do the following:
foreach($models as $model) {
echo 'Value of hidden input is: ' . $model;
echo '<br />';
}
$model will represent an actual value received through PHP request. Check out this example
Related
I have the need to receive javascript variables in PHP so I set up my Ajax call and script, I have verified that AJAX is sending back the proper response it just seems like server side is not wanting to actually pull the information. Here is my javascript
$("#payments2").on("change", function() {
$("#p1").val($(this).find("option:selected").text());
var Id = $(this).find("option:selected").attr('value');
var Ids = $("#payments").find("option:selected").attr('value');
$.post("postit.php", {
Id: Id,
Ids: Ids
}, function(data){
var theResult = data;
}, 'json' );
});
$("#exchange").on("change", function() {
var am = $(this).attr('value');
var fee = $("#fee").attr('value');
var cost = $("#cost").attr('value');
var perc = fee / 100;
var tot = perc * am;
var total = am - tot - cost;
$("#return").val(total);
});
and here is my PHP variable call
<li>
<label for="exchange">Amount to Exchange</label>
<input type="text" id="exchange" name="exchange" maxlength="100">
<span>Amount to Exchange</span>
</li>
<?php
$amounts = $db->query("SELECT * FROM `exchange` WHERE `fromp` = '".$_POST['fromp']."' AND `top` = '".$_POST['top']."'");
$amo = $amounts->fetch_assoc();
?>
<input type="hidden" id="fee" name="fee" value="<?php echo $amo['fee'] ?>" />
<input type="hidden" id="cost" name="pay" value="<?php echo $amo['cost'] ?>" />
<li>
<label for="return">Amount to Receive</label>
<input type="text" id="return" name="return" maxlength="100" value="">
<span>Amount you will receive</span>
</li>
Since I can clearly tell that my Ajax call is sending back the proper information and I am not getting any errors in my query then I am unsure as to why my values for fees and cost aren't changing causing me to receive NaN in my return text box.
Here is also the contents of my postit.php file
$Id= isset($_POST['Id']) ? $_POST['Id'] : '';
$Ids= isset($_POST['Ids']) ? $_POST['Ids'] : '';
include "connect.php";
$que = $db->query("SELECT * FROM `exchange` WHERE `fromp` = '".$Ids."' AND `top` = '".$Id."'");
/* Get query results */
$results = $que->fetch_assoc();
/* Send back to client */
echo json_encode($results);
exit;
This is my first time using posting variables from javascript to php so I am sure I have done something wrong, or maybe there is a way to get the information that was passed by the script using javascript, perhaps a way to get the variables I need within my javascript function rather than the mysql query?
You're not setting the values for the fields from your json response, try
$.post("postit.php", {
Id: Id,
Ids: Ids
}, function(data){
$("#fee").val(data['fee']);
$("#cost").val(data['cost']);
}, 'json' );
Perhaps I'm missing something, but your jQuery is sending 'Id' and 'Ids' as the form data, and the PHP is trying to use 'fromp' and 'top'.
Additionally, it doesn't appear that your response handler is doing anything with the DOM. Have you inspected the Network panel of your chrome debugger to see what the PHP script is responding with?
I wrote a php function which does the job perfectly if it is called standalone by PHP page. but I want to integrate this function in a program and want to call it when a button is clicked.
My PHP function is
function adddata($mobile){
// outside of this function, another database is already selected to perform different
//tasks with program's original database, These constants are defined only within this
//this function to communicate another database present at the same host
define ("HOSTNAME","localhost");
define ("USERNAME","root");
define ("PWD","");
define ("DBNAME","budgetbot");
// link to mysql server
if (!mysql_connect(HOSTNAME,USERNAME,PWD)) {
die ("Cannot connect to mysql server" . mysql_error() );
}
// selecting the database
if (!mysql_select_db(DBNAME)) {
die ("Cannot select database" . mysql_error() );
}
//inserting phone number into database
$query = "INSERT INTO `verify_bot` (phone_number) values('".$mobile."')";
if(!mysql_query($query)){
die( mysql_error() );
}
// wait for 2 seconds after adding the data into the database
sleep(2);
$query = "SELECT * FROM `verify_bot` WHERE phone_number = ".$mobile;
$result = mysql_query($query) or die( mysql_error() );
// if more than one records found for the same phone number
if(mysql_num_rows($result) > 1){
while($row = mysql_fetch_assoc($result)){
$data[] = $row['response'];
}
// return an array of names for the same phone numbers
return $data;
}else{
// if only one record found
$row = mysql_fetch_assoc($result);
$response = $row['response'];
return $response;
}
// end of function
}
HTML Code is written as
<form action="self_page_address_here" method="post" accept-charset="utf-8" class="line_item_form" autocomplete="off">
<input type="text" name="mobile_number" value="" placeholder="(000) 000-0000" class="serial_item" size="20" id="serialnumber_1" maxlength="10" />
<button id="verify" class="btn btn-primary">Verify</button>
<button id="cname" class="btn btn-primary"><!-- I want to print return value of the php function here --></button>
</form>
I want to call this function and assign the return value to a javascript variable by ajax/jquery.
My code to do this is...
<script type="text/javascript" language="javascript">
$('#verify').click(function(){
var value = $( ".serial_item" ).val();
//I have some knowledge about php but I am beginner at ajax/jquery so don't know what is happening below. but I got this code by different search but doesn't work
$.ajax({
url : "add_data.php&f="+value,
type : "GET"
success: function(data){
document.getElementById("cname").innerHTML = data;
}
});
});
</script>
I would like to share that the above javascript code is placed outside of documnet.ready(){}
scope
Any help would be much appreciated.
Thanks
Because your <button> elements have no type="button" attribute, they're supposed to submit the form using normal POST request.
You should either use type="button" attribute on your buttons, or prevent default form submission using event.preventDefault():
$('#verify').click(function(event){
event.preventDefault();
var value = $( ".serial_item" ).val();
$.ajax({
// there's a typo, should use '?' instead of '&':
url : "add_data.php?f="+value,
type : "GET",
success: function(data){
$("#cname").html(data);
}
});
});
[EDIT] Then in add_data.php (if you call AJAX to the same page, place this code at the top, so that no HTML is rendered before this):
if(isset($_GET['f'])){
// call your function:
$result = adddata(trim($_GET['f']));
// if returned value is an array, implode it:
echo is_array($result) ? implode(', ', $result) : $result;
// if this is on the same page use exit instead of echo:
// exit(is_array($result) ? implode(', ', $result) : $result);
}
Make sure you escape the value on $query.
It's my first post on stackoverflow so excuse any of my faux pas regarding code posting etc., guys.
So I am writing this social network and have most of the things working except for I cannot figure out why I cannot update the profile information using jQuery. It only seems to work for the first field (name), it posts data to the server and returns it. As long as I want to work on the second field (about) it returns an empty box and data is not inserted. I tried checking the spelling, typos etc. but I think the fault lays in the logics.
HTML:
<br/>Name<br/>
<input type="text" size="50" id="input_text" value="<?php echo getUser($_SESSION['user_id'], 'name'); ?>"/>
<input type="button" value="Change..." id="name_update_btn"/>
<br/>About<br/>
<input type="text" size="50" id="input_text_2" value="<?php echo getUser($_SESSION['user_id'], 'about');?>"/>
<input type="button" value="Change..." id="about_update_btn"/>
jQuery:
$( document ).ready(function(){
$( '#name_update_btn' ).click( function(){
$.post( "update.php?person_name=true", {
person_name : $ ('#input_text').val()
}, function( data ){
$('#input_text').val( data );
})
});
$( '#about_update_btn' ).click( function(){
$.post( "update.php?about=true", {
about : $ ('#input_text_2').val()
}, function( data ){
$('#input_text_2').val( data );
})
});
});
PHP (update.php):
if(isset($_POST['about'])==true){
update($_SESSION['user_id'], 'about', $_POST['about']);
}
if(isset($_POST['avatar'])==true){
update($_SESSION['user_id'], 'avatar', $_POST['avatar']);
}
if(isset($_POST['person_name'])==true){
update($_SESSION['user_id'], 'name', $_POST['name']);
}
Anyone who could help me with that?
I'm no php expert but it seems to me that the second use of POST should user person_name instead of name; when used within the update method call...
So like this
if(isset($_POST['person_name'])==true){
update($_SESSION['user_id'], 'name', $_POST['person_name']);
}
Perhaps you should just keep things consistent and either use name or person_name and don't mix the 2?
So your jquery is like this
$.post( "update.php?name=true", {
name : $ ('#input_text').val()
}, function( data ){
$('#input_text').val( data );
})
and your php is like this
if(isset($_POST['name'])==true){
update($_SESSION['user_id'], 'name', $_POST['name']);
}
your html already uses name
value="<?php echo getUser($_SESSION['user_id'], 'name'); ?>"
Update your jquery function with LIVE method like -
$('#name_update_btn').live('click', function(){
// code
});
This section was wrong
Edit:
Now I see what's the problem. in the one but last line in PHP you have $_POST['name'] and it should be $_POST['person_name']. Besides - you don't have to do
if(isset($_GET['person_name'])==true){
This will be enough:
if(isset($_GET['person_name'])){
For the future folks that might be stuck with something similar - I figured out what the problem was.
After fixing the naming problems as guys kindly pointed out I realized that my function "update" used here:
if(isset($_POST['person_name'])==true){
update($_SESSION['user_id'], 'name', $_POST['person_name']);
}
was not returning any values and looked like this:
function update($user_id, $field, $update){
$query = mysql_query("UPDATE `users` SET `$field` = '".$update."' WHERE `id` = ".(int)$user_id);
}
Therefore no value was returned and also no value was entered back to the form. Fixed function here:
function update($user_id, $field, $update){
$query = mysql_query("UPDATE `users` SET `$field` = '".$update."' WHERE `id` = ".(int)$user_id);
$query2 = mysql_query("SELECT `$field` FROM `users` WHERE `id` = ".(int)$user_id);
while($row = mysql_fetch_assoc($query2)){
$updated = $row[$field];
}
return $updated;
}
i am having a probelem with ajax multiple delete. I've sucessfully set the values of the checkbox slected in a variable.
the problem i have to solve is how to get the value of the sent array in php.
here is the ajax post code
<script>
$("#delete-btn").click(function(e){
e.preventDefault();
var id = new Array();
$(".check:checked").each(function() {
id.push($(this).attr('value'));
});
$.post("../ajax/multiDelete.php",{id:id},function(data){
alert(data);
});
});
</script>
now, the php page
<?php
if(isset($_POST['id'])){
$id = array($_POST['id']);
foreach($id as $value){
echo $value;
}
}
?>
when the data is alerted, i only get "array";
i do not know about JSON, so if there is anything i can do without it then your help is most appreciated! thanks : D
Since id is an array and in your code you are wrapping it inside an array again. Instead of that,do this :
<?php
if(isset($_POST['id'])){
// Don't use array($_POST['id']) as id is already an array
$id = $_POST['id'];
foreach($id as $value){
echo $value;
// Here you'll get the array values
}
}
?>
If you want retun array from php - user json_encode()
echo json_encode(array($_POST['id']));
P.S. JS function alert() can`t print arrays or object. Use console.log(data) and you will see result in developer console of your browser.
This is not related to your question, but I just wanted to show you a better way of getting the id values, without creating a new array variable and then pushing items into the array, by using the jQuery .map() method:-
$("#delete-btn").click(function (e) {
e.preventDefault();
// Get all the values in the array 'id' variable
var id = $(".check:checked").map(function () {
return this.value || 0;
}).get();
$.post("../ajax/multiDelete.php", { id: id }, function (data) {
alert(data);
});
});
Hope this helps!
Don't pass array variable in AJAX. Convert id array to JSON using JSON.stringify(id).
In PHP backend,use
<?php $val = json_decode($_REQUEST['id']);
foreach($val as $ids){
echo $ids;
}
use $val array to proceed further in php.
You have to access your checked value by-
<?php
if(isset($_POST['id'])){
$id = array($_POST['id']);
foreach($id as $value){
foreach($value as $value1){
echo $value1;
}
}
}
?>
Because this is an array inside array.
I use the following to retrieve some html using Jquery:
index.php
$.post(
'get-products.php',
$("#offerForm").serialize() + '&lastid=' + highest,
function(data) {
$('#demo').html(data);
}
Is it possible to also retrieve a value of a variable from get-products.php, example:
get-products.php
<? echo $htmlOutput;
echo $variable; ?>
index.php
$.post(
'get-products.php',
$("#offerForm").serialize() + '&lastid=' + highest,
function(data) {
$('#demo').html(data);
//variable processing statement goes here
}
You should try to communicate in JSON.
This way in get-products.php you can return an array json encoded containing your html, some variables
and then in jquery you'll get data.variable1, data.variable2, etc...
Do it by calling post with a third parameter ("json")
http://api.jquery.com/jQuery.post/
$.post(
'get-products.php',
$("#offerForm").serialize() + '&lastid=' + highest,
function(data) {
$('#demo').html(data.html);
variable1 = data.variable1;
}
And in get-products.php return
echo json_encode(array('html' => '<div>some html</div>', 'variable1'=>xxxx));
yes you could, use json for that. Example:
<?php
$html = "<p>some html</p>";
$data = array('key' => 'value');
$output = json_encode(array('html' => $html, 'data'=>$data));
echo $output;
?>
Now in jquery retrieve the data like:
function(data) {
$('#demo').html(data.html);
// and do something with data.data
alert(data.data.key); // alerts "value"
}
You could instead return JSON from your get-products.php page, like this:
<?
$arr = array('htmlOutput' => $htmlOutput, 'otherVariable' => $variable);
echo json_encode($arr);
?>
jQuery:
$.post(
'get-products.php',
$("#offerForm").serialize() + '&lastid=' + highest,
function(data) {
$('#demo').html(data.htmlOutput);
var x = data.otherVariable;
}
)
the problem is that you set as url a local path on the, that the js request is not understanding in a request, because it is running local on your system.
simple replace the 'get-products.php' with an url like http://yourhomepage.com/get-products.php
JSON is the best option, but if for some reason you're unable to implement this, you could set a data attribute on the outer element in the html returned, and then read it using jQuery.data().
html
<div class="response-outer" data-variable-name="value">
...
</div>
NOTE: the data attribute will be automatically parsed by jQuery and if it is in JSON format will be converted into a javascript object
jQuery
$.post(
'get-products.php',
$("#offerForm").serialize() + '&lastid=' + highest,
function(data) {
$('#demo').html(response);
var x = $("#demo").find(".response-outer").data("variable-name");
}
)
There are several options to do that, depending on your data. They are all based on the same concept: Add your data to the DOM.
You can return a hidden input with some value in it:
<input id=data-object type=hidden value=myvalue />
This works for single, small values.
You can add the data to the relevant DOM elements:
<div id=some-div custom-value=myvalue>
that way you can attach extra info to specific elements around the DOM
You can add a Javascript object inside a script tag, and access it with client code:
<script type=text/javascript>
var myData = {attribute: value, someObject:{anotherAttribute: value}};
</script>