jquery.ajax with php - php

I have just started working on php. It's a very good lang as I'm feeling but some point I get stuck as I'm new to this.
My javascript code
var pv = $("#txtStart").val();
var av = $("#txtStartNextLevel").val();
var au = $("#fileStartPlay").val();
alert(pv+" "+av+" "+au);
var myau = au.split('\\');
$.ajax({
type:"POST",
url:php_url,
data:"{startPoint:"+pv+"nextLevelPoint:"+av+"audioFile:"+myau[myau.length-1]+"}",
contentType:"application/json",
dataType:"json",
success:function(){
alert("done");
},
error:function(){
alert(response);
}
});
My PHP code.
<?php
if(file_exists("Text.txt"))
{
$fileName = "Text.txt";
$fh = fopen($fileName,"a")
$Starts = $_POST["startPoint"];
$NextLevel = $_POST["nextLevelPoint"];
$AudioFileName = $_POST["audioFile"];
$code .=$Starts."*".$NextLevel."_1*".$AudioFileName."\"";
fwrite($fh,$code);
fclose($fh);
}
?>
When I run this it executes but doesn't write the values in the variable
$Starts,$NextLevel,$AudioFileName**.
And further if I write the same ajax procedure in
$.post(php_url,{startPoint:pv,nextLevelPoint:av,audioFile:myau[myau.length-1]},function(data){});
this works fine and write the content in the file.
Also As I'm using post method it should not display the values in Address bar what I'm passing to write. But it's showing those values in both the method.
localhost://myphp.php?txtStart=Start&fileStartPlay=aceduos.jpg&txtStartNextLevel=adfd
Please guide me where I'm lacking...

Replace the value bellow (with quotas)
"{startPoint:"+pv+"nextLevelPoint:"+av+"audioFile:"+myau[myau.length-1]+"}"
to
{startPoint:pv, nextLevelPoint: av, audioFile: myau[myau.length-1]}

Do what Burak TAMTURK said, and also get rid of
contentType:"application/json",
$_POST data should be in content-type application/x-www-form-urlencoded, which is the default.

Related

php MVC jquery ajax

Im beginner and have just simple PHP MVC for JQUERY SPA, and just wonnt to use Jquery Ajax to
index.php, like front controller calling RouterControler and class AjaxKontroler with registruj() method...using user model to add new user to MySQL..
class AjaxKontroler
{
public function registrovat()
{
if ($_POST)
{
try
{
$spravceUzivatelu = new SpravceUzivatelu();
$spravceUzivatelu->registruj($_POST['email'],$_POST['heslo'],$_POST['hesloZnovu'],$_POST['jmeno'],$_POST['prijmeni'],$_POST['telefon'],$_POST['ulice'],$_POST['mesto'],$_POST['psc'],$_POST['captcha']);
$spravceUzivatelu->prihlas($_POST['email'], $_POST['heslo']);
}
catch (ChybaUzivatele $chyba)
{
$this->pridejZpravu($chyba->getMessage());
}
}
echo "Registrace proběhla úspěšně";
}
Singup form:
$("#dokoncitregistraci").click(function () {
var email = $("#emailreg").val();
var heslo = $("#hesloreg").val();
var hesloznovu = $("#hesloznovureg").val();
var jmeno = $("#jmenoreg").val();
var prijmeni = $("#prijmenireg").val();
var telefon = $("#telefonreg").val();
var ulice = $("#ulicereg").val();
var mesto = $("#mestoreg").val();
var psc = $("#pscreg").val();
var captcha = $("#captcha").val();
console.log("jedu");
$.ajax({
type: "POST",
url: "../ajax/registrovat",
data: {
"email" : email,
"heslo": heslo,
"hesloznovu" : hesloznovu,
"jmeno" :jmeno ,
"prijmeni":prijmeni,
"telefon":telefon,
"ulice":ulice,
"mesto" :mesto,
"psc" : psc,
"captcha" :captcha
},
dataType: "JSON",
success: function(msg){
alert("msg");
}
But all signup inputs are correctly add ti MySQL like new row. I have no success response to work with. Are there some trick to use success response in MVC?
Browser just doesn't make any JS alert(). Sorry abeout using StackOwerflow, its my first question here ane no best practise for it:)
Your code looks fine overall. As far as I know, you don't need the double quotes in "email":email. It can be email:email, but that shouldn't be the problem.
My instinct tells me to double check your ajax url:. Relative urls are tricky, as you have to make them relative to the page running the execution, not what the browser shows. I'd switch to absolute urls like http://www.example.com/ajax/registrovat/ until you are certain what the problem is. The last slash after registrovat is important for differentiating between a controller name and a value.
You can also add an error: function() {} to get more information about what is going on.

javascript image upload via datauri and php base64 decode

I am trying to make an image upload where the JavaScript posts DataURI of an image via AJAX and the PHP receives it to decode it into an image.
The problem is, everything is working fine except that the end product is not an image file.
Please have a look at the following example code.
JavaScript:
dataString='encodedimg='+e.target.result.match(/,(.*)$/)[1]+'&type='+type;
$.ajax({
url: 'uploadhandler_ajax.php',
type: 'POST',
data: dataString,
success: function(data){
//print success message
});
PHP:
$encodedimg = $_POST['encodedimg'];
file_put_contents('asdf.png', base64_decode($encodedimg));
There is no problem with $_POST['encodedimg'] as it produces the right image using online base64 converter. So I am assuming that there is a misuse with file_put_contents() or base64_decode().
Appreciate the help!
To read image on PHP i used a function like this
function rcd($data) {
$p = strpos($data, ',');
$d = base64_decode(substr($data, $p+1));
$rfn = md5(mt_rand(1,123123123));
file_put_contents($rfn, $d, LOCK_EX);
return $rfn;
}
Usage example:
$img_file_name = rcd($_POST['image_data']);
On JS part it is tricky (different browsers, etc). First of all You need to have the image data. Now You do not precise how this is sourced and the code example does not give a hint. We can assume some options
Simple You get dataString properly populated by whatever means neccesary, then Your example should basically work
imgdata = .... // any means of getting the data
$.ajax({
url: 'uploadhandler_ajax.php',
type: 'POST',
image_data: imgdata,
success: function(data){
//print success message
});
Not so simple You have a Canvas object on the screen which was populated by any means and You want to send that data. Whatever above is true, however the way to get image data would be
var canv = document.getElementById('id_of_canvas');
imgdata = canv. toDataURL('image/jpeg', 0.88); // last arg is quality
However, as some browsers (mobiles) might not be so lucky to support this, you might want to find JPEGEncoder for JS and add it, along with the code below, to Your project.
var tdu = HTMLCanvasElement.prototype.toDataURL;
HTMLCanvasElement.prototype.toDataURL = function(type,param1)
{
var res = tdu.apply(this,arguments);
if(res.substr(0,11) != "data:image/")
{
var encoder = new JPEGEncoder();
return encoder.encode(this.getContext("2d").getImageData(0,0,this.width,this.height), (param1 ? param1*100 : 88));
}
else return res;
}
Hope this helps!
FOr #Marcin Gałczyński:
$.ajax({
url: 'uploadhandler_ajax.php',
type: 'POST',
image_data: imgdata,
success: function(data){
//print success message
}
})
I think jQuery.ajax didnt have image_data jQuery.ajax

Using AJAX to send data to Coder Igniter controller function results in a 500 Internal Server Error

I am trying to use AJAX to send data from a Code Igniter view to a controller that will handle the data as needed. I'm gathering the data using a JQuery plugin (Handsontable) and when the user hits the "save" button it extracts the required data from the table and executes the ajax function.
$.ajax({
url: "/survey/save",
data: {"data": data},
type: "POST",
});
I am able to send it to a regular .php file which collects the data with $_POST but not my controller.
public function save() {
$data = $this->input->post('data');
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
for ($i = 0, $size = count($data); $i < $size; ++$i) {
fwrite($fh, $data[$i][0]."\t".$data[$i][1]."\t".$data[$i][2]."\n");
}
fclose($fh);
}
The above code is not what I really want the controller to do but if can successfully execute this code, I will be able to do what I wish.
I have a feeling it has something to do with the URL of the ajax function but I am extremely new to all of these languages and am probably overlooking something simple. Please let me know if I should include any other code!
Hey you have to change in ajax url The format of url must be absolute path for e.g.
In your view the ajax should be like this
$.ajax({
url:'<?php echo site_url('survey/save'); ?>',
type: 'post',
data: "data="+data,
beforeSend:function(){
//before send code for e.g. put a loader
},
success:function(result){
// success result code goes here
},
error:function(jqXHR, status, error){
if(status!='error')
alert(error);
}
});
Now in your controller you can get the data
$data=$this->input->post('data');
and one more thing you have to use relative path when your using fopen for e.g.
//you have used
$myFile = "testFile.txt";
//instead of that you have to use
$myFile="./YOUR_FOLDER_NAME/YOUR_FILE_NAME";
and you can set in your config.php
$config['base_url'] = '';
Answering my own question in case it helps others. The problem was my csrf settings. I realized turning off csrf protection fixed the problem but I didn't want to keep csrf protection off. I think CI may have came out with a whitelist to fix this but I just edited my config file as follows:
if(stripos($_SERVER["REQUEST_URI"],'/survey') === FALSE)
{
$config['csrf_protection'] = TRUE;
}
else
{
$config['csrf_protection'] = FALSE;
}
If you have done your config file in the CI Application/Config folder
$config['base_url'] = 'http://yourwebsite.com/';
then for your url it is
"<?php echo base_url();?>survey/save",
The very simple and easy way try this code:
first you must have set your base_url in application/confiq.php
or with .htaccess
your script:
<script type='text/javascript'>
var base_url = '<?=base_url()?>';
function m_ajax()
{
var ids = $("#all_users").val();
$.ajax({
type:"POST",
url: base_url+"history/home/get_users",
data: "userid=" + ids,
success: function(result){
$("#m_ajax").html(result);
}
});
}
</script>
in your controller you can get the value of userid as post
$userid = $this->input->post('userid');
and you can perform other operations according.

jQuery parse/display json data from php json_encode

Initial .ajax call in jquery:
$.ajax({
type: 'post',
url: 'items_data.php',
data: "id="+id,
dataType: 'json',
success: function(data){
if(data){
make_item_rows(data);
}else{
alert("oops nothing happened :(");
}
}
});
Sends a simple string to a php file which looks like:
header('Content-type: application/json');
require_once('db.php');
if( isset($_POST['id'])){
$id = $_POST['id'];
}else{
echo "Danger Will Robinson Danger!";
}
$items_data = $pdo_db->query ("SELECT blah blah blah with $id...");
$result_array = $items_data->fetchAll();
echo json_encode($result_array);
I am catching the $result_array just fine and passing it on to another function. I double checked that there is indeed proper values being returned as I can just echo result to my page and it displays something like the following:
[{"item_id":"230","0":"230","other_id":"700"},{"item_id":"231","0":"231","other_id":"701"},{"item_id":"232","0":"232","other_id":"702"}]
I am having trouble figuring out how to iterate through the results so I can inject values into a table I have in my HTML. Here is what I have for my function:
function make_item_rows(result_array){
var string_buffer = "";
$.each(jQuery.parseJSON(result_array), function(index, value){
string_buffer += value.item_id; //adding many more eventually
$(string_buffer).appendTo('#items_container');
string_buffer = ""; //reset buffer after writing
});
}
I also tried putting an alert in the $.each function to make sure it was firing 3 times, which it was. However no data comes out of my code. Have tried some other methods as well with no luck.
UPDATE: I changed my code to include the parseJSON, no dice. Got an unexpected token error in my jquery file (right when it attempts to use native json parser). Tried adding the json header to no avail, same error. jquery version 1.9.1. Code as it is now should be reflected above.
Set the dataType:"JSON" and callback in your ajax call.
For example:
$.ajax({
url: "yourphp.php?id="+yourid,
dataType: "JSON",
success: function(json){
//here inside json variable you've the json returned by your PHP
for(var i=0;i<json.length;i++){
$('#items_container').append(json[i].item_id)
}
}
})
Please also consider in your PHP set the JSON content-type. header('Content-type: application/json');
function make_item_rows(result_array){
var string_buffer = "";
var parsed_array=JSON.parse(result_array);
$.each(parsed_array, function(){
string_buffer += parsed_array.item_id;
$(string_buffer).appendTo('#items_container');
string_buffer = "";
});
}
You need to parse it with jQuery.parseJSON
function make_item_rows(result_array){
var string_buffer = "";
$.each(jQuery.parseJSON(result_array), function(index, value){
string_buffer = value.item_id;
$(string_buffer).appendTo('#items_container');
});
}
Try this.
function make_item_rows(result_array){
var string_buffer = "";
$.each(result_array, function(index, value){
value = jQuery.parseJSON(value);
string_buffer += value.item_id;
$(string_buffer).appendTo('#items_container');
string_buffer = "";
});
}
Assuming you already parsed the json response and you have the array. I think the problem is you need to pass a callback to $.each that takes and index and an element param
function make_item_rows(result_array){
$.each(result_array, function(index, element){
document.getElementById("a").innerHTML+=element.item_id;
});
}
(Slightly modified) DEMO
for starters within the $.each you need to access the properties of the instance of object contained within result_array, not result_array itself.
var string_buffer = "";
$.each(result_array, function(index, object){
/* instance is "object"*/
alert( object.item_id);
});
Not entirely sure what you are expecting from this line: $(string_buffer).appendTo('#items_container');
$(string_buffer) does not create a valid jQuery selector since nothing within string_buffer has a prefix for class, tagname or ID, and values from json don't either
If just want the string value of the item_id appended :
$('#items_container').append( object.item_id+'<br/>');
If you are receiving this using jQuery AJAX methods you don't need to use $.parseJSON as other answers suggest, it will already be done for you internally provided you are setting correct dataType for AJAX

jQuery ajax call won't update mysql after pressing back button

I have a form that uses ajax to submit data to a mysql database, then sends the form on to PayPal.
However, after submitting, if I click the back button on my browser, change some fields, and then submit the form again, the mysql data isn't updated, nor is a new entry created.
Here's my Jquery:
$j(".submit").click(function() {
var hasError = false;
var order_id = $j('input[name="custom"]').val();
var order_amount = $j('input[name="amount"]').val();
var service_type = $j('input[name="item_name"]').val();
var order_to = $j('input[name="to"]').val();
var order_from = $j('input[name="from"]').val();
var order_message = $j('textarea#message').val();
if(hasError == false) {
var dataString = 'order_id='+ order_id + '&order_amount=' + order_amount + '&service_type=' + service_type + '&order_to=' + order_to + '&order_from=' + order_from + '&order_message=' + order_message;
$j.ajax({ type: "GET", cache: false, url: "/gc_process.php", data: dataString, success: function() { } });
} else {
return false;
}
});
Here's what my PHP script looks like:
<?php
// Make a MySQL Connection
include('dbconnect.php');
// Get data
$order_id = $_GET['order_id'];
$amount = $_GET['order_amount'];
$type = $_GET['service_type'];
$to = $_GET['order_to'];
$from = $_GET['order_from'];
$message = $_GET['order_message'];
// Insert a row of information into the table
mysql_query("REPLACE INTO gift_certificates (order_id, order_type, amount, order_to, order_from, order_message) VALUES('$order_id', '$type', '$amount', '$to', '$from', '$message')");
mysql_close();
?>
Any ideas?
You really should be using POST instead of GET, but regardless, I would check the following:
That jQuery is executing the ajax call after you click back and change the information, you should probably put either a console.log or an alert calls to see if javascript is failing
Add some echos in the PHP and some exits and go line by line and see how far it gets. Since you have it as a get, you can just load up another tab in your browser and change the information you need to.
if $j in your jQuery is the form you should be able to just do $j.serialize(), it's a handy function to get all the form data in one string
Mate,
Have you enclosed your jquery in
$j(function(){
});
To make sure it is only executed when the dom is ready?
Also, I'm assuming that you've manually gone and renamed jquery from "$" to "$j" to prevent namespace conflicts. If that isn't the case it should be $(function and not $j(function
Anyway apart from that, here are some tips for your code:
Step 1: rename all the "name" fields to be the name you want them to be in your "dataString" object. For example change input[name=from] to have the name "order_from"
Step 2:
Use this code.
$j(function(){
$j(".submit").click(function() {
var hasError = false;
if(hasError == false) {
var dataString = $j('form').serialize();
$j.ajax({ type: "GET", cache: false, url: "/gc_process.php?uu="+Math.random(), data: dataString, success: function() { } });
} else {
return false;
}
});
});
You'll notice i slapped a random variable "uu=random" on the url, this is generally a built in function to jquery, but to make sure it isn't caching the response you can force it using this method.
good luck. If that doesn't work, try the script without renaming jquery on a fresh page. See if that works, you might have some collisions between that and other scripts on the page
Turns out the problem is due to the fact that I am using iframes. I was able to fix the problem by making the page without iframes. Thanks for your help all!

Categories