Im trying to pass and return an array to and from a php script, I've tested the json_ecode portion and its working but I can't get the json_decode on the php side.
Javascript
scid_list = [];
$('.filter_on').each(function(){scid_list.push($(this).data("scid"));});
$.ajax({
type: "POST",
dataType: "json",
data: {scid_list:scid_list},
url: "/scripts/products_filter.php",
success: function(data){
alert(data.join('\n'));
}
});
PHP
<?php
$scid_list=(json_decode($_POST['scid_list'], true));
echo json_encode($scid_list);
exit();
?>
Ive also tried leaving out the true on decode
$scid_list=(json_decode($_POST['scid_list']);
and not decoding it at all
$scid_list=$_POST['scid_list'];
I'm not sure what I'm missing. I've tried playing around with serializing the data too but read I didn't have to if you specify the dataType as json, I tried using stripslashes
Any help is appreciated!
Cheers
I think the problem is that the data you're sending isn't json even though you're specifying it on the Ajax call. As it's only a 2-dimensional array you're getting, why don't you just use Array.join in your JS before doing the post:
var scids = scid_list.join(',');
That would turn it in to a comma separated string. e.g.
"id1,id2..."
You can simplify the Ajax call a bit too:
$.post('/scripts/products_filter.php', {scids: scids}, function(data) {
// process data response here
});
Then in your PHP file you can use explode() to turn it back in to an array:
$ids = explode(",",$_POST["scids"]);
foreach ($ids as $id) {
// Do something with the array of ids.
};
Hope that all makes sense.
Your dataType parameter specifies that you expect JSON data in response, but it does not mean you are sending data as JSON. In your case you are sending an array, therefor in PHP instead of:
$scid_list=(json_decode($_POST['scid_list'], true)); /* WRONG */
you should simply use:
$scid_list=$_POST['scid_list'];
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String The type of data that you're expecting back from the
server.
Alltogether, for given HTML:
<form action="work.php" method="post">
<p><input class="filter_on" data-scid="22" type="checkbox" /> Filter 22</p>
<p><input class="filter_on" data-scid="28" type="checkbox" /> Filter 28</p>
<p><input class="filter_on" data-scid="31" type="checkbox" /> Filter 31</p>
<p><input type="submit" value="Send" /></p>
</form>
and SCRIPT:
$(document).on('ready', function() {
$('form').on('submit', function(e) {
e.preventDefault();
scid_list = [];
$('.filter_on:checked').each(function(i){
scid_list.push( $(this).data("scid") );
});
$.ajax({
type: "POST",
dataType: "json",
data: {scid_list:scid_list},
url: "work.php",
success: function(data){
alert(data.join('\n'));
}
});
});
});
PHP part is:
$scid_list=$_POST['scid_list'];
echo json_encode($scid_list);
exit();
Related
I try to get post data from using alert() and its worked problem is that data is not passing to php page result is always {"success":false,"result":0}
What I want is send password to php page and hash it using password_hash() and return result
$('#spass').on('submit',function(){
var that=$(this),
contents=that.serialize();
alert(contents);
$.ajax({
url:'passwordhashing.php',
dataType:'json',
data:contents,
success:function(data){
alert(JSON.stringify(data));
console.log(data);
}
});
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="spass" >
<h4>Change Your Password</h4>
<input type='password'name="passc" >
<!--<input type='password' name="cpass" id="cpass"> -->
<input type="submit">
</form>
**this my php code**
<?php
header('Content-type: text/javascript');
$json=array(
'success'=>false,
'result'=>0
);
if(isset($_POST['passc']) && !empty($_POST['passc'])) {
$pass=password_hash($_POST['passc'],PASSWORD_DEFAULT);
$json['success']=true;
$json['result']=$pass;
}
echo json_encode($json);
?>
You can test that your data has not actually been passed to a PHP page.
In the PHP code, do the following: echo $ _POST ['YOUR_VARIABLE'].
Check the INSPECT_ELEMENT / NETWORK browser to make sure you actually send data to the correct link. Your link may be relative, so you may be sending data to the wrong link.
So, try to put the entire link in the ajax url
$ .ajax ({
url: 'HTTP: //WHOLE_LINK_IN_HERE.COM/passwordhashing.php',
});
SET method in Ajax: type: "POST"
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
**i used $.post() instead of using $.ajax() and it fix my problem**
$('#spass').on('submit',function(){
var that=$(this),
contents=that.serialize();
alert(contents);
$.post({
url:'passwordhashing.php',
dataType:'json',
data:contents,
success:function(data){
alert(JSON.stringify(data));
console.log(data);
}
});
return false;
});
First, I do not have much talent in ajax so please consider that while answering. Here I want to get all the values which I inserted into the form in a table before getting submitted but unfortunately am not getting the results I want. So far I have done this. Please have a look.
<script>
var form_data={ agent_name: $('#agent_name').val(),
type: $('input[name="type"]').val(),
number: $('#number').val(),
quantity: $('#quantity').val()
}
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>admin_control/ajax_data',
data: form_data,
dataType:"json", //to parse string into JSON object,
success: function(data){
if(data){
var len = data.length;
alert(len);
var txt = "";
if(len > 0){
for(var i=0;i<len;i++){
if(data[i].agent_name && data[i].type){
txt += $('#table').append('<tr class="item-row"><td><input type="hidden" id="add_type" name="add_type[]" value="super">Super</td><td><input type="hidden" id="add_amount" name="add_amount[]" value="10">745</td><td><input type="hidden" class="add_quantity" id="add_quantity" name="add_quantity[]" value="10">10</td><td name="add_amount" id="add_amount">100</td><td><input type="checkbox" class="add_checkbox" name="layout" id="add_checkbox" value="1" checked></td></tr>');
}
}
if(txt != ""){
$("#table").append(txt).removeClass("hidden");
}
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;
</script>
Here I want to pass the values of form_data in to the table I had written and how can we pass that and did it compulsory to use the url in ajax while using this am getting an error like error: parsererror: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.
Here is my controller
public function ajax_data()
{
$array = array("agent_name" => "admin","number"=>"785","type"=>"super","quantity"=>"10");
$data['json'] = $array;
echo json_encode($data);
}
The Ajax post will call the controller method for post values. The ajax code usually correct but you have not defined url.
url: '',
Firstly define a method (ex: HomeController) then set ajax url parameter like
url: '#Url.Action("Save","Home")' or url: 'Save/Home'
[HttpPost]
public JsonResult Save(string agent_name, string type , int number,int quantity)
{
// return json
}
Note :
The data types you send from the form with the method types must be
the same.
Well, just to give you some hints to work on: The Ajax call could look like this:
$.ajax({
type: 'POST',
url: 'echodata.php',
data: form_data,
dataType:"json",
success: function(data){
$('#table').append('<tr><td>'+data.agent_name+'</td>' // + more columns ...
+'</tr>');}
);
The php script should really be something that processes the incoming information (passed as the $_POST array) into some other data that will ultimately be echoed as JSON string.
This is just a trivial version of echodata.php for testing:
<?php
echo json_encode($_POST);
?>
EDIT:
While you have fixed your URL attribute and have added a "controller" on the server your Ajax success function still expects something it will not get. Your PHP script delivers a JSON string that will be parsed into as a JavaScript object and not an array. The object will not have the length property your success function tries to use. Instead you should be looking for the json property.
So, there is no point for the for loop, instead you can use data.json.agent_name, data.json.number and data.json.type (etc.) properties directly. Your current .append() also only adds a static string to your table. This should of course be changed to use the freshly received values.
I have an ajax call that sends data from serialized checkboxes (among other) to a php file:
$("#button1").click(function(e) {
var category_id = {};
category_id['datumanf'] = $("#datumanf").datepicker().val();
category_id['checkboxvalue'] = $('.checkboxes').serialize();
console.log($('.checkboxes').serialize());
$.ajax({
type: "POST",
url: "allgemein.php
dataType: "html",
data: category_id,
success: function(response) {
$("#resulttable").show().html(response);
}
});
});
The html checkboxes look like this (they contain bits of SQL):
<input type="checkbox" class="checkboxes" name="checkb[]" value="SYSTEM LIKE '%system%'">
When I try to call their name via POST in php like
echo $_POST['checkb'];
it's always empty. I tried variations like $_POST['checkb[1]']; or $_POST['checkb[]']; it's always empty.
However when i call the whole array echo $_POST['checkboxvalues']; I get the same as console.log.
I need the values singularily however. How can I do that?
I'm having some trouble getting my form to submit data to my PHP file.
Without the AJAX script that I have, the form takes the user through to 'xxx.php' and submits the data on the database, however when I include this script, it prevents the page from refreshing, displays the success message, and fades in 'myDiv' but then no data appears in the database.
Any pointers in the right direction would be very much appreciated. Pulling my hair out over this one.
HTML
<form action='xxx.php' id='myForm' method='post'>
<p>Your content</p>
<input type='text' name='content' id='content'/>
<input type='submit' id='subbutton' name='subbutton' value='Submit' />
</form>
<div id='message'></div>
JavaScript
<script>
$(document).ready(function(){
$("#subbutton").click(function(e){
e.preventDefault();
var content = $("#content").attr('value');
$.ajax({
type: "POST",
url: "xxx.php",
data: "content="+content,
success: function(html){
$(".myDiv").fadeTo(500, 1);
},
beforeSend:function(){
$("#message").html("<span style='color:green ! important'>Sending request.</br></br>");
}
});
});
});
</script>
A couple of small changes should get you up and running. First, get the value of the input with .val():
var content = $("#content").val();
You mention that you're checking to see if the submit button isset() but you never send its value to the PHP function. To do that you also need to get its value:
var submit = $('#subbutton').val();
Then, in your AJAX function specify the data correctly:
$.ajax({
type: "POST",
url: "xxx.php",
data: {content:content, subbutton: submit}
...
quotes are not needed on the data attribute names.
On the PHP side you then check for the submit button like this -
if('submit' == $_POST['subbutton']) {
// remainder of your code here
Content will be available in $_POST['content'].
Change the data atribute to
data:{
content:$("#content").val()
}
Also add the atribute error to the ajax with
error:function(e){
console.log(e);
}
And try returning a var dump to $_POST in your php file.
And the most important add to the ajax the dataType atribute according to what You send :
dataType: "text" //text if You try with the var dump o json , whatever.
Another solution would be like :
$.ajax({
type: "POST",
url: "xxxwebpage..ifyouknowhatimean",
data: $("#idForm").serialize(), // serializes the form's elements.
dataType:"text" or "json" // According to what you return in php
success: function(data)
{
console.log(data); // show response from the php script.
}
});
Set the data type like this in your Ajax request: data: { content: content }
I think it isnt a correct JSON format.
So basically i have two files. 1 is my php file and it creates tables with some variables when it's called, and second file is jquery script file that makes that call. My script file:
$.ajax({
type: 'POST',
data: ({p:2,ank : ankieta,wybrane:wybrane}),
url: 'zestawienia_db.php',
success: function(data) {
$('#results').html(data);
}
});
and it works fine by printing my results.
My php file is echoing data that should be printed in my results div.
Question is how to get some PHP data variables and be able to use them in my jquery file without actually echoing them ??
Like i said in my comment to your question, a way to do that is by echoing the variables on a script tag, so you can access in javascript.
<script>
var PHPVariables;
PHPVariables.VariableName1 = '<?=$phpVariableName1?>';
PHPVariables.VariableName2 = '<?=$phpVariableName2?>';
PHPVariables.VariableName3 = '<?=$phpVariableName2?>';
</script>
And you could use those values accessing PHPVariables.VariableName1 on the javascript.
You can do this by echoing all the data you want like so peiceofdata§anotherpeice§onemorepeice§anotherpeice then you can use php's explode function and use § for the "exploding char" this will make an array of all the above data like this somedata[0] = peiceofdata somedata[1] = anotherpeice and so on.
the explode function is used like this
explode('§', $somestringofinfoyouwanttoturnintoanarray);
you can then echo the relevent data like so
echo data[0];
which in this case wiill echo the text peiceofdata.
write this type of code in ajax file
var data =array('name'=>'steve', date=>'18-3-2014');
echo jsonencode(data);
//ajax call in this manner
$.ajax({
type: 'POST',
data: pass data array,
url: ajaxfile url,
success: function(data) {
var data = $.parseJSON(data);
$('#name').html(data.name);
$('#date').html(data.date);
}
});
Use json format, and in this json add your data variables :
PHP :
$arr = array('var1' => $var1, 'var2' => $var2, 'var3' => $var3);
echo json_encode($arr);
Javascript :
$.ajax({
type: 'POST',
data: ({p:2,ank : ankieta,wybrane:wybrane}),
url: 'zestawienia_db.php',
success: function(data) {
data = JSON && JSON.parse(data) || $.parseJSON(data);
$('#results1').html(data.var1);
$('#results2').html(data.var2);
}
});