SQL DELETE not work - javascript

Good morning, everyone,
I have a problem with my script I can't figure out how to make a feature. I'll explain:
I'm using the outlook API I get my mails, send them to my bdd in an inbox table. I then have some buttons that allow to send my mails in other table (to do/ Urgent/Archive).
The problem is that I want to delete the inbox data when I send an email to another table.
I have a view file (I don't put it in I don't think it's useful)
A file with my AJAX request:
window.onload = function(item){
console.log("********************TEST_INSERT*********************");
for($i = 0; $i <= 2; $i++){
console.log("after for");
console.log($i);
$thisInput = document.getElementsByClassName('from_1')[$i].textContent;
$thisSub = document.getElementsByClassName('subject_1')[$i].textContent;
$thisRecei = document.getElementsByClassName('received_1')[$i].textContent;
$thisPreview = document.getElementsByClassName('bodypreview_1')[$i].textContent;
$thisBody_2 = document.getElementsByClassName('body_2')[$i].textContent;
console.log("*********************");
console.log($thisInput);
console.log($thisSub);
console.log($thisRecei);
console.log($thisPreview);
console.log($thisBody_2);
console.log("*********************");
console.log("**********************");
console.log("******STOCK************");
console.log("**********************");
//var $input = $(item).closest(".emailBody").find(".from_1")[0].innerHTML;
//var $sub = $(item).closest(".emailBody").find(".subject_1")[0].innerHTML;
//var $recei = $(item).closest(".emailBody").find(".received_1 em")[0].innerHTML;
//var $preview= $(item).closest(".emailBody").find(".bodypreview_1 em")[0].innerHTML;
//var $body_2 = $(item).closest(".emailBody").find(".body_2 em")[0].innerHTML;
$.ajax({url: '../../wp-content/plugins/game_plugin/process_general.php',
type: 'POST',
data: {info: 'stock_mail_inbox', input: $thisInput, sub: $thisSub, recei: $thisRecei, preview: $thisPreview, body : $thisBody_2},
success: function() {
console.log("OK");
}
});
};
$.ajax({url: '../../wp-content/plugins/game_plugin/process_general.php',
type: 'POST',
dataType: 'html',
data: {info: 'display_mail'},
success: function(html) {
console.log("OKok");
$('#display_mail').html(html);
}
});
};
function btn_a_faire(item){
console.log("**********************");
console.log("******ajax A FAIRE************");
console.log("**********************");
var $thisInput = $(item).closest(".emailBody").find(".from_1")[0].innerHTML;
var $thisSub = $(item).closest(".emailBody").find(".subject_1")[0].innerHTML;
var $thisRecei = $(item).closest(".emailBody").find(".received_1 em")[0].innerHTML;
var $thisPreview = $(item).closest(".emailBody").find(".bodypreview_1 em")[0].innerHTML;
var $thisBody_2 = $(item).closest(".emailBody").find(".body_2 em")[0].innerHTML;
console.log($thisBody_2);
$.ajax({url: '../../wp-content/plugins/game_plugin/process_general_2.php',
type: 'POST',
data: {info: 'insert_to_db_a_faire', input: $thisInput, sub: $thisSub, recei: $thisRecei, preview: $thisPreview, body : $thisBody_2},
success: function() {
console.log("OK");
}
});
};
function btn_urgent(item){
console.log("**********************");
console.log("******ajax URGENT************");
console.log("**********************");
var $thisInput = $(item).closest(".emailBody").find(".from_1")[0].innerHTML;
var $thisSub = $(item).closest(".emailBody").find(".subject_1")[0].innerHTML;
var $thisRecei = $(item).closest(".emailBody").find(".received_1 em")[0].innerHTML;
var $thisPreview = $(item).closest(".emailBody").find(".bodypreview_1 em")[0].innerHTML;
var $thisBody_2 = $(item).closest(".emailBody").find(".body_2 em")[0].innerHTML;
$.ajax({url: '../../wp-content/plugins/game_plugin/process_general_3.php',
type: 'POST',
data: {info: 'insert_to_db', input: $thisInput, sub: $thisSub, recei: $thisRecei, preview: $thisPreview, body : $thisBody_2},
success: function() {
console.log("OK");
}
});
}
function btn_archive(item){
console.log("**********************");
console.log("******ajax URGENT************");
console.log("**********************");
var $thisInput = $(item).closest(".emailBody").find(".from_1")[0].innerHTML;
var $thisSub = $(item).closest(".emailBody").find(".subject_1")[0].innerHTML;
var $thisRecei = $(item).closest(".emailBody").find(".received_1 em")[0].innerHTML;
var $thisPreview = $(item).closest(".emailBody").find(".bodypreview_1 em")[0].innerHTML;
var $thisBody = $(item).closest(".emailBody").find(".body_2 em")[0].innerHTML;
$.ajax({url: '../../wp-content/plugins/game_plugin/process_general_4.php',
type: 'POST',
data: {info: 'insert_to_db_archive', input: $thisInput, sub: $thisSub, recei: $thisRecei, preview: $thisPreview, body : $thisBody_2},
success: function() {
console.log("OK");
}
});
}
And I have 4 files that process INSERTs in my bdd (proccess_general. php/proccess_general_2...):
Proccess_general.php:
$info = $_POST['info'];
$thisInput= $_POST['input'];
$thisRecei= $_POST['recei'];
$thisSub= $_POST['sub'];
$thisPreview= $_POST['preview'];
$thisBody= $_POST['body'];
stock_mail_inbox($thisInput, $thisSub, $thisRecei, $thisPreview, $thisBody);
function stock_mail_inbox($thisInput, $thisSub, $thisRecei, $thisPreview, $thisBody){
global $wpdb;
$wpdb->insert(
'inbox', //table name
array(
'id' => '',
'from_mail' => $thisInput,
'subject' =>$thisSub,
'recei' => $thisRecei,
'preview' =>$thisPreview,
'body' => $thisBody,
), //columns
array(
'%d',
'%s',
'%s',
'%s',
'%s',
'%s',
)
);
}
proccess_general_2.php:
$info = $_POST['info'];
$thisInput= $_POST['input'];
$thisRecei= $_POST['recei'];
$thisSub= $_POST['sub'];
$thisPreview= $_POST['preview'];
$thisBody= $_POST['body'];
insert_to_db_a_faire($thisInput, $thisSub, $thisRecei, $thisPreview, $thisBody);
function insert_to_db_a_faire($thisInput, $thisSub, $thisRecei, $thisPreview, $thisBody){
global $wpdb;
$wpdb->insert(
'a_faire', //table name
array(
'id' => '',
'from_mail' => $thisInput,
'subject' =>$thisSub,
'recei' => $thisRecei,
'preview' =>$thisPreview,
'body' => $thisBody,
), //columns
array(
'%d',
'%s',
'%s',
'%s',
'%s',
'%s',
)
);
$wpdb->prepare('DELETE FROM `inbox` WHERE recei = $thisRecei');
}
In proccess_general_2 I added a DELETE but it doesn't work. When I test my request in phpmyadmin it works but once in my code nothing works.
I hope to have been clear, I remain available if necessary.
Thank you all for a great day.

You should have something like execute( ) after preparing. Try this (or find the equivalent, according to what tools you use)
$wpdb->prepare('DELETE FROM `inbox` WHERE recei = $thisRecei');
$wpdb->execute();

Related

grapesjs how to disable embedAsBase64?

I try to disable grapesjs embedAsBase64 on the image insert without success!
From this :
<img id="irik" data-gjs-type="image" draggable="true"
src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAiIHZpZXdCb3g9IjAgMCAyNCAyNCIgc3R5bGU9ImZpbGw6IHJnYmEoMCwwLDAsMC4xNSk7IHRyYW5zZm9ybTogc2NhbGUoMC43NSkiPgogICAgICAgIDxwYXRoIGQ9Ik04LjUgMTMuNWwyLjUgMyAzLjUtNC41IDQuNSA2SDVtMTYgMVY1YTIgMiAwIDAgMC0yLTJINWMtMS4xIDAtMiAuOS0yIDJ2MTRjMCAxLjEuOSAyIDIgMmgxNGMxLjEgMCAyLS45IDItMnoiPjwvcGF0aD4KICAgICAgPC9zdmc+" class="gjs-plh-image">
To this :
<img id="irik" data-gjs-type="image" draggable="true"
src="https://avatars.githubusercontent.com/u/11614725?s=52&v=4"
class="gjs-plh-image">
this its my code but still not works!! please help!
var editor = grapesjs.init({
height: '100%',
container : '#gjs',
fromElement: true,
showOffsets: true,
embedAsBase64: false,
assetManager: {
storageType : '',
embedAsBase64: false,
// assets: images
custom: true,
},
});
assetManager: {
storageType : '',
storeOnChange : true,
storeAfterUpload : true,
upload: 'images',
assets : [ ],
uploadFile: function(e) {
var files = e.dataTransfer ? e.dataTransfer.files : e.target.files;
var formData = new FormData();
for(var i in files){
formData.append('file-'+i, files[i]) //containing all the selected images from local
}
$.ajax({
url: 'upload_image.php',
type: 'POST',
data: formData,
contentType:false,
crossDomain: true,
dataType: 'json',
mimeType: "multipart/form-data",
processData:false,
success: function(result){
var myJSON = [];
$.each( result['data'], function( key, value ) {
myJSON[key] = value;
});
var images = myJSON;
editor.AssetManager.add(images);
}
});
},
},
upload_image.php:
if($_FILES)
{
$resultArray = array();
foreach ( $_FILES as $file){
$fileName = $file['name'];
$tmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileType = $file['type'];
if ($file['error'] != UPLOAD_ERR_OK)
{
error_log($file['error']);
echo JSON_encode(null);
}
$uploadDir = "../images/";
$targetPath = $uploadDir. $fileName;
move_uploaded_file($tmpName, $targetPath);
$finalDir = "../images/";
$finalPath = $finalDir. $fileName;
$result=array(
'name'=>$fileName,
'type'=>'image',
'src'=>$finalPath,
'height'=>350,
'width'=>250
);
array_push($resultArray, $result);
}
$response = array( 'data' => $resultArray );
echo json_encode($response);
}

How to update image with AJAX in Laravel

I'm having problems updating a record with an image. I don't what I need to do. My image is stored in a public folder called 'img/products'
ProductController.php
This is my controller. It works well without modifying the image.
public function update(Request $request, $id)
{
$validator = Validator::make($request->input(), array(
'name' => 'required',
'category_id' => 'required',
'description' => 'required',
'price_neto' => 'required',
'iva' => 'required',
'price_total' => 'required',
'image' => '',
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
$products = Product::find($id);
$products->name = $request->input('name');
$products->category_id = $request->input('category_id');
$products->description = $request->input('description');
$products->price_neto = $request->input('price_neto');
$products->iva = $request->input('iva');
$products->price_total = $request->input('price_total');
$products->image = $request->input('image');
$products->save();
return response()->json([
'error' => false,
'products' => $products,
], 200);
}
Product.js
All I know is that I have to use var formData = new FormData ($ ("# frmAddProduct") [0]); as in the store function. I can enter records with images but not edit them. My image is stored in a public folder called 'img/products'
$(document).ready(function() {
$("#btn-edit").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'PUT',
url: '/product/' + $("#frmEditProduct input[name=product_id]").val(),
data: {
name: $("#frmEditProduct input[name=name]").val(),
category_id: $("#frmEditProduct select[name=category_id]").val(),
description: $("#frmEditProduct input[name=description]").val(),
price_neto: $("#frmEditProduct input[name=price_neto2]").val(),
iva: $("#frmEditProduct input[name=iva2]").val(),
price_total: $("#frmEditProduct input[name=price_total2]").val(),
image: $("#frmEditProduct input[name=image]").val(),
},
dataType: 'json',
success: function(data) {
$('#frmEditProduct').trigger("reset");
$("#frmEditProduct .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#edit-product-errors').html('');
$.each(errors.messages, function(key, value) {
$('#edit-product-errors').append('<li>' + value + '</li>');
});
$("#edit-error-bag").show();
}
});
});
});
function editProductForm(product_id) {
$.ajax({
type: 'GET',
url: '/product/' + product_id,
success: function(data) {
$("#edit-error-bag").hide();
$("#frmEditProduct input[name=name]").val(data.products.name);
$("#frmEditProduct select[name=category_id]").val(data.products.category_id);
$("#frmEditProduct input[name=description]").val(data.products.description);
$("#frmEditProduct input[name=price_neto2]").val(data.products.price_neto);
$("#frmEditProduct input[name=iva2]").val(data.products.iva);
$("#frmEditProduct input[name=price_total2]").val(data.products.price_total);
$("#frmEditProduct file[name=image]").val(data.products.image);
$("#frmEditProduct input[name=product_id]").val(data.products.id);
$('#editProductModal').modal('show');
},
error: function(data) {
console.log(data);
}
});
}
You should check if the file exists before trying to delete, for example:
$product = Product::find($id);
if(!$product)
{
return response()->json(['error' => 'Product not found'], 404);
}
if (Storage::disk('local')->exists('img/products/'.$product->image)) {
Storage::disk('local')->delete('img/products/'.$product->image);
}
Take a look one example only:
public function update(UpdateProductFormRequest $request, $id)
{
$product = Product::find($id);
$data = $request->only('name','category_id','description',
'price_neto','iva','price_total');
if(!$product)
{
return response()->json(['error' => 'Product not found'], 404);
}
// when saving the file, delete the old file first
if ($request->hasFile('image')) {
$file = $request->file('image');
$original_filename = $file->getClientOriginalName();
// $mime = $file->getMimeType(); // Suggestion
$extention = $file->getExtension();
// $size = $file->getClientSize(); // Suggestion
$stored_filename = $original_filename; // md5($original_filename); // Suggestion
$file_path = storage_path('public/img/products/');
if (Storage::disk('local')
->exists("public/img/products/{$stored_filename}.{$extention}"))
{
Storage::disk('local')
->delete("public/img/products/{$recordSet->stored_filename}.{$extention}");
}
$file_moved = $file->move($file_path, "{$stored_filename}.{$extention}");
$data->image = "{$stored_filename}.{$extention}";
}
// Updating data
$result = $product->update($data);
if ($result) {
/* return redirect()
->route('products.index')
->withSuccess('Product was successfully updated'); */
return response()->json([
'message' => 'Product was successfully updated'
'product' => $product
]); // You don't have to put 200 because it's the default
}
/* return back()
->withErrors(['Unable to update the product'])
->withInput($request->input()); */
return response()->json(['error' => 'Unable to update the product'], 400);
}
It would be better if you create a form request to do your validations.
Don't forget to create links to the storage path:
php artisan storage:link
I think it would be helpful:
$("#btn-edit").click(function() {
var formData = new FormData($("#frmAddProduct")[0]);
formData.append('_method', 'put');
formData.append('_token', "{{ csrf_token() }}"); // if you are using Blade
var route= "{{ route('products.update', ['id' => ':id']) }}"; // if you are using Blade
route= route.replace(':id', $("#frmEditProduct input[name=product_id]").val())
$.ajax({
method: 'post',
url: route,
data: formData,
dataType: 'json',
success: function(data) {
$('#frmEditProduct').trigger("reset");
$("#frmEditProduct .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#edit-product-errors').html('');
$.each(errors.messages, function(key, value) {
$('#edit-product-errors').append('<li>' + value + '</li>');
});
$("#edit-error-bag").show();
}
});
});
Is your js script in "Blade" ? If so, try it this way:
var image = '{{ asset("/img/products/_image_file") }}'
image.replace('_image_file', data.products.image)
$("#frmEditProduct file[name=image]").val(image)
Note that we can first use the "asset ()" helper to create the full path to use to find the image, but with a "_image_file" placeholder
After that, we use the replace () function to change the "_image_file" placeholder with the actual image file brought from the ajax response.
Something like this?
ProductController.php
public function update(Request $request, $id)
{
$validator = Validator::make($request->input(), array(
'name' => 'required',
'category_id' => 'required',
'description' => 'required',
'price_neto' => 'required',
'iva' => 'required',
'price_total' => 'required',
'image' => '',
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
$products = Product::find($id);
if ($request->hasFile('image')) {
$productImage = $request->file('image');
$productImageName = rand() . '.' . $productImage->getClientOriginalExtension();
if (Storage::disk('local')->exists("img/products/{$productImageName}")) {
Storage::disk('local')->delete("img/products/{$recordSet->$productImageName}");
}
$file_moved = $productImage->move(public_path('img/products'), $productImageName);
$data->image = "{$productImageName}";
}
$products->save([
'name' => $request->name,
'category_id' => $request->category_id,
'description' => $request->description,
'price_neto' => $request->price_neto,
'iva' => $request->iva,
'price_total' => $request->price_total,
'image' => $productImageName,
]);
return response()->json([
'error' => false,
'products' => $products,
]);
}
Product.js
$("#btn-edit").click(function() {
var formData = new FormData($("#frmEditProduct")[0]);
formData.append('_method', 'put');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: '/product/' + $("#frmEditProduct input[name=product_id]").val(),
data: formData,
dataType: 'json',
success: function(data) {
$('#frmEditProduct').trigger("reset");
$("#frmEditProduct .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#edit-product-errors').html('');
$.each(errors.messages, function(key, value) {
$('#edit-product-errors').append('<li>' + value + '</li>');
});
$("#edit-error-bag").show();
}
});
});

Ajax response isn't showed on page

My ajax is
$.ajax({
type: 'POST',
url: ajax.ajax,
contentType: false,
processData: false,
dataType: 'JSON',
status: 200,
data: formdata,
success: function(msg){
$('#success_message').fadeIn().html(data);
setTimeout(function() {
$('#success_message').fadeOut("slow");
}, 2000 );
}
});
This is the PHP part
function form(){
global $wpdb;
$table = cars;
foreach ($_FILES as $file) {
if($file['error'] == UPLOAD_ERR_NO_FILE) {
continue;
}
$valid_ext = array( 'img' , 'png');
$extension_upload = strtolower( substr( strrchr($file['name'], '.') ,1) );
if ( in_array($extension_upload,$valid_ext) ) {
$name_upload = uniqid() . $file['name'];
$url_insert = trailingslashit( plugin_dir_path( dirname( __FILE__ ) ) ) . 'uploads';
wp_mkdir_p($url_insert);
$name_insert = trailingslashit($url_insert) . $name_upload;
$action = move_uploaded_file($file['tmp_name'],$name_insert);
$data = array( 'customer_resume' => $name_upload );
$format = array( '%s' );
$success=$wpdb->insert( $table, $data, $format );
$msg_true = 'Upload ok ';
} else {
$msg_error = 'Upload error';
}
}
$result = !isset($msg_error);
$msg = array();
if($result) {
$msg['error'] = 'true';
$msg['true'] = $msg_true;
} else {
$msg['error'] = 'false';
$msg['false'] = $msg_error;
}
header('Content-Type: application/json');
echo json_encode($msg);
}
And the HTML where I try to show the success or error message
<div id="error_message"></div>
<div id="success_message"></div>
When I click on Submit button I everything works fine and saved in database but there is no indication wheather is success or no. I've tried to add this msg's but still nothing shows on page.
PHP side:
You need to print same variable for success and failure:
if($result) {
$msg['error'] = 'true';
$msg['msg'] = $msg_true;
} else {
$msg['error'] = 'false';
$msg['msg'] = $msg_error;
}
JavaScript Side:
The AJAX response will come as
data.error -> true or false.
data.msg -> Success or Error message depending upon program logic.
...
success: function(data){
$('#success_message').fadeIn().html(data.msg);
...
What is hiding behind "ajax.ajax" ?
Also if you want to show your data you need to use "msg"
success: function(msg){
$('#success_message').fadeIn().html(msg);
setTimeout(function() {
$('#success_message').fadeOut("slow");
}, 2000 );
}

my data not update in the database in laravel 5.4

I am using laravel 5.4 in my app I update some record through ajax jquery I get the data from form values through ajax function and append it in array and pass that array (formData in my code) to ajax data then when I request my data in controller it updated as null message in my database.
This is my view jquery function
$('#updateProduct').on('submit', function(e){
e.preventDefault(e);
var redirect_url = $(this).find("[name='redirect_url']").val();
var url = $(this).attr('action');
var method = $(this).attr('method');
var video = document.getElementById('videoToUpload').files[0];
// console.log(video);
var formData = new FormData();
formData.append('_method', 'patch');
formData.append('name', $(this).find("[name='name']").val());
formData.append('description', $(this).find("[name='description']").val());
formData.append('brand', $(this).find("[name='brand']").val());
formData.append('category', $(this).find("[name='category']").val());
formData.append('condition', $(this).find("[name='condition']").val());
formData.append('shipper', $(this).find("[name='shipper']").val());
formData.append('shipping_from', $(this).find("[name='shipping_from']").val());
formData.append('shipping_paid_by', $(this).find("[name='shipping_paid_by']").val());
formData.append('shipping_within', $(this).find("[name='shipping_within']").val());
formData.append('shipping_weight', $(this).find("[name='shipping_weight']").val());
formData.append('shipping_fee', $(this).find("[name='shipping_fee']").val());
formData.append('seller_get', $(this).find("[name='seller_get']").val());
formData.append('price_per_unit', $(this).find("[name='price_per_unit']").val());
formData.append('selling_fee', $(this).find("[name='selling_fee']").val());
formData.append('seller_id', $(this).find("[name='seller_id']").val());
formData.append('is_active', $(this).find("[name='is_active']:checked").val());
console.log(formData);
$.ajax({
type: method,
url: url,
dataType: 'JSON',
data: formData,
contentType: false,
processData: false,
success: function(data){
alert("Products updated successfullly");
console.log(data);
//window.location.href = redirect_url;
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
In my controller
public function update(Request $request, $id)
{
return Response::json([
'message' => $request['name']
], 200);
if(!$request){
return Response::json([
'error' => [
'message' => 'Kindly provide all the required details'
]
], 422);
}
$product = Product::find($id);
$product->name = $request['name'];
$product->sku = $request['sku'];
$product->slug = $request['slug'];
$product->description = $request['description'];
$product->brand = $request['brand'];
$product->condition = $request['condition'];
$product->shipper = $request['shipper'];
$product->shipping_from = $request['shipping_from'];
$product->shipping_fee = $request['shipping_fee'];
$product->shipping_paid_by = $request['shipping_paid_by'];
$product->shipping_within = $request['shipping_within'];
$product->shipping_weight = $request['shipping_weight'];
$product->selling_fee = $request['selling_fee'];
$product->seller_get = $request['seller_get'];
$product->price_per_unit = $request['price_per_unit'];
///$product->seller_id = $request['seller_id'];
$product->is_active = $request['is_active'];
$product->save();
$category = ProductCategory::where('product_id', '=', $id);
$category->update([
'category_id' => $request['category']
]);
return Response::json([
'message' => $product
], 200);
}

(Wordpress / Ajax) ReferenceError: Can't find variable: ajaxobject

I'm working with Wordpress + Ajax and even using the proper hooks I get the error "ReferenceError: Can't find variable: ajaxobject". Of course there is some problem with my ajaxurl but I don't understand where since it seems well done to me. Can you help me?
In my functions.php
add_action( 'wp_enqueue_scripts', 'add_frontend_ajax_javascript_file', 11, 2 );
function add_frontend_ajax_javascript_file()
{
wp_localize_script( 'ajax-script', 'ajaxobject', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
my jQuery/AJAX file
var itemtitle = $('#itemtitle').val();
var itemdescription = $('#itemdescription').val();
jQuery.ajax({
method: 'post',
url : ajaxobject.ajaxurl, //Why???
dataType: "json",
data: {
'action':'update_portfolio_function',
'pid' : id,
'itemtitle' : itemtitle,
'itemdescription' : itemdescription,
},
success:function(data) {
// This outputs the result of the ajax request
alert("Coooool");
},
error: function(errorThrown){
console.log(errorThrown);
}
});
of course the update_portfolio_function looks like
add_action('wp_ajax_update_portfolio', 'update_portfolio_function' );
function update_portfolio_function(){
$id = $_REQUEST['pid'];
$title = $_REQUEST['itemtitle'];
$description = $_REQUEST['itemdescription'];
$attachment = array(
'ID' => $id,
'post_title' => $title,
'post_content' => $description
);
// now update main post body
wp_update_post( $attachment );
die();
}
Should I use init or no_priv?
You just need to use ajaxurl instead of ajaxobject.ajaxurl
like below
jQuery.ajax({
method: 'post',
url : ajaxurl,
dataType: "json",

Categories

Resources