Hi guys this script was working fine when I add a console.log but as soon as I replaced the console.log with the $.ajax() function it wont give me the result back from the php file the ajax function I used was working from my other projects but I cant seem to find out why it wont work on this snippet
Here is my js code :
$(document).ready(function(){
$("#qs").find(".chs").each(function(i,obj){
$(this).addClass("chs"+i);
$(".chs"+i).on("click",function(){
var s = $(this).data("lvs"),carrier= {"vars":s};
$.ajax({
url: aScript.php,
type: "POST",
data: carrier,
dataType: "json"
success: function(data) {
console.log(data) }
});
});
});
});
my php file looks like this
<?php
$json = $_POST['carrier'];
$data = json_decode($json);
$d = $data->vars;
echo $d;
?>
<input type="hidden" id="ss" value="<?=$d?>" />
can someone review this file for me cause I cant seem to find whats wrong please help me find out whats wrong with this script
You should wrap the filename inside quotes, as it is a string variable
$.ajax({
url: 'aScript.php',
type: "POST",
data: carrier,
dataType: "json",
success: function(data) {
console.log(data) }
});
});
There are some issues with your code
in this line url: aScript.php, the url string is not quoted, it should be url: 'aScript.php',
you set dataType: "json" but aScript.php returns html instead of json, remove that line
the data you're passing is not json, it will be serialized into key=value pairs and you'll be able to access it via $d = $_POST['vars'];
Related
This is my ajax code
<script type="text/javascript">
$('#right_make').change(function() {
var make = document.getElementById('right_make').value;
alert(make);
$.ajax({
url: 'get.php',
async: true,
cache: false,
data: {make:make},
dataType: "html",
type:'post',
success: function (result) {
var select = document.getElementById('right_model');
select.insertAdjacentHTML('beforeend', result);
}
});
});
</script>
I am getting data in form of html reverted from backend php ,I want to append this data in select tag ,given below
<select name="model" id="right_model" class="custom-select c_model right_model">
<option value="">Model</option>
</select>
I tried the above thing but it is producing gaps between the options ,
this is what I am appending from backend
<?php
include 'includes/config.php';
include 'includes/database.php';
$make=$_POST['make'];
$stmt=$db->prepare("SELECT distinct `model` FROM `car` WHERE make=?");
$stmt->bind_param("s",$make);
$stmt->execute();
$stmt->bind_result($model);
while ($stmt->fetch()) {
echo "<option>".$model."<option>";
}
?>
Any idea ow to do that?
Generally, if you want to communicate some data with a php server, you may use JSON.
JSON keeps a very sample solution to traduce javascript or php to a very sample string. After, you can traduce JSON to php, Javascript or what else...
You may do this because php do not understand javascript and javascript do not understand php, of course.
When you pass data with your ajax, you may do like this:
$.ajax({
url: 'get.php',
async: true,
cache: false,
data: {make:JSON.stringify (make)}, // Traduce to simply string.
dataType: "html",
type:'post',
success: function (result) {
var select = document.getElementById('right_model');
select.insertAdjacentHTML('beforeend', result);
}
});
Then, when you get the data in your php, you may do like this:
$make=json_decode ($_POST['make']); // Traduce to php.
When you use echo:
echo json_encode ("<option>".$model."<option>");
And finally in your javascript:
success: function (result) {
var select = document.getElementById('right_model');
select.insertAdjacentHTML('beforeend', JSON.parse (result));
}
Consult the documentation.
I am trying to get the contents from some autogenerated divs (with php) and put the contents in a php file for further processing. The reason for that is I have counters that count the number of clicks in each div. Now, I ran into a problem. When I echo back the data from the php file, the call is made, but I get undefined in the form-data section of the headers, and NULL if I do var_dump($_POST). I am almost certain I am doing something wrong with the AJAX call. I am inexperienced to say the least in AJAX or Javascript. Any ideas? The code is pasted below. Thanks for any help / ideas.
The AJAX:
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).find(".test");
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#resultcart").html(returnhtml);
}
});
});
});
The PHP is a simple echo. Please advise.
Suppose you have a div
<div id="send_me">
<div class="sub-item">Hello, please send me via ajax</div>
<span class="sub-item">Hello, please send me also via ajax</span>
</div>
Make AJAX request like
$.ajax({
url: 'get_sorted_content.php',
type: 'POST', // GET is default
data: {
yourData: $('#send_me').html()
// in PHP, use $_POST['yourData']
},
success: function(msg) {
alert('Data returned from PHP: ' + msg);
},
error: function(msg) {
alert('AJAX request failed!' + msg);
}
});
Now in PHP, you can access this data passed in the following manner
<?php
// get_sorted_content.php
if(!empty($_POST['yourdata']))
echo 'data received!';
else
echo 'no data received!';
?>
It's sorted. Thanks to everyone. The problem was I didn't respect the pattern parent -> child of the divs. All I needed to do was to wrap everything in another div. I really didn't know this was happening because I was echoing HTML code from PHP.
I am trying to get a jQuery var into PHP so I can use it with mysql. I have searched everywhere but nothing seemed to solve it.
I have the following jQuery code:
$('.eventRow').click(function(){
var eventID = this.id;
$.ajax(
{
url: "index.php",
type: "POST",
data: { phpEventId: eventID},
success: function (result) {
console.log('success');
}
});
$('#hiddenBox').html(eventID);
console.log(eventID);
});
If I run this, the ID is shown in both #hiddenBox and in the console.log. The console also says "Succes" from the Ajax.
I am trying to get it in the php file:
$value = $_POST['phpEventId'];
echo "<div class = 'showNumber'>"."Nummer: ".$value."</div>";
It just says: Nummer:
It also gives no error whatsoever.
Thanks for your help!
Try
var eventID = $(this).attr('id');
Where this id comes from in your code ?
Passing it as JSON often gets the results I'm looking for. The server will interpret the JSON object as POST variables:
$.ajax({
url: "index.php",
type: "POST",
data: JSON.stringify({phpEventId: eventID}),
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log(result);
}
});
I am trying to use javascript to call a php script which then will return multiple variables back to my javascript so I can manipulate them.
This is my JS.
$.ajax({
url: 'test.php',
data: { id : lastFileId },
success: function(output) {
alert(output);
}
});
my PHP
<?php
$fileId = ($_GET['id']);
$num1 = 1;
$num2 = 2;
?>
From here, how can I return variables $num1 and $num2 so i can use them in my javascript. Is it possible?
also this is a very basic idea of what I have planned to do if I can achieve this.
You can return as many variables as you want with json_encode().
Try in your PHP:
<?php
echo json_encode(array($num1, $num2));
?>
You can add to that array , $num3, $num4, ... and so on.
In your JS, you can access each number as follows.
First, you will need this line of code to parse the encoded JSON string, in your success function.
var result = $.parseJSON(output);
That sets result as a JSON object. Now you can access all fields within result:
result[0] -- $num1 in PHP
result[1] -- $num2 in PHP
You can go for Json in PHP and javascript if you want array in response for a ajax request
PHP Code
<?php
$fileId = isset($_GET['id'])?$_GET['id']:0;
echo json_encode(array("field"=>$fileId,"num1"=>1,"num2"=>2));
?>
Js Code
jQuery.ajax({
type: "GET",
url: 'test.php',
dataType: "json",
success: function(response) {
console.log(response);
alert(response.num1);
}
});
convert json to object
jQuery.ajax({
type: "GET",
url: 'test.php',
dataType: "json",
success: function(response) {
item=JSON.parse(response);
console.log(item);
alert(item.num1);
}
});
Use a simply string and explode(split) it further in ajax response. Here is PHP code
<?php
$fileId = ($_GET['id']);
echo $num1."|".$num2;
?>
Now split(explode) the response with JavaScript
$.ajax({
url: 'test.php',
data: { id : lastFileId },
success: function(output) {
var my_arr = output.split("|");
console.log(my_arr[0] + "" + my_arr[1]);
}
});
you can simply return it like that
return ['num1'=>$num1,'num2' => $num2];
and also, you can access it as followed,
respone.num1
I have the following ajax call.
My addList variable holds a string: list=Sports&list=Cars&list=Outdoor&new_list=123123
I want to grab the addList in my PHP file as
$_POST['list'] is an array with values Sports, Cars, Outdoor
$_POST['new_list'] is a string 123123
But I couldnt convert the POST string into right forms.
I can create arrays/loops in both sides but it didnt feel right.
Whats the convenient way of doing it?
jQuery.ajax({
type: "post",
url: ajax_var.url,
data: "action=post-list&nonce="+ajax_var.nonce+"&post_list=&post_id="+post_id+"&" + addList,
success: function(count){
alert("done");
}
});
Any help will be appreciated. thanks!
try using followig code.
you just neeed to locate your form if and url to pass values to :
var form = new FormData($('#form_id')[0]);
form.append('view_type','addtemplate');
$.ajax({
type: "POST",
url: "savedata.php",
data: form,
cache: false,
contentType: false,
processData: false,
success: function(data){
//alert("---"+data);
alert("Settings has been updated successfully.");
window.location.reload(true);
}
});
this will pass all form element automatically.
Working and tested code.
When you pass variable with the ajax method from jQuery, you can pass array like this :
jQuery
var myArray = newArray();
myArray.push("data1");
myString = "data2";
jQuery.ajax({
type: "post",
url: ajax_var.url,
data: {array:myArray, param2:myString},
^name ^value
success: function(count){
alert("done");
}
});
PHP
echo $_POST['array'][0]; // data1
echo $_POST['param2']; // data2
Change your addList variable to this:
list[]=Sports&list[]=Cars&list[]=Outdoor&new_list=123123
PHP will parse the items named list[] into an array, and you'll find the values as $_POST['list'][0],$_POST['list'][1],$_POST['list'][2]