This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What to do with php after jquery .serialize()
I am serializing the following form using jQuery, sending it to the server using ajax and deserializing using PHP.
When I deserializing I get the error:
Error at offset 0 of 39 bytes
<form id="Marriage" style="display: none">
<input type="text" name="city" class="txtt" value="city"/>
<input type='button' value='Apply' id="msendsend" class="sendaf" name="jobforming"/>
</form>
Here is the jquery function to send this form
$(document).ready(function () {
$('#msendsend').click(function () {
var id=getParam('ID');
$.ajax({
type:'POST',
url:"send.php",
data:{option:'apply', sr:$("form").serialize()},
success:function (jd) {
}
});
});
});
This is the server code:
if($_REQUEST['option']=='catapply') {
$sc=$_POST['sr'];
mysql_query("insert into user_data(uid,data) values('$session->userid','$sc')");
}
And here I am unserializing .
$sql = mysql_query("SELECT * from user_data");
while ($row = mysql_fetch_array($sql)) {
$un = unserialize($row['data']);
$city=$un['city'];
echo $city;
}
The data in the database is shown as
to=&select_category=25&msg=&city=laho
jQuery's serialize function is way different from PHP's. It creates a query string, as you can see in your database.
This format may be decoded in PHP with the parse_str function. Use it instead of unserialize.
Instead of parsing it manually, though, you may be better off posting your form data as the query string:
data: $("form").serialize(),
You can add a hidden field to convey the option=apply value.
That way, you don't have to decode anything (it'll already be in $_POST) and you may insert every value in a separate row. It'll save you a lot of trouble in the future, e.g. when there's more data and you need to search through it.
Related
I am a new user of ajax; so...
I am using ajax on a simple html page to access a php script to receive data, calculate results using data in an mysql table, and echo results in a div on the same page. My javascript statement to do this is:
$.post('ajax/phpscript.php', {
postuser:theuser,
postname:uans1
}, function(data) {
$('#outputdiv1').html(data);
}
);
The php echo output goes to a div on the main page called outputdiv1.
I got that part; no problem. Not sure exactly how it works, but it does work.
I would also like to echo output to a different div (which I will call outputdiv2) on the same page, using the php script. In my php script, How do I refer to or echo output this other div?
I guess I could have a second $.post statement in the javascript code, accessing a second php script. But that would force me to access the mysql database a second time. Doesn't seem efficient to me.
Is there a better way to do this?
Thanks.
HTML code is here:
theuser is defined earlier
<table width=400 align=center><tr><td>
There is a question here, with 2 possible answers:<p>
<form>
<input type=radio style="width:22px; height:22px" name="ques1" id="opt1" value="answer 1" onclick="post1()"> answer 1<br>
<input type=radio style="width:22px; height:22px" name="ques1" id="opt2" value="answer 2" onclick="post1()"> answer 2<br>
</form>
<div id="outdiv1">first response from php will go here, beneath the question.<br></div>
<script type="text/javascript">
function post1() {
var uans1 = "none"
if (document.getElementById("opt2").checked) {
uans1 = "answer 2"
}
if (document.getElementById("opt1").checked) {
uans1 = "answer 1"
}
$.post('ajax/phpscript.php',{postuser:theuser,postname:uans1}, function(data) {$('#ans1div').html(data);});
}
</script>
</td>
<td width=20%>
<div id="outputdiv2">
second response from php will go here, to the right of the question.<p>
</div>
</td>
</tr></table>
first response will not be the same as the second response.
You could use JSON to communicate and return an array. something like this in js
$.ajax({
url: 'ajax/phpscript.php',
method: 'POST',
data: {
postuser: theuser,
postname: uans1
},
dataType: 'JSON'
}).done(function(data) {
if ($.isArray(data)) {
$('#outputdiv1').html(data[0]);
$('#outputdiv2').html(data[1]);
}
});
And your php script should do something look like this
<?php
include('dbconnection.php');
$result = [];
//SELECT data for div1 (part you already have)
$result[] = $mysql_result_as_html_for_outputdiv_1; // In your case this would be a html string
//SELECT other data for div2
$result[] = $mysql_result_as_html_for_outputdiv_2; // In your case this would be a html string
header('Content-Type: application/json');
echo json_encode($result);
?>
An even more clean solution would be to just return the data as objects from php and make some templates in js suitable for your data.
You need to understand this: who write in the div is javascript, not php, cause you are using ajax. Ajax is a way to comunicate with php, and give a response. Now you need to handle this response with javascript.
If you want to put the same content in outputdiv1 and outputdiv2, you not need to post ajax again, only write it in two divs.
$.post('ajax/phpscript.php',{postuser:theuser,postname:uans1}, function(data) {$('#outputdiv1').html(data);$('#outputdiv2').html(data);});
if you want different data i suggest you think the system to get all result that you need in one post request and return it in a json format (see http://php.net/manual/es/function.json-encode.php), so you can handle better with JSON.parse() in client side.
I have some problems loading input field from html using php. I am using jQuery Ajax $.post function to send my data from input filed to php file in order to do the query from the database.
I have fixed the code. Code below is working perfectly.
Here is the html from my main page
<input class="detail" maxlength="60" name="detail" placeholder="Type to search">
<button class="searchbtn" name="search">Search</button>
and this is the jQuery Ajax part
$(".searchbtn").click(function(e) {
makeAjaxRequest();
});
function makeAjaxRequest(){
var input = $(".detail").val();
$.post("search.php",{detail:input},function(data,status){
$('#resultTable tbody').html(data);
});
Then last part is the php file (search.php)
if (isset($_POST['detail'])) {
$data = $_POST['detail'];
$query = "SELECT * FROM products WHERE ".%data;
$result = $conn->query($query) or trigger_error($mysqli->error."[$sql]");
while($row = $result->fetch_assoc()){
$rows[] = $row;
}
}
Now it worked perfectly. Thanks for the answer.
You are extracting $_POST['detail'] on your server side page, but while sending on client side, you are sending like this, $.post("search.php",input.
Data should be sent data as PlainObject or string. I mean, every POST data should have some index to get referenced on the other end.
Since you are extracting with index detail, add detail on following like:
$.post("search.php",{detail:input},function(data,status){
See : jQuery : $.post()
currently you're just sending a string with no key/value. You need to send a key/value pair as your data parameter, either as a string or an object (object is safer, as it'l get automatically urlencoded)
$.post("search.php",{detail:input},function(data,status){
You could try this.
function makeAjaxRequest(){
var input = $(".detail").val();
$.post("search.php",
{detail: input},
function(data,status){
$('#resultTable tbody').html(data);
});
}
This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 8 years ago.
I have a php function that simply get me the value of an array given the key.
Example:
<?=__('mykey')?>
Return the value of my array.
I would to call this function after an ajax jQuery call, with a param.
The POST give me a json array, and I need to use the previous funct like this
$.ajax({
url: myfile.php',
type: 'POST',
data: $('#contact_form').serialize(),
dataType: 'json',
}).done(function(data) {
str = '';
$.each(data, function(index) {
$('#message').html(" <?=__('"+index+"')?> ");
});
})
The problem is that the index value inside the $.each function is not passed to php...there is a way to solve it or i have to do something like this?
$.each(data, function(index) {
switch(index):{
case 1: $('#message').html(" <?=__('1')?> "); break;
case 2: $('#message').html(" <?=__('2')?> "); break;
case 3: $('#message').html(" <?=__('3')?> "); break;
...
}
});
I've had to do something similar and actually used jQuery to set the value on a hidden input for me to grab later.
$('#some-hidden-input').val(yourvalue)
Make sure this hidden field exists and is in the rendered HTML
Then the PHP can simply grab that input value on POST.
$myVar = $_POST['some-hidden-input'];
To pass variables to PHP via Javascript, the only reasonable way is to use AJAX, but you do it only when you are posting something. If not, the best way is to have a hidden input field.
Based on different conditions you define, you can set the hidden input field to carry the value you want to apply it to.
To assign the value to <input name="A" id="B">
$("Input[name='A']").val(data);
or
$('#B').val(data);
Both will assign the value of data to the input field
Could someone help me with how to pass an array of values from PHP and retrieve it using AJAX. What i have found is only to pass a single value from PHP. When i try passing the value of an array i dont know how to receive it at the AJAX side
This is my PHP code:
$success[];
$timeout[];
$fail[];
while($row1 = mysql_fetch_array($masterresult))
{
$success[]=$row1[1];
$timeout[]=$row1[2];
$fail[]=$row1[3];
}
echo json_encode(array("a"=>$success,"b"=>$timeout,"c"=>$fail));
And below is by AJAX call:
var channel;
function overall(){
$(".one").show();
$(".two").hide();
$(".three").hide();
$(".four").hide();
window['channel']="overall";
$.ajax({
type:"GET",
url:"dash2.php",
data:{channel:channel},
dataType:'json',
success:function(data){
console.log(data.a);
console.log(data.b);
console.log(data.c);
}
});
}
How should i pass those php array values onto this ajax call? could someone help me with the code
What you want to do is encode it as JSON.
$yourArray = array('asdf', 'qwer', 'zxcv');
echo 'var yourJavaScriptArray = ' . json_encode($yourArray) . ';';
This makes all of your arbitrary data safe for use in JavaScript as well.
If you are only doing this with AJAX, no need for the var part. Just output from json_encode() directly.
Whether it is one value or multiple values in an array for example, you should always use:
json_encode($your_php_var)
json_encode your array on PHP end.
Use that JSON object in JavaScript without any additional effort, its part of JavaScript.
When you send it back to PHP just json_decode it in PHP.
Reference: PHP Manual
Hope this example will help you. Imagine if you have some input data on html form and need to send them by AJAX, do something with them on server side and recive the result on client side and do some stuff with it.
<form id="my_form" method="post" action="<?=$ServerSideUrl?>">
<input type="text" name="field_1" value="">
<input type="text" name="field_2" value="">
<input type="text" name="field_3" value="">
</form>
Here is you AJAX script, i used in this example JQuery
$('#my_form').ajaxSubmit({
dataType: 'html',
error: function() {
alert('some error text');
},
complete: function(data) {
//data this is the result object which returned from server side
//for example you shpold alert the sum of thouse 3 field
alert(data.sum);
}
});
Here is your server side code
<?
$data = array();
$data["sum"] = $_POST["field_1"] + $_POST["field_2"] + $_POST["field_3"];
echo my_json_encode($data);
return true;
?>
So when your AJAX will be complete it alert the sum of three field on your form,
You can use JSON in combination with jQuery for that.
<?php
$myArray = array('a', 'b');
echo json_encode($myArray);
?>
Ajax
$.get('http://localhost/index.php',
function(data) {
var response = jQuery.parseJSON(data);
console.log(response);
}
);
In your code:
var channel;
function overall(){
$(".one").show();
$(".two").hide();
$(".three").hide();
$(".four").hide();
window['channel']="overall";
$.ajax({
type:"GET",
url:"dash2.php",
data:{channel:channel},
dataType:'json',
success:function(data){
console.log(data["a"]);
console.log(data["b"]);
console.log(data["c"]);
}
});
}
I HAVE modified my code, i used firebug console.log to detect weather the the php gets the array passed or not. and firebug displays this - rescheck[]=2&rescheck=1&rescheck=3
I think php gets the array if THATS what an array in php supposed to be like.
SO guys, if thats correct how to insert that array in database? or how to loop it? the foreach loop ive made didnt work.
JQUERY CODE:
$('#res-button').click(function (){
var room_id=$('[name=rescheck[]]:checked').serialize().replace(/%5B%5D/g,'[]');
alert(room_id);
$.ajax({
type: "POST",
url: "reservation-valid.php",
data: {name_r:name_r, email_r:email_r,contact_r:contact_r,prop_id:p_id,cvalue:room_id},
success: function(data) {
console.log(data);
}
});
});
<input type="checkbox" name="rescheck[]" value="<?php echo $roomid; ?>" />
PHP CODE:
$c_array=$_POST['cvalue'];
echo $c_array;
//foreach($c_array as $ch)
//{
//$sql=mysql_query("INSERT INTO reservation VALUES('','$prop_id','$ch','$name_r','$contact_r','$email_r','')");
//}
I think I managed my jquery code to be right, but I don't know how to fetch that with PHP.
room_id is an array, so if you want to get the value for each, you need to get all value together first.
var room_id_string = '';
for(i=0;i<room_id.length;i++){
room_id_string += room_id.eq(i).val() + ',';
}
your below code will only pass Array jquery object of [name=rescheck[]]:checked to room_id
Instead of this you will have to create a array and push values in it like this
var room_id = Array();
$('[name=rescheck[]]:checked').each(function(){
room_id.push($(this).val());
});
In jQuery it might be easier for you to just use the serialize function to get all the form data. jQuery passes the form to the server so you don't have to worry about getting all the values. If you use it in conjunction with the validate plugin you might find it a little easier!
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
This is what I do ibn my site for saving to a db a list of checkboxes with jquery and ajax call. It make an array and pass it to the ajax call and the php script handle the array.
If you get any error here you should debug the js array with firebug for be sure that is formed correctly.
js script:
var $checkBox = $('[name=rescheck[]]:checked');
$checkBox.each(function() {
if ($(this).is(":checked")){
valuesCheck[this.value] = 1;
}else{
valuesCheck[this.value] = 0;
}
and the PHP script:
$checkTab = $_POST['cvalue'];
foreach ($checkTab as $idChkTab => $checkedOrNot){
if ($checkedOrNot== "0"){
//do something if isn't checked
}